style: readability pass on delegate-written hooks and models

This commit is contained in:
Callum Alpass committed 2026-11-02 22:37:00 +11:00
1 parent a6cfb9a2cd
commit d5b6406cae
9 files changed
+844 -309

No files matched your search

+24 -5
View File
@@ -40,12 +40,27 @@ export function useAttachments(deps: {
const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map());
const pending = byComposer.get(composerKey) ?? [];
const add = (attachment: ChatAttachment) =>
setByComposer((previous) => new Map(previous).set(composerKey, [...(previous.get(composerKey) ?? []), attachment]));
// Lists are replaced whole, per composer, so switching threads never mixes them.
const setPending = (attachments: readonly ChatAttachment[]) => {
setByComposer((previous) => new Map(previous).set(composerKey, attachments));
};
const add = (attachment: ChatAttachment) => {
setByComposer((previous) => {
const current = previous.get(composerKey) ?? [];
return new Map(previous).set(composerKey, [...current, attachment]);
});
};
const upload = (name: string, bytes: Uint8Array, mimeType?: string) => {
if (maxFileBytes === undefined) return say("Still loading the server's attachment limits.", true);
const checked = checkAttachment({ name, sizeBytes: bytes.length, ...(mimeType ? { mimeType } : {}), pending: byComposer.get(composerKey) ?? [], maxFileBytes });
const checked = checkAttachment({
name,
sizeBytes: bytes.length,
...(mimeType ? { mimeType } : {}),
pending: byComposer.get(composerKey) ?? [],
maxFileBytes,
});
if (!checked.ok) return say(checked.error, true);
say(`Uploading ${checked.upload.name}…`);
session.uploadAttachment(checked.upload, bytes).then(
@@ -91,7 +106,11 @@ export function useAttachments(deps: {
};
const remove = (attachment: ChatAttachment) => {
setByComposer((previous) => new Map(previous).set(composerKey, (previous.get(composerKey) ?? []).filter((candidate) => candidate.id !== attachment.id)));
setByComposer((previous) => {
const current = previous.get(composerKey) ?? [];
const kept = current.filter((candidate) => candidate.id !== attachment.id);
return new Map(previous).set(composerKey, kept);
});
session.deleteAttachment(attachment.id).then(
() => say(`Removed ${attachment.name}`),
(error) => say(`Removed ${attachment.name}; deleting the upload failed: ${messageOf(error)}`, true),
@@ -117,7 +136,7 @@ export function useAttachments(deps: {
remove,
take: () => {
const taken = byComposer.get(composerKey) ?? [];
if (taken.length > 0) setByComposer((previous) => new Map(previous).set(composerKey, []));
if (taken.length > 0) setPending([]);
return taken;
},
};
+25 -5
View File
@@ -10,17 +10,37 @@ export function usePaletteSearch(session: T3Session, snapshot: OrchestrationV2Sh
const before = snapshot?.olderSettled?.before;
const [result, setResult] = useState<{ query: string; value: OrchestrationV2SearchThreadsResult } | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
setError(null);
if (!normalized) return;
let cancelled = false;
const timer = setTimeout(() => {
session.searchThreads({ query: normalized, ...(before ? { olderSettledBefore: before, ...(messageSearchTokens(normalized).long.length ? {} : { titlesOnly: true }) } : {}) }).then(
(value) => { if (!cancelled) setResult({ query: normalized, value }); },
(error) => { if (!cancelled) setError(`Could not search messages: ${String(error)}`); },
// Beyond the live shelf a query with no searchable words can only match titles.
const titlesOnly = before ? messageSearchTokens(normalized).long.length === 0 : false;
const search = {
query: normalized,
...(before ? { olderSettledBefore: before, ...(titlesOnly ? { titlesOnly: true } : {}) } : {}),
};
session.searchThreads(search).then(
(value) => {
if (!cancelled) setResult({ query: normalized, value });
},
(searchError) => {
if (!cancelled) setError(`Could not search messages: ${String(searchError)}`);
},
);
}, 120);
return () => { cancelled = true; clearTimeout(timer); };
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [session, normalized, before]);
return { result: normalized && result?.query === normalized ? result.value : null, pending: normalized !== null && result?.query !== normalized && !error, error };
const fresh = normalized !== null && result?.query === normalized;
return {
result: fresh ? result.value : null,
pending: normalized !== null && result?.query !== normalized && !error,
error,
};
}
+95 -33
View File
@@ -93,7 +93,10 @@ export function usePullRequests(deps: PullRequestDeps) {
const load = async (link: ThreadPullRequestLink, reference: PullRequestRef) => {
const token = { link, reference };
try {
const [detail, activity] = await Promise.all([session.pullRequestDetail(reference), session.pullRequestActivity(reference)]);
const [detail, activity] = await Promise.all([
session.pullRequestDetail(reference),
session.pullRequestActivity(reference),
]);
let merged = detail;
if (capabilities?.pullRequestChecks === true) {
const checks = await session.pullRequestChecks(reference).catch(() => null);
@@ -169,7 +172,10 @@ export function usePullRequests(deps: PullRequestDeps) {
const comment = () => {
const current = loadedRef.current;
if (!current?.detail || !current.detail.capabilities.comment || !current.detail.viewerPermissions.comment) return deps.say("Commenting is not available on this pull request.", true);
const canComment = current?.detail?.capabilities.comment && current.detail.viewerPermissions.comment;
if (!current?.detail || !canComment) {
return deps.say("Commenting is not available on this pull request.", true);
}
const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; nothing was posted.", true);
const body = edited.trim();
@@ -191,8 +197,39 @@ export function usePullRequests(deps: PullRequestDeps) {
const current = loadedRef.current;
const detail = current?.detail;
if (!current || !detail) return;
const offered = VERDICTS.filter((verdict) => detail.capabilities.review.verdicts.includes(verdict.value) && detail.viewerPermissions.verdicts.includes(verdict.value));
const offered = VERDICTS.filter((verdict) => {
const hostOffers = detail.capabilities.review.verdicts.includes(verdict.value);
const viewerMay = detail.viewerPermissions.verdicts.includes(verdict.value);
return hostOffers && viewerMay;
});
if (offered.length === 0) return deps.say("Reviewing is not available on this pull request.", true);
const writeReview = (verdict: (typeof VERDICTS)[number]) => {
const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; the review was not submitted.", true);
const body = edited;
const summaryRequired = sourceControlClients.get(detail.provider).reviewSummaryRequired("request-changes");
// Requesting changes can demand a summary; approving never does.
const needsSummary = verdict.value === "request-changes" && summaryRequired;
const canSubmit = needsSummary ? body.trim().length > 0 : verdict.value === "approve" || body.trim().length > 0;
if (!canSubmit) {
const message = needsSummary
? "Summarize your review (required to request changes)."
: "Summarize your review or approve without one.";
return deps.say(message, true);
}
deps.confirm({
title: `${verdict.label} #${detail.number}?`,
...(body.trim() ? { detail: firstLine(body) } : {}),
confirmLabel: "submit review",
run: () =>
deps.run(verdict.sent, async () => {
await session.submitPullRequestReview(current.reference, verdict.value, body);
reloadQuietly();
}),
});
};
deps.openPicker({
placeholder: "Review verdict",
groups: [
@@ -201,25 +238,7 @@ export function usePullRequests(deps: PullRequestDeps) {
items: offered.map((verdict) => ({
id: `verdict:${verdict.value}`,
title: verdict.label,
run: () => {
const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; the review was not submitted.", true);
const body = edited;
const summaryRequired = sourceControlClients.get(detail.provider).reviewSummaryRequired("request-changes");
const canSubmit =
verdict.value === "request-changes" && summaryRequired ? body.trim().length > 0 : verdict.value === "approve" || body.trim().length > 0;
if (!canSubmit) return deps.say(verdict.value === "request-changes" && summaryRequired ? "Summarize your review (required to request changes)." : "Summarize your review or approve without one.", true);
deps.confirm({
title: `${verdict.label} #${detail.number}?`,
...(body.trim() ? { detail: firstLine(body) } : {}),
confirmLabel: "submit review",
run: () =>
deps.run(verdict.sent, async () => {
await session.submitPullRequestReview(current.reference, verdict.value, body);
reloadQuietly();
}),
});
},
run: () => writeReview(verdict),
})),
},
],
@@ -307,7 +326,8 @@ export function usePullRequests(deps: PullRequestDeps) {
const setWatching = (link: ThreadPullRequestLink, watching: boolean) => {
if (!threadShell) return;
deps.run(watching ? "Watching for changes" : "Stopped watching", () => session.watchPullRequest(threadShell.id, linkKey(link), watching));
const label = watching ? "Watching for changes" : "Stopped watching";
deps.run(label, () => session.watchPullRequest(threadShell.id, linkKey(link), watching));
};
const linkDialog = () => {
@@ -324,8 +344,15 @@ export function usePullRequests(deps: PullRequestDeps) {
const resolved = resolveLinkInput({ reference: text, project, projects: deps.projects });
if (resolved === null) return deps.say("Use a pull request URL, 123, or #123.", true);
if ("error" in resolved) return deps.say(resolved.error, true);
const mutation = planThreadPullRequestMutation({ capabilities, threadId: id, reference: resolved.link, linked: true });
if (mutation === null || mutation.type !== "thread.pull-request.link") return deps.say("This environment does not support linking this pull request.", true);
const mutation = planThreadPullRequestMutation({
capabilities,
threadId: id,
reference: resolved.link,
linked: true,
});
if (mutation === null || mutation.type !== "thread.pull-request.link") {
return deps.say("This environment does not support linking this pull request.", true);
}
const { threadId: _threadId, source: _source, url, ...key } = mutation.input;
deps.run(`Linked #${key.number}`, () => session.linkPullRequest(id, key, url));
},
@@ -377,7 +404,9 @@ export function usePullRequests(deps: PullRequestDeps) {
});
};
const watchingCurrent = loaded ? links.some((link) => link.host === loaded.link.host && link.repository === loaded.link.repository && link.number === loaded.link.number && link.watch !== undefined) : false;
const watchingCurrent = loaded
? links.some((link) => isSameLink(link, loaded.link) && link.watch !== undefined)
: false;
const view: PullRequestViewState | null = loaded
? {
@@ -442,7 +471,13 @@ export function usePullRequests(deps: PullRequestDeps) {
}
if (threadShell) {
for (const link of links) {
commands.push({ id: `unlink-pull-request:${link.number}`, title: `${link.source === "stack" ? "Dismiss" : "Unlink"} pull request #${link.number} from thread`, keywords: ["unlink", "pull request", "pr"], run: () => unlink(link) });
const verb = link.source === "stack" ? "Dismiss" : "Unlink";
commands.push({
id: `unlink-pull-request:${link.number}`,
title: `${verb} pull request #${link.number} from thread`,
keywords: ["unlink", "pull request", "pr"],
run: () => unlink(link),
});
if (supportsWatch && (link.snapshot === null || link.snapshot.state === "open")) {
const watching = link.watch !== undefined;
commands.push({
@@ -467,12 +502,19 @@ export function usePullRequests(deps: PullRequestDeps) {
return { view, isOpen: loaded !== null, open, close, handleKey, commands };
}
/** Two links name the same pull request when host, repository and number all match. */
function isSameLink(left: ThreadPullRequestLink, right: ThreadPullRequestLink): boolean {
return left.host === right.host && left.repository === right.repository && left.number === right.number;
}
/** The project's configured merge method, as the web pre-selects it. */
function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) {
return resolveProjectSettings(config.settings, projectId).settings.pullRequestMergeMethod ?? undefined;
}
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
/**
* The composer's `#` search, debounced as the web's (180ms): the recent list (host-searched for
@@ -498,16 +540,36 @@ export function useComposerPullRequests(input: {
const timer = setTimeout(() => {
void (async () => {
try {
const list = await session.pullRequestsList({ state: "all", projectId, limit: COMPOSER_PULL_REQUEST_LIST_LIMIT, ...(textQuery === null ? {} : { query: textQuery }) });
const list = await session.pullRequestsList({
state: "all",
projectId,
limit: COMPOSER_PULL_REQUEST_LIST_LIMIT,
...(textQuery === null ? {} : { query: textQuery }),
});
const number = exactPullRequestNumber(query);
const hasExact =
number !== null &&
list.entries.some((entry) => entry.projectId === projectId && entry.repository.trim().toLowerCase() === repository.trim().toLowerCase() && entry.number === number);
const exact = number !== null && !hasExact ? await session.pullRequestDetail({ projectId, repository, number }).catch(() => null) : null;
list.entries.some((entry) => {
const sameRepository = entry.repository.trim().toLowerCase() === repository.trim().toLowerCase();
return entry.projectId === projectId && sameRepository && entry.number === number;
});
// A typed number names one pull request exactly, so look it up when the list lacks it.
const exact =
number !== null && !hasExact
? await session.pullRequestDetail({ projectId, repository, number }).catch(() => null)
: null;
const exactDetail = exact?.number === number ? exact : null;
if (cancelled) return;
const matches = rankComposerPullRequests({ result: list, exact: exactDetail, links: linksRef.current, projectId, repository, query });
setResult({ key, items: pullRequestItems(matches, repository), failed: list.errors.some((error) => error.projectId === projectId) });
const matches = rankComposerPullRequests({
result: list,
exact: exactDetail,
links: linksRef.current,
projectId,
repository,
query,
});
const failed = list.errors.some((error) => error.projectId === projectId);
setResult({ key, items: pullRequestItems(matches, repository), failed });
} catch {
if (!cancelled) setResult({ key, items: [], failed: true });
}
+48 -12
View File
@@ -11,45 +11,81 @@ export function useThreadFind(session: T3Session, id: ThreadId | undefined, thre
const [index, setIndex] = useState(0);
const [result, setResult] = useState<{ key: string; value: OrchestrationV2SearchThreadResult } | null>(null);
const [error, setError] = useState<string | null>(null);
const normalized = query.trim().slice(0, 200).trim();
const key = open && id && normalized ? JSON.stringify([id, normalized, index]) : null;
// A new tail entry can hold a new match, so it re-runs the search below.
const latestText = thread?.projection?.visibleTurnItems.at(-1);
useEffect(() => { setQuery(""); setIndex(0); }, [id]);
useEffect(() => {
setQuery("");
setIndex(0);
}, [id]);
useEffect(() => {
setError(null);
if (!key || !id) return;
let cancelled = false;
const timer = setTimeout(() => {
session.searchThread({ threadId: id, query: normalized, index }).then(
(value) => { if (!cancelled) setResult({ key, value }); },
(error) => { if (!cancelled) setError(String(error)); },
(value) => {
if (!cancelled) setResult({ key, value });
},
(searchError) => {
if (!cancelled) setError(String(searchError));
},
);
}, 100);
return () => { cancelled = true; clearTimeout(timer); };
return () => {
cancelled = true;
clearTimeout(timer);
};
}, [session, id, key, latestText]);
const data = key && result?.key === key ? result.value : null;
const match = data?.match ?? null;
// Page in older history until the selected match is on screen, once per cursor.
const requested = useRef<string | null>(null);
useEffect(() => {
if (!id || !match || !timeline || timeline.rows.some((row) => row.id === match.entryId)) return;
if (!id || !match || !timeline) return;
if (timeline.rows.some((row) => row.id === match.entryId)) return;
const history = thread?.history;
if (!history?.hasMore || history.loading || history.error) return;
const request = `${key}:${history.cursor}`;
if (requested.current === request) return;
requested.current = request;
session.loadEarlier(id).catch((error) => setError(String(error)));
session.loadEarlier(id).catch((loadError) => setError(String(loadError)));
}, [session, id, match, timeline, thread?.history, key]);
const step = (delta: number) => {
if (data) setIndex(stepThreadFindIndex(data.activeIndex, data.totalMatches, delta));
};
const handleKey = (key: KeyEvent): boolean => {
const handleKey = (keyEvent: KeyEvent): boolean => {
if (!open) return false;
if (key.name === "escape") return true;
else if (key.name === "return") step(key.shift ? -1 : 1);
else if (key.ctrl && key.name === "n") step(1);
else if (key.ctrl && key.name === "p") step(-1);
if (keyEvent.name === "escape") return true;
if (keyEvent.name === "return") step(keyEvent.shift ? -1 : 1);
else if (keyEvent.ctrl && keyEvent.name === "n") step(1);
else if (keyEvent.ctrl && keyEvent.name === "p") step(-1);
else return false;
return true;
};
return { open, query, onQuery: (value: string) => { setQuery(value); setIndex(0); }, data, match, error, pending: key !== null && data === null && !error, step, handleKey };
const onQuery = (value: string) => {
setQuery(value);
setIndex(0);
};
return {
open,
query,
onQuery,
data,
match,
error,
pending: key !== null && data === null && !error,
step,
handleKey,
};
}
+141 -35
View File
@@ -1,5 +1,11 @@
import type { KeyEvent } from "@opentui/core";
import type { OrchestrationV2ArchivedShellSnapshot, OrchestrationV2OlderSettledCursor, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import type {
OrchestrationV2ArchivedShellSnapshot,
OrchestrationV2OlderSettledCursor,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadShell,
ThreadId,
} from "@t3tools/contracts";
import { ThreadId as ThreadIdSchema } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { useEffect, useMemo, useState } from "react";
@@ -10,6 +16,9 @@ import type { PaletteCommand } from "../model/palette.ts";
type Command = PaletteCommand & { readonly run: () => void };
/** How many settled threads one "show more" step reveals, as the web's shelf pages. */
const SETTLED_PAGE_SIZE = 30;
/** The sidebar's fetched shelves live separately from its live shell. */
export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string) {
const [archived, setArchived] = useState(false);
@@ -17,79 +26,176 @@ export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2Sh
const [older, setOlder] = useState<readonly OrchestrationV2ThreadShell[]>([]);
const [cursor, setCursor] = useState<OrchestrationV2OlderSettledCursor | null>(null);
const [end, setEnd] = useState(false);
const [limit, setLimit] = useState(30);
const [limit, setLimit] = useState(SETTLED_PAGE_SIZE);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// A new live cut-off makes every fetched older page stale, so paging starts over.
const cut = snapshot?.olderSettled?.before;
useEffect(() => {
setOlder([]);
setCursor(null);
setEnd(false);
setLimit(30);
setLimit(SETTLED_PAGE_SIZE);
}, [cut]);
const refreshArchive = () => session.archivedThreads().then(setArchive);
useEffect(() => {
if (!archived) { setLoading(false); return; }
if (!archived) {
setLoading(false);
return;
}
let cancelled = false;
setLoading(true);
setError(null);
session.archivedThreads().then(
(value) => { if (!cancelled) { setArchive(value); setLoading(false); } },
(error) => { if (!cancelled) { setError(String(error)); setLoading(false); } },
(value) => {
if (cancelled) return;
setArchive(value);
setLoading(false);
},
(archiveError) => {
if (cancelled) return;
setError(String(archiveError));
setLoading(false);
},
);
return () => { cancelled = true; };
return () => {
cancelled = true;
};
}, [session, archived]);
const merged = useMemo(() => mergeThreadShells(snapshot, older), [snapshot, older]);
const listSnapshot = archived && snapshot ? { ...snapshot, projects: archive?.projects ?? snapshot.projects, threads: archive?.threads ?? [] } : merged;
const allRows = useMemo(() => threadRows(listSnapshot, { query, archived, settledLimit: limit }), [listSnapshot, query, archived, limit]);
const totalSettled = useMemo(() => threadRows(merged, { query, settledLimit: Infinity }).filter((row) => row.section === "settled").length, [merged, query]);
const hasOlder = !archived && (totalSettled > limit || (!end && (snapshot?.olderSettled?.counts.some((count) => count.count > 0) ?? false)));
// The archive keeps the live snapshot's shape so threadRows reads both the same way.
const listSnapshot =
archived && snapshot
? { ...snapshot, projects: archive?.projects ?? snapshot.projects, threads: archive?.threads ?? [] }
: merged;
const allRows = useMemo(
() => threadRows(listSnapshot, { query, archived, settledLimit: limit }),
[listSnapshot, query, archived, limit],
);
const totalSettled = useMemo(() => {
const settled = threadRows(merged, { query, settledLimit: Infinity });
return settled.filter((row) => row.section === "settled").length;
}, [merged, query]);
const serverHasOlder = snapshot?.olderSettled?.counts.some((count) => count.count > 0) ?? false;
const hasOlder = !archived && (totalSettled > limit || (!end && serverHasOlder));
const loadOlder = async () => {
if (loading) return;
setLimit((value) => value + 30);
setLimit((value) => value + SETTLED_PAGE_SIZE);
// Rows already fetched fill the wider limit without another request.
if (!cut || end || totalSettled > limit) return;
setLoading(true);
setError(null);
try {
const page = await session.olderSettledThreads({ before: cursor ?? { settledAt: cut }, limit: 30 });
const page = await session.olderSettledThreads({ before: cursor ?? { settledAt: cut }, limit: SETTLED_PAGE_SIZE });
setOlder((previous) => [...previous, ...page.threads]);
const last = page.threads.at(-1);
if (last?.settledAt) setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id });
setEnd(page.threads.length < 30);
} catch (error) {
setError(String(error));
if (last?.settledAt) {
setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id });
}
setEnd(page.threads.length < SETTLED_PAGE_SIZE);
} catch (loadError) {
setError(String(loadError));
} finally {
setLoading(false);
}
};
const toggle = () => { setError(null); setArchived((value) => !value); };
const toggle = () => {
setError(null);
setArchived((value) => !value);
};
const unarchive = async (id: ThreadId) => {
await session.unarchiveThread(id);
await refreshArchive();
};
const reorder = async (id: ThreadId, delta: 1 | -1) => {
const row = allRows.find((row) => row.thread.id === id);
const row = allRows.find((candidate) => candidate.thread.id === id);
// The web's Working shelf makes Active chronological, not manually reorderable.
if (row?.section === "active") { setError("Active threads are ordered by return time, as in T3 Code's Working shelf."); return; }
const plan = threadReorder(allRows, id, delta, threadRows(listSnapshot, { archived, settledLimit: limit }));
if (row?.section === "active") {
setError("Active threads are ordered by return time, as in T3 Code's Working shelf.");
return;
}
const unfilteredRows = threadRows(listSnapshot, { archived, settledLimit: limit });
const plan = threadReorder(allRows, id, delta, unfilteredRows);
if (!plan || archived) return;
try {
for (const assignment of plan.assignments) await session.reorderThread(ThreadIdSchema.make(assignment.id), plan.section, assignment.orderKey);
} catch (error) { setError(String(error)); }
for (const assignment of plan.assignments) {
await session.reorderThread(ThreadIdSchema.make(assignment.id), plan.section, assignment.orderKey);
}
} catch (reorderError) {
setError(String(reorderError));
}
};
const commands = (id: ThreadId | undefined): Command[] => [
{ id: "archived", title: archived ? "Show active threads" : "Show archived threads", shortcut: "A", keywords: ["archive", "history", "restore"], run: toggle },
...(hasOlder ? [{ id: "older-settled", title: "Show more settled threads", keywords: ["older", "history", "load"], run: () => void loadOlder() }] : []),
...(id && archive?.threads.some((thread) => thread.id === id) ? [{ id: "unarchive", title: "Unarchive thread", keywords: ["restore", "archived"], run: () => void unarchive(id).catch((error) => setError(String(error))) }] : []),
...(id && allRows.some((row) => row.thread.id === id && row.section === "pinned") ? [
{ id: "reorder-up", title: "Move pinned thread up", shortcut: "K", keywords: ["reorder", "sort"], run: () => void reorder(id, -1) },
{ id: "reorder-down", title: "Move pinned thread down", shortcut: "J", keywords: ["reorder", "sort"], run: () => void reorder(id, 1) },
] : []),
];
const key = (key: KeyEvent, id: ThreadId | undefined): boolean => {
if (key.name === "a" && key.shift) return toggle(), true;
if (id && key.shift && (key.name === "j" || key.name === "k")) return void reorder(id, key.name === "j" ? 1 : -1), true;
const commands = (id: ThreadId | undefined): Command[] => {
const list: Command[] = [
{
id: "archived",
title: archived ? "Show active threads" : "Show archived threads",
shortcut: "A",
keywords: ["archive", "history", "restore"],
run: toggle,
},
];
if (hasOlder) {
list.push({
id: "older-settled",
title: "Show more settled threads",
keywords: ["older", "history", "load"],
run: () => void loadOlder(),
});
}
if (id && archive?.threads.some((thread) => thread.id === id)) {
list.push({
id: "unarchive",
title: "Unarchive thread",
keywords: ["restore", "archived"],
run: () => void unarchive(id).catch((unarchiveError) => setError(String(unarchiveError))),
});
}
if (id && allRows.some((row) => row.thread.id === id && row.section === "pinned")) {
list.push(
{
id: "reorder-up",
title: "Move pinned thread up",
shortcut: "K",
keywords: ["reorder", "sort"],
run: () => void reorder(id, -1),
},
{
id: "reorder-down",
title: "Move pinned thread down",
shortcut: "J",
keywords: ["reorder", "sort"],
run: () => void reorder(id, 1),
},
);
}
return list;
};
const key = (keyEvent: KeyEvent, id: ThreadId | undefined): boolean => {
if (keyEvent.name === "a" && keyEvent.shift) {
toggle();
return true;
}
if (id && keyEvent.shift && (keyEvent.name === "j" || keyEvent.name === "k")) {
void reorder(id, keyEvent.name === "j" ? 1 : -1);
return true;
}
return false;
};
return { archived, allRows, merged, archive, commands, key, hasOlder, loadOlder, loading, error };
}
+192 -68
View File
@@ -38,7 +38,10 @@ export function useWorkspace(input: {
const activeThread = useRef(thread?.id);
activeThread.current = thread?.id;
const lastReady = useRef<string | null>(null);
useEffect(() => live ? session.watchTerminals(setTerminals) : undefined, [session, live]);
useEffect(() => {
if (!live) return undefined;
return session.watchTerminals(setTerminals);
}, [session, live]);
useEffect(() => {
setSetup(null);
setSetupError(null);
@@ -48,26 +51,39 @@ export function useWorkspace(input: {
setSetupError(state.status === "error" ? state.error ?? "Could not load worktree setup." : null);
});
}, [session, live, thread?.id]);
useEffect(() => session.watchServerLifecycle((state) => {
const event: ServerLifecycleStreamEvent | null = state.event;
if (event?.type === "ready" && event.payload.at !== lastReady.current) {
// Server restarts and updates are worth a line, but the first "ready" is just startup.
useEffect(() => {
return session.watchServerLifecycle((state) => {
const event: ServerLifecycleStreamEvent | null = state.event;
if (event?.type === "legacyThreadMigration") {
sayRef.current(`Thread migration ${event.payload.status} · ${event.payload.totalThreadCount} threads`);
return;
}
if (event?.type !== "ready" || event.payload.at === lastReady.current) return;
const restarted = lastReady.current !== null;
lastReady.current = event.payload.at;
const outcome = event.payload.updateOutcome;
sayRef.current(outcome
? `Server update ${outcome.targetVersion}: ${outcome.status}${outcome.reason ? ` · ${outcome.reason}` : ""}`
: `Server ${restarted ? "restarted" : "ready"} · ${event.payload.environment.serverVersion}`, outcome !== undefined && outcome.status !== "committed");
} else if (event?.type === "legacyThreadMigration") {
sayRef.current(`Thread migration ${event.payload.status} · ${event.payload.totalThreadCount} threads`);
}
}), [session]);
if (outcome) {
const reason = outcome.reason ? ` · ${outcome.reason}` : "";
sayRef.current(`Server update ${outcome.targetVersion}: ${outcome.status}${reason}`, outcome.status !== "committed");
return;
}
const version = event.payload.environment.serverVersion;
sayRef.current(`Server ${restarted ? "restarted" : "ready"} · ${version}`);
});
}, [session]);
const threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
const cwd = thread?.worktreePath ?? project?.workspaceRoot;
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => {
if (!thread) return;
attachTerminal(renderer, session, { threadId: thread.id, ...terminal, label: resolveTerminalSessionLabel(terminal.terminalId, terminal) }, (message) => {
const target = {
threadId: thread.id,
...terminal,
label: resolveTerminalSessionLabel(terminal.terminalId, terminal),
};
attachTerminal(renderer, session, target, (message) => {
if (message) say(message);
});
};
@@ -81,27 +97,53 @@ export function useWorkspace(input: {
};
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
if (!thread) return;
run(action === "close" ? "Terminal closed" : "Terminal cleared", () => action === "close" ? session.closeTerminal(thread.id, terminal.terminalId) : session.clearTerminal(thread.id, terminal.terminalId));
if (action === "close") {
run("Terminal closed", () => session.closeTerminal(thread.id, terminal.terminalId));
return;
}
run("Terminal cleared", () => session.clearTerminal(thread.id, terminal.terminalId));
};
const terminalItems = (action: "close" | "clear"): PickerItem[] => threadTerminals.map((terminal) => ({
id: `terminal:${action}:${terminal.terminalId}`, title: `${action === "close" ? "Close" : "Clear"} › ${label(terminal)}`,
run: () => terminalMutation(terminal, action),
}));
const terminalItems = (action: "close" | "clear"): PickerItem[] => {
const verb = action === "close" ? "Close" : "Clear";
return threadTerminals.map((terminal) => ({
id: `terminal:${action}:${terminal.terminalId}`,
title: `${verb} › ${label(terminal)}`,
run: () => terminalMutation(terminal, action),
}));
};
// Close/clear appear as one sub-picker each, plus search-only rows so typing finds them.
const terminalActionItems = (): PickerItem[] => {
const items: PickerItem[] = [{ id: "terminal:new", title: "New terminal", run: newTerminal }];
for (const action of ["close", "clear"] as const) {
const targets = terminalItems(action);
if (targets.length === 0) continue;
const verb = action === "close" ? "Close" : "Clear";
items.push({
id: `terminal:${action}`,
title: `${verb} terminal…`,
run: () => openPicker({ placeholder: `${verb} terminal`, groups: [{ label: "Terminals", items: targets }] }),
});
for (const target of targets) items.push({ ...target, searchOnly: true });
}
return items;
};
const terminalPicker = () => {
if (!thread || input.draft) return say("Open a thread first.", true);
openPicker({ placeholder: "Terminals · type close or clear for actions", groups: [
{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:${terminal.terminalId}`, title: label(terminal), hint: terminal.hasRunningSubprocess ? "busy" : terminal.status, run: () => enterTerminal(terminal) })) },
{ label: "Actions", items: [
{ id: "terminal:new", title: "New terminal", run: newTerminal },
...(["close", "clear"] as const).flatMap((action) => {
const items = terminalItems(action);
return items.length ? [
{ id: `terminal:${action}`, title: `${action === "close" ? "Close" : "Clear"} terminal…`, run: () => openPicker({ placeholder: `${action === "close" ? "Close" : "Clear"} terminal`, groups: [{ label: "Terminals", items }] }) },
...items.map((item) => ({ ...item, searchOnly: true })),
] : [];
}),
] },
] });
const openItems = threadTerminals.map((terminal) => ({
id: `terminal:${terminal.terminalId}`,
title: label(terminal),
hint: terminal.hasRunningSubprocess ? "busy" : terminal.status,
run: () => enterTerminal(terminal),
}));
openPicker({
placeholder: "Terminals · type close or clear for actions",
groups: [
{ label: "Terminals", items: openItems },
{ label: "Actions", items: terminalActionItems() },
],
});
};
const openTerminal = () => {
if (!thread || input.draft) return say("Open a thread first.", true);
@@ -113,48 +155,88 @@ export function useWorkspace(input: {
const branchPicker = () => {
if (!thread || !cwd || !project || input.draft) return say("Open a thread with a repository first.", true);
say("Loading refs…");
session.listRefs(cwd).then((refs) => {
if (activeThread.current !== thread.id) return;
const updateWorkspace = (branch: string | null, path: string | null) => session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath);
const promptBranch = (worktree: boolean) => confirm({
session.listRefs(cwd).then(
(refs) => {
if (activeThread.current !== thread.id) return;
openRefPicker(refs);
},
(error) => say(`Could not list refs: ${messageOf(error)}`, true),
);
};
const openRefPicker = (refs: Awaited<ReturnType<T3Session["listRefs"]>>) => {
if (!thread || !cwd || !project) return;
const updateWorkspace = (branch: string | null, path: string | null) =>
session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath);
const promptBranch = (worktree: boolean) =>
confirm({
title: worktree ? "Create a new worktree?" : "Create and switch ref",
detail: worktree ? `Based on ${thread.branch ?? "HEAD"}. The thread will move to the new worktree.` : cwd,
message: { placeholder: "New branch name" }, confirmLabel: "create",
message: { placeholder: "New branch name" },
confirmLabel: "create",
run: (raw) => {
const name = sanitizeNewRefName(raw);
if (!name) return say("Enter a branch name.", true);
run(worktree ? "Worktree created" : "Branch created", async () => {
if (worktree) {
const result = await session.createWorktree(cwd, thread.branch ?? "HEAD", name);
await updateWorkspace(result.worktree.refName, result.worktree.path);
const created = await session.createWorktree(cwd, thread.branch ?? "HEAD", name);
await updateWorkspace(created.worktree.refName, created.worktree.path);
} else {
const result = await session.createRef(cwd, name);
await updateWorkspace(result.refName, thread.worktreePath);
const created = await session.createRef(cwd, name);
await updateWorkspace(created.refName, thread.worktreePath);
}
});
},
});
openPicker({ placeholder: "Select ref", groups: [
{ label: "Refs", items: refs.map((ref) => ({
id: `ref:${ref.isRemote ? "remote:" : ""}${ref.name}`, title: ref.name,
hint: ref.current ? "current" : ref.worktreePath ? "worktree" : ref.isRemote ? "remote" : ref.isDefault ? "default" : "local",
run: () => run("Ref selected", async () => {
const target = resolveBranchSelectionTarget({ activeProjectCwd: project.workspaceRoot, activeWorktreePath: thread.worktreePath, refName: ref });
const result = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name);
await updateWorkspace(ref.isRemote ? result?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name) : ref.name, target.nextWorktreePath);
const selectRef = (ref: (typeof refs)[number]) => {
run("Ref selected", async () => {
const target = resolveBranchSelectionTarget({
activeProjectCwd: project.workspaceRoot,
activeWorktreePath: thread.worktreePath,
refName: ref,
});
const switched = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name);
const branch = ref.isRemote ? (switched?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name)) : ref.name;
await updateWorkspace(branch, target.nextWorktreePath);
});
};
const refItems = refs.map((ref) => ({
id: `ref:${ref.isRemote ? "remote:" : ""}${ref.name}`,
title: ref.name,
hint: refHint(ref),
run: () => selectRef(ref),
}));
const actionItems: PickerItem[] = [
{ id: "branch:create", title: "Create and switch ref…", run: () => promptBranch(false) },
{ id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) },
{ id: "worktree:create", title: "Create worktree…", run: () => promptBranch(true) },
];
if (thread.worktreePath) {
const worktreePath = thread.worktreePath;
actionItems.push({
id: "worktree:remove",
title: "Remove worktree…",
run: () =>
confirm({
title: "Remove this worktree?",
detail: `${worktreePath} · Stops this thread's provider session. Refuses shared worktrees and uncommitted changes.`,
confirmLabel: "remove",
run: () => run("Worktree removed", () => session.removeThreadWorktree(thread.id, project.workspaceRoot, worktreePath)),
}),
})) },
{ label: "Actions", items: [
{ id: "branch:create", title: "Create and switch ref…", run: () => promptBranch(false) },
{ id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) },
{ id: "worktree:create", title: "Create worktree…", run: () => promptBranch(true) },
...(thread.worktreePath ? [{ id: "worktree:remove", title: "Remove worktree…", run: () => confirm({
title: "Remove this worktree?", detail: `${thread.worktreePath} · Stops this thread's provider session. Refuses shared worktrees and uncommitted changes.`, confirmLabel: "remove",
run: () => run("Worktree removed", () => session.removeThreadWorktree(thread.id, project.workspaceRoot, thread.worktreePath!)),
}) }] : []),
] },
] });
}, (error) => say(`Could not list refs: ${messageOf(error)}`, true));
});
}
openPicker({
placeholder: "Select ref",
groups: [
{ label: "Refs", items: refItems },
{ label: "Actions", items: actionItems },
],
});
};
const openInEditor = () => {
@@ -167,11 +249,22 @@ export function useWorkspace(input: {
if (diff.path) return open(resolvePathLinkTarget(diff.path, diff.cwd));
const files = splitPatch(diff.patch ?? "");
if (!files.length) return say("No file to open in this diff.", true);
openPicker({ placeholder: "Open diff file in editor", groups: [{ label: "Files", items: files.map((file) => ({ id: `editor:${file.path}`, title: file.path, run: () => open(resolvePathLinkTarget(file.path, diff.cwd)) })) }] });
const fileItems = files.map((file) => ({
id: `editor:${file.path}`,
title: file.path,
run: () => open(resolvePathLinkTarget(file.path, diff.cwd)),
}));
openPicker({ placeholder: "Open diff file in editor", groups: [{ label: "Files", items: fileItems }] });
};
const cancelSetup = () => {
if (!setup || setup.threadId !== thread?.id || setup.phase !== "running") return;
confirm({ title: "Cancel worktree setup?", detail: "Stops workspace preparation and its setup script.", confirmLabel: "cancel setup", run: () => run("Worktree setup cancellation requested", () => session.cancelWorktreeSetup(setup.threadId)) });
confirm({
title: "Cancel worktree setup?",
detail: "Stops workspace preparation and its setup script.",
confirmLabel: "cancel setup",
run: () => run("Worktree setup cancellation requested", () => session.cancelWorktreeSetup(setup.threadId)),
});
};
const commands: Command[] = thread && !input.draft ? [
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal },
@@ -182,14 +275,45 @@ export function useWorkspace(input: {
{ id: "workspace-editor", title: input.diff ? "Open diff file in editor" : "Open workspace in editor", shortcut: "E", keywords: ["folder", "code", "vscode", "cursor"], run: openInEditor },
...(setup?.threadId === thread.id && setup.phase === "running" ? [{ id: "setup-cancel", title: "Cancel worktree setup…", keywords: ["preparation", "stop"], run: cancelSetup }] : []),
] : [];
const key = (key: KeyEvent): boolean => {
if (key.ctrl || key.meta) return false;
if (key.name === "t" && key.shift) return terminalPicker(), true;
if (key.name === "b" && !key.shift) return branchPicker(), true;
if (key.name === "e" && key.shift) return openInEditor(), true;
const key = (keyEvent: KeyEvent): boolean => {
if (keyEvent.ctrl || keyEvent.meta) return false;
if (keyEvent.name === "t" && keyEvent.shift) {
terminalPicker();
return true;
}
if (keyEvent.name === "b" && !keyEvent.shift) {
branchPicker();
return true;
}
if (keyEvent.name === "e" && keyEvent.shift) {
openInEditor();
return true;
}
return false;
};
return { commands, key, openTerminal, note: input.draft ? null : setupError ?? worktreeSetupNote(setup?.threadId === thread?.id ? setup : null), setupFailed: setup?.phase === "failed" || setupError !== null };
// Setup belongs to one thread; another thread's snapshot is not this one's note.
const setupForThread = setup?.threadId === thread?.id ? setup : null;
const note = input.draft ? null : (setupError ?? worktreeSetupNote(setupForThread));
return {
commands,
key,
openTerminal,
note,
setupFailed: setup?.phase === "failed" || setupError !== null,
};
}
const messageOf = (error: unknown) => error instanceof Error ? error.message : String(error);
/** Why a ref matters at a glance, in the web branch picker's order of importance. */
function refHint(ref: { readonly current: boolean; readonly worktreePath: string | null; readonly isRemote?: boolean | undefined; readonly isDefault: boolean }): string {
if (ref.current) return "current";
if (ref.worktreePath) return "worktree";
if (ref.isRemote) return "remote";
if (ref.isDefault) return "default";
return "local";
}
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}