From d5b6406caebf8c5c5da4f65cff0969585b0995e2 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 22:37:00 +1100 Subject: [PATCH] style: readability pass on delegate-written hooks and models --- src/model/automations.ts | 163 ++++++++++++++-------- src/model/pullRequests.ts | 272 +++++++++++++++++++++++++------------ src/model/workspace.ts | 35 ++++- src/ui/useAttachments.ts | 29 +++- src/ui/usePaletteSearch.ts | 30 +++- src/ui/usePullRequests.ts | 128 ++++++++++++----- src/ui/useThreadFind.ts | 60 ++++++-- src/ui/useThreadLibrary.ts | 176 +++++++++++++++++++----- src/ui/useWorkspace.ts | 260 +++++++++++++++++++++++++---------- 9 files changed, 844 insertions(+), 309 deletions(-) diff --git a/src/model/automations.ts b/src/model/automations.ts index 25abf37..bd31b2b 100644 --- a/src/model/automations.ts +++ b/src/model/automations.ts @@ -47,16 +47,17 @@ export function newAutomationTemplate(projects: readonly OrchestrationProjectShe /** The $EDITOR template for an existing automation, its fields filled in. */ export function automationTemplate(task: ScheduledTask, projects: readonly OrchestrationProjectShell[]): string { const project = projects.find((candidate) => candidate.id === task.projectId); + const strategy = task.workspaceStrategy; return template({ title: task.title, enabled: task.enabled, schedule: scheduleText(task), project: project?.title ?? task.projectId, thread: task.threadId ?? "", - workspace: task.workspaceStrategy.type, - baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main", - startFromOrigin: task.workspaceStrategy.type === "worktree" ? (task.workspaceStrategy.startFromOrigin ?? false) : true, - checkoutPath: task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath : "", + workspace: strategy.type, + baseRef: strategy.type === "worktree" ? strategy.baseRef : "main", + startFromOrigin: strategy.type === "worktree" ? (strategy.startFromOrigin ?? false) : true, + checkoutPath: strategy.type === "existing_worktree" ? strategy.worktreePath : "", model: `${task.modelSelection.instanceId}:${task.modelSelection.model}`, mode: task.runtimeMode, prompt: task.prompt, @@ -107,10 +108,13 @@ function scheduleText(task: ScheduledTask): string { switch (schedule.type) { case "interval": { const minutes = schedule.everyMs / 60_000; - return Number.isInteger(minutes) && minutes % 60 === 0 ? `interval ${minutes / 60}h` : `interval ${Math.max(1, Math.round(minutes))}m`; + const wholeHours = Number.isInteger(minutes) && minutes % 60 === 0; + return wholeHours ? `interval ${minutes / 60}h` : `interval ${Math.max(1, Math.round(minutes))}m`; } case "fixed_time": { - const days = schedule.weekdays && schedule.weekdays.length > 0 && schedule.weekdays.length < 7 ? ` ${schedule.weekdays.map((day) => WEEKDAY_NAMES[day]).join(",")}` : ""; + // No days, or every day, both read as plain "every day at HH:MM". + const weekdayNames = (schedule.weekdays ?? []).map((day) => WEEKDAY_NAMES[day]); + const days = weekdayNames.length > 0 && weekdayNames.length < 7 ? ` ${weekdayNames.join(",")}` : ""; return `fixed ${schedule.timeOfDay}${days}`; } case "webhook": @@ -127,6 +131,58 @@ export type AutomationParse = { readonly ok: true; readonly input: ScheduledTask * its signature, dedupe and filters, as the template says. */ export function parseAutomation(text: string, projects: readonly OrchestrationProjectShell[], existing?: ScheduledTask): AutomationParse { + const { fields, prompt } = readTemplate(text); + const get = (key: string) => fields.get(key) ?? ""; + + const title = get("title"); + const projectText = get("project"); + const byTitle = projects.find((candidate) => candidate.title === projectText); + const project = byTitle ?? projects.find((candidate) => candidate.id === projectText); + const model = parseModel(get("model"), existing?.modelSelection); + if (!title || !prompt || !project || !model) { + return { ok: false, error: "Scheduled task is incomplete: add a title, prompt, project, and model." }; + } + + const schedule = parseSchedule(get("schedule"), existing); + if (!schedule.ok) return schedule; + + const workspace = get("workspace") || "worktree"; + const checkoutPath = get("checkout path"); + if (workspace === "existing_worktree" && !checkoutPath) { + return { ok: false, error: "Checkout path is required: enter the path of the checkout to run in." }; + } + const workspaceStrategy = workspaceStrategyFor(workspace, checkoutPath, get); + if (workspaceStrategy === null) { + return { ok: false, error: `Workspace must be worktree, root, or existing_worktree, not "${workspace}".` }; + } + + const mode = get("mode"); + if (!(RUNTIME_MODES as readonly string[]).includes(mode)) { + return { ok: false, error: `Mode must be one of ${RUNTIME_MODES.join(", ")}, not "${mode}".` }; + } + + const threadId = get("thread"); + return { + ok: true, + input: { + ...(existing ? { id: existing.id, requireExisting: true } : {}), + title, + prompt, + enabled: get("enabled").toLowerCase() !== "false", + schedule: schedule.schedule, + projectId: ProjectId.make(project.id), + threadId: threadId ? ThreadId.make(threadId) : null, + workspaceStrategy, + modelSelection: model, + runtimeMode: mode as RuntimeMode, + interactionMode: existing?.interactionMode ?? "default", + creationSource: "web", + }, + }; +} + +/** The template's `Key: value` lines, plus everything after `Prompt:` as the prompt. */ +function readTemplate(text: string): { fields: Map; prompt: string } { const fields = new Map(); const promptLines: string[] = []; let inPrompt = false; @@ -146,48 +202,29 @@ export function parseAutomation(text: string, projects: readonly OrchestrationPr } fields.set(key, match[2]!.trim()); } - const get = (key: string) => fields.get(key) ?? ""; - const title = get("title"); - const prompt = promptLines.join("\n").trim(); - const projectText = get("project"); - const project = projects.find((candidate) => candidate.title === projectText) ?? projects.find((candidate) => candidate.id === projectText); - const model = parseModel(get("model"), existing?.modelSelection); - if (!title || !prompt || !project || !model) return { ok: false, error: "Scheduled task is incomplete: add a title, prompt, project, and model." }; + return { fields, prompt: promptLines.join("\n").trim() }; +} - const schedule = parseSchedule(get("schedule"), existing); - if (!schedule.ok) return schedule; - - const workspace = get("workspace") || "worktree"; - const checkoutPath = get("checkout path"); - if (workspace === "existing_worktree" && !checkoutPath) return { ok: false, error: "Checkout path is required: enter the path of the checkout to run in." }; - if (workspace !== "root" && workspace !== "worktree" && workspace !== "existing_worktree") return { ok: false, error: `Workspace must be worktree, root, or existing_worktree, not "${workspace}".` }; - - const mode = get("mode"); - if (!(RUNTIME_MODES as readonly string[]).includes(mode)) return { ok: false, error: `Mode must be one of ${RUNTIME_MODES.join(", ")}, not "${mode}".` }; - - const threadId = get("thread"); - return { - ok: true, - input: { - ...(existing ? { id: existing.id, requireExisting: true } : {}), - title, - prompt, - enabled: get("enabled").toLowerCase() !== "false", - schedule: schedule.schedule, - projectId: ProjectId.make(project.id), - threadId: threadId ? ThreadId.make(threadId) : null, - workspaceStrategy: - workspace === "root" - ? { type: "root" } - : workspace === "existing_worktree" - ? { type: "existing_worktree", worktreePath: checkoutPath } - : { type: "worktree", baseRef: get("base ref") || "main", startFromOrigin: get("start from origin").toLowerCase() !== "false" }, - modelSelection: model, - runtimeMode: mode as RuntimeMode, - interactionMode: existing?.interactionMode ?? "default", - creationSource: "web", - }, - }; +/** The workspace a template names, or null when it names none of the three. */ +function workspaceStrategyFor( + workspace: string, + checkoutPath: string, + get: (key: string) => string, +): ScheduledTaskUpsertInput["workspaceStrategy"] | null { + switch (workspace) { + case "root": + return { type: "root" }; + case "existing_worktree": + return { type: "existing_worktree", worktreePath: checkoutPath }; + case "worktree": + return { + type: "worktree", + baseRef: get("base ref") || "main", + startFromOrigin: get("start from origin").toLowerCase() !== "false", + }; + default: + return null; + } } function parseModel(text: string, base?: ModelSelection): ModelSelection | null { @@ -207,32 +244,46 @@ function parseSchedule(text: string, existing?: ScheduledTask): ScheduleParse { const [kind = "", ...rest] = text.trim().split(/\s+/); if (kind === "interval") { const match = /^(\d+)\s*(m|h)?$/.exec(rest.join(" ")); - const everyMs = match ? Number(match[1]) * (match[2] === "h" ? 3_600_000 : 60_000) : Number.NaN; - if (!Number.isSafeInteger(everyMs) || everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS) return { ok: false, error: "Invalid interval: enter an interval of at least one minute." }; + const unitMs = match?.[2] === "h" ? 3_600_000 : 60_000; + const everyMs = match ? Number(match[1]) * unitMs : Number.NaN; + if (!Number.isSafeInteger(everyMs) || everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS) { + return { ok: false, error: "Invalid interval: enter an interval of at least one minute." }; + } return { ok: true, schedule: { type: "interval", everyMs } }; } if (kind === "fixed") { const timeOfDay = rest[0] ?? ""; - if (!/^([01]?\d|2[0-3]):([0-5]\d)$/.test(timeOfDay)) return { ok: false, error: `Invalid schedule: "${text}" — use fixed HH:MM, interval 15m, or webhook.` }; - const days = rest.slice(1).join(" ").split(/[,\s]+/).filter(Boolean); + if (!/^([01]?\d|2[0-3]):([0-5]\d)$/.test(timeOfDay)) { + return { ok: false, error: `Invalid schedule: "${text}" — use fixed HH:MM, interval 15m, or webhook.` }; + } + const dayNames = rest.slice(1).join(" ").split(/[,\s]+/).filter(Boolean); const weekdays: number[] = []; - for (const day of days) { + for (const day of dayNames) { const index = WEEKDAY_BY_NAME.get(day.toLowerCase()); - if (index === undefined) return { ok: false, error: `Unknown weekday "${day}": use ${WEEKDAY_NAMES.join(", ")}.` }; + if (index === undefined) { + return { ok: false, error: `Unknown weekday "${day}": use ${WEEKDAY_NAMES.join(", ")}.` }; + } weekdays.push(index); } - const everyDay = weekdays.length === 0 || new Set(weekdays).size === 7; - return { ok: true, schedule: { type: "fixed_time", timeOfDay, ...(everyDay ? {} : { weekdays: [...new Set(weekdays)].sort((a, b) => a - b) }) } }; + const uniqueWeekdays = [...new Set(weekdays)].sort((a, b) => a - b); + const everyDay = weekdays.length === 0 || uniqueWeekdays.length === 7; + return { + ok: true, + schedule: { type: "fixed_time", timeOfDay, ...(everyDay ? {} : { weekdays: uniqueWeekdays }) }, + }; } if (kind === "webhook") { const current = existing?.schedule.type === "webhook" ? existing.schedule : null; if (!current) return { ok: true, schedule: { type: "webhook", signature: null, dedupe: {} } }; // Filters stay stored when left out; a signature without a secret keeps the stored one. + const signature = current.signature + ? { header: current.signature.header, encoding: current.signature.encoding, prefix: current.signature.prefix } + : null; return { ok: true, schedule: { type: "webhook", - signature: current.signature ? { header: current.signature.header, encoding: current.signature.encoding, prefix: current.signature.prefix } : null, + signature, ...(current.maxDeliveryAgeMinutes !== undefined ? { maxDeliveryAgeMinutes: current.maxDeliveryAgeMinutes } : {}), dedupe: current.dedupe ?? {}, }, diff --git a/src/model/pullRequests.ts b/src/model/pullRequests.ts index 83cf99a..72fc3c2 100644 --- a/src/model/pullRequests.ts +++ b/src/model/pullRequests.ts @@ -77,51 +77,61 @@ export function rankComposerPullRequests(input: { const { projectId, repository, query } = input; const linked = composerPullRequestsFromLinks(input.links ?? [], projectId); const entries = input.result?.entries ?? []; - const exactEntry: PullRequestListEntry[] = input.exact - ? [ - { - provider: input.exact.provider, - host: input.exact.capabilities ? "" : "", - projectId: input.exact.projectId, - projectTitle: input.exact.projectTitle, - repository: input.exact.repository, - number: input.exact.number, - title: input.exact.title, - url: input.exact.url, - author: input.exact.author, - headBranch: input.exact.headBranch, - baseBranch: input.exact.baseBranch, - state: input.exact.state, - isDraft: input.exact.isDraft, - mergeability: input.exact.mergeability, - additions: input.exact.additions, - deletions: input.exact.deletions, - createdAt: input.exact.createdAt, - updatedAt: input.exact.updatedAt, - viewerReviewRequested: false, - labels: input.exact.labels, - }, - ] - : []; + const exactEntry: PullRequestListEntry[] = input.exact ? [listEntryFromDetail(input.exact)] : []; + if (/^\d*$/u.test(query)) { - return filterComposerPullRequestMatches({ + const filtered = filterComposerPullRequestMatches({ entries: [...exactEntry, ...entries], linked, projectId, repository, query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, - }).map(toComposerPullRequest); + }); + return filtered.map(toComposerPullRequest); } - const matches = rankPullRequestMatches( - entries.filter((entry) => { - if (entry.projectId !== projectId || entry.repository.trim().toLowerCase() !== repository.trim().toLowerCase()) return false; - const provider = input.result?.providers.find((candidate) => candidate.host === entry.host); - return provider?.searchesOnHost === true || matchesPullRequestQuery(entry, query); - }), + + const inRepository = entries.filter((entry) => { + if (entry.projectId !== projectId) return false; + if (entry.repository.trim().toLowerCase() !== repository.trim().toLowerCase()) return false; + // Host-searched results already matched on the host; the rest match here. + const provider = input.result?.providers.find((candidate) => candidate.host === entry.host); + return provider?.searchesOnHost === true || matchesPullRequestQuery(entry, query); + }); + const matches = rankPullRequestMatches(inRepository, query); + const ranked = withLinkedComposerPullRequestsFirst({ + matches, + linked, query, - ); - return withLinkedComposerPullRequestsFirst({ matches, linked, query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT }).map(toComposerPullRequest); + limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, + }); + return ranked.map(toComposerPullRequest); +} + +/** A detail reshaped as a list entry, so an exact lookup ranks alongside the recent list. */ +function listEntryFromDetail(detail: PullRequestDetail): PullRequestListEntry { + return { + provider: detail.provider, + host: detail.capabilities ? "" : "", + projectId: detail.projectId, + projectTitle: detail.projectTitle, + repository: detail.repository, + number: detail.number, + title: detail.title, + url: detail.url, + author: detail.author, + headBranch: detail.headBranch, + baseBranch: detail.baseBranch, + state: detail.state, + isDraft: detail.isDraft, + mergeability: detail.mergeability, + additions: detail.additions, + deletions: detail.deletions, + createdAt: detail.createdAt, + updatedAt: detail.updatedAt, + viewerReviewRequested: false, + labels: detail.labels, + }; } function toComposerPullRequest(entry: { @@ -151,7 +161,8 @@ export function exactPullRequestNumber(query: string): number | null { * buildPullRequestReferenceContext + reviewCommentContextRecord build it. */ export function pullRequestContextRecord(meta: PullRequestContextMetadata): { record: ReviewCommentContextRecord; replacement: string } { - const term = (sourceControlClients.findByChangeRequestUrl(meta.url) ?? sourceControlClients.get(undefined)).changeRequest.singular; + const client = sourceControlClients.findByChangeRequestUrl(meta.url) ?? sourceControlClients.get(undefined); + const term = client.changeRequest.singular; const comment = { id: `pr-reference:${meta.url}`, sectionId: `pull-request:${meta.number}`, @@ -189,7 +200,8 @@ export function pullRequestContextRecord(meta: PullRequestContextMetadata): { re diff: "", pullRequest: comment.pullRequest, }; - return { record, replacement: `${formatComposerContextReference({ kind: "review-comment", contextId, label: `#${meta.number}` })} ` }; + const reference = formatComposerContextReference({ kind: "review-comment", contextId, label: `#${meta.number}` }); + return { record, replacement: `${reference} ` }; } function boundedField(value: string): string { @@ -203,16 +215,21 @@ export function resolveLinkInput(input: { readonly project: OrchestrationProjectShell | undefined; readonly projects: readonly OrchestrationProjectShell[]; }): { link: ThreadPullRequestKey & { url: string } } | { error: string } | null { - const resolved = resolveLinkPullRequestInput({ + const hasProject = (reference: { host: string; repository: string; url: string }): boolean => { + const known = input.projects.some((project) => { + const identity = pullRequestLinkProject(project.repositoryIdentity); + if (identity === null) return false; + const sameHost = identity.host === reference.host; + const sameRepository = identity.repository.toLowerCase() === reference.repository.toLowerCase(); + return sameHost && sameRepository; + }); + return known || sourceControlClients.parseChangeRequestUrl(reference.url) !== null; + }; + return resolveLinkPullRequestInput({ reference: input.reference, project: pullRequestLinkProject(input.project?.repositoryIdentity), - hasProject: (reference) => - input.projects.some((project) => { - const identity = pullRequestLinkProject(project.repositoryIdentity); - return identity !== null && identity.host === reference.host && identity.repository.toLowerCase() === reference.repository.toLowerCase(); - }) || sourceControlClients.parseChangeRequestUrl(reference.url) !== null, + hasProject, }); - return resolved; } export type PullRequestLineKind = "title" | "meta" | "body" | "check" | "review" | "comment" | "guide" | "faint"; @@ -223,75 +240,135 @@ export interface PullRequestLine { } /** The PR view's lines: what the web's summary and timeline tabs lead with, in terminal order. */ -export function pullRequestLines(detail: PullRequestDetail, activity: PullRequestActivity | null, guide: PullRequestReviewGuideResult | null, now = Date.now()): PullRequestLine[] { +export function pullRequestLines( + detail: PullRequestDetail, + activity: PullRequestActivity | null, + guide: PullRequestReviewGuideResult | null, + now = Date.now(), +): PullRequestLine[] { const lines: PullRequestLine[] = []; + pushHeaderLines(lines, detail, now); + pushCheckLines(lines, detail); + pushCommentLines(lines, activity, now); + pushCommitLines(lines, activity); + lines.push(...guideLines(guide)); + return lines; +} + +/** Title, state and description: the summary the view leads with. */ +function pushHeaderLines(lines: PullRequestLine[], detail: PullRequestDetail, now: number): void { const state = detail.state === "open" && detail.isDraft ? "draft" : detail.state; + const fileCount = `${detail.changedFiles} ${detail.changedFiles === 1 ? "file" : "files"}`; + const meta = [ + state, + detail.author ? `by ${detail.author.login}` : "", + `${detail.headBranch} → ${detail.baseBranch}`, + `+${detail.additions} −${detail.deletions} · ${fileCount}`, + detail.mergeability !== "unknown" ? detail.mergeability : "", + `updated ${ago(detail.updatedAt, now)}`, + ]; + lines.push({ kind: "title", text: `#${detail.number} ${detail.title}` }); - lines.push({ - kind: "meta", - text: [ - state, - detail.author ? `by ${detail.author.login}` : "", - `${detail.headBranch} → ${detail.baseBranch}`, - `+${detail.additions} −${detail.deletions} · ${detail.changedFiles} ${detail.changedFiles === 1 ? "file" : "files"}`, - detail.mergeability !== "unknown" ? detail.mergeability : "", - `updated ${ago(detail.updatedAt, now)}`, - ] - .filter(Boolean) - .join(" · "), - }); + lines.push({ kind: "meta", text: meta.filter(Boolean).join(" · ") }); lines.push({ kind: "faint", text: detail.url }); - if (detail.labels.length > 0) lines.push({ kind: "meta", text: `Labels: ${detail.labels.map((label) => label.name).join(", ")}` }); - if (detail.reviewers.length > 0) lines.push({ kind: "meta", text: `Reviewers: ${detail.reviewers.map((actor) => actor.login).join(", ")}` }); + + if (detail.labels.length > 0) { + const names = detail.labels.map((label) => label.name); + lines.push({ kind: "meta", text: `Labels: ${names.join(", ")}` }); + } + if (detail.reviewers.length > 0) { + const logins = detail.reviewers.map((actor) => actor.login); + lines.push({ kind: "meta", text: `Reviewers: ${logins.join(", ")}` }); + } if (detail.body.trim()) { lines.push({ kind: "title", text: "Description" }); for (const text of wrapBody(detail.body)) lines.push({ kind: "body", text }); } +} + +/** One line per check, or a note that the host reported none. */ +function pushCheckLines(lines: PullRequestLine[], detail: PullRequestDetail): void { lines.push({ kind: "title", text: `Checks (${detail.checks.length})` }); if (detail.checks.length === 0) lines.push({ kind: "faint", text: "No checks reported." }); for (const check of detail.checks) { - lines.push({ kind: "check", text: `${checkGlyph(check.status)} ${check.name}${check.description ? ` — ${check.description}` : ""}${check.required ? " (required)" : ""}` }); + const description = check.description ? ` — ${check.description}` : ""; + const required = check.required ? " (required)" : ""; + lines.push({ kind: "check", text: `${checkGlyph(check.status)} ${check.name}${description}${required}` }); } +} + +/** Reviews, then the newest comments and review threads, as the timeline tab shows them. */ +function pushCommentLines(lines: PullRequestLine[], activity: PullRequestActivity | null, now: number): void { const reviews = latestReviews(activity); lines.push({ kind: "title", text: "Reviews" }); if (reviews.length === 0) lines.push({ kind: "faint", text: "No reviews yet." }); for (const review of reviews) lines.push({ kind: "review", text: review }); + const comments = activity?.comments ?? []; - lines.push({ kind: "title", text: `Comments (${activity?.commentCount ?? comments.length}${activity?.commentsTruncated ? ", cut short" : ""})` }); + const commentCount = activity?.commentCount ?? comments.length; + const cutShort = activity?.commentsTruncated ? ", cut short" : ""; + lines.push({ kind: "title", text: `Comments (${commentCount}${cutShort})` }); if (comments.length === 0) lines.push({ kind: "faint", text: "No comments yet." }); for (const comment of comments.slice(-20)) { const who = comment.author?.login ?? "ghost"; - const kind = comment.kind === "review" ? `review${comment.reviewState ? ` · ${comment.reviewState}` : ""}` : comment.path ? `on ${comment.path}` : "comment"; - lines.push({ kind: "comment", text: `${who} · ${kind} · ${ago(comment.createdAt, now)}` }); + lines.push({ kind: "comment", text: `${who} · ${commentKindLabel(comment)} · ${ago(comment.createdAt, now)}` }); for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` }); } + const threads = activity?.reviewThreads ?? []; - if (threads.length > 0) { - lines.push({ kind: "title", text: `Review threads (${threads.length})` }); - for (const thread of threads.slice(-20)) { - lines.push({ kind: "comment", text: `${thread.isResolved ? "✓ resolved" : "● open"} ${thread.path}${thread.line ? `:${thread.line}` : ""}` }); - for (const comment of thread.comments.slice(-3)) { - lines.push({ kind: "comment", text: ` ${comment.author?.login ?? "ghost"} · ${ago(comment.createdAt, now)}` }); - for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` }); - } + if (threads.length === 0) return; + lines.push({ kind: "title", text: `Review threads (${threads.length})` }); + for (const thread of threads.slice(-20)) { + const state = thread.isResolved ? "✓ resolved" : "● open"; + const atLine = thread.line ? `:${thread.line}` : ""; + lines.push({ kind: "comment", text: `${state} ${thread.path}${atLine}` }); + for (const comment of thread.comments.slice(-3)) { + const who = comment.author?.login ?? "ghost"; + lines.push({ kind: "comment", text: ` ${who} · ${ago(comment.createdAt, now)}` }); + for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` }); } } +} + +/** What a comment is, in the timeline's words: a review, a note on a file, or plain talk. */ +function commentKindLabel(comment: PullRequestActivity["comments"][number]): string { + if (comment.kind === "review") { + return comment.reviewState ? `review · ${comment.reviewState}` : "review"; + } + if (comment.path) return `on ${comment.path}`; + return "comment"; +} + +/** The newest commits, short hash first as in a log. */ +function pushCommitLines(lines: PullRequestLine[], activity: PullRequestActivity | null): void { const commits = activity?.commits ?? []; - if (commits.length > 0) { - lines.push({ kind: "title", text: `Commits (${commits.length})` }); - for (const commit of commits.slice(-10)) lines.push({ kind: "meta", text: `${commit.oid.slice(0, 7)} ${commit.messageHeadline}` }); + if (commits.length === 0) return; + lines.push({ kind: "title", text: `Commits (${commits.length})` }); + for (const commit of commits.slice(-10)) { + lines.push({ kind: "meta", text: `${commit.oid.slice(0, 7)} ${commit.messageHeadline}` }); } - lines.push(...guideLines(guide)); - return lines; } /** The review guide's lines, or its run state, as the web's guide tab leads with. */ export function guideLines(guide: PullRequestReviewGuideResult | null): PullRequestLine[] { if (!guide) return []; - if (guide.run?._tag === "Running") return [{ kind: "title", text: "Review guide" }, { kind: "guide", text: "Writing the review guide…" }]; - if (guide.run?._tag === "Failed" && !guide.guide) return [{ kind: "title", text: "Review guide" }, { kind: "guide", text: `The review guide failed: ${guide.run.detail}` }]; + if (guide.run?._tag === "Running") { + return [ + { kind: "title", text: "Review guide" }, + { kind: "guide", text: "Writing the review guide…" }, + ]; + } + if (guide.run?._tag === "Failed" && !guide.guide) { + return [ + { kind: "title", text: "Review guide" }, + { kind: "guide", text: `The review guide failed: ${guide.run.detail}` }, + ]; + } if (!guide.guide) return []; - const lines: PullRequestLine[] = [{ kind: "title", text: guide.currentHeadSha && guide.guide.headSha !== guide.currentHeadSha ? "Review guide (out of date)" : "Review guide" }]; + const outOfDate = guide.currentHeadSha && guide.guide.headSha !== guide.currentHeadSha; + const lines: PullRequestLine[] = [ + { kind: "title", text: outOfDate ? "Review guide (out of date)" : "Review guide" }, + ]; for (const stop of guide.guide.stops) { lines.push({ kind: "guide", text: stop.title }); for (const text of wrapBody(stop.summary)) lines.push({ kind: "body", text: ` ${text}` }); @@ -310,9 +387,12 @@ export function latestReviews(activity: PullRequestActivity | null): string[] { if (comment.kind !== "review" || !comment.reviewState) continue; const who = comment.author?.login ?? "ghost"; const held = latest.get(who); - if (!held || comment.createdAt.localeCompare(held.at) >= 0) latest.set(who, { at: comment.createdAt, text: `${who}: ${comment.reviewState}` }); + if (!held || comment.createdAt.localeCompare(held.at) >= 0) { + latest.set(who, { at: comment.createdAt, text: `${who}: ${comment.reviewState}` }); + } } - return [...latest.values()].sort((a, b) => b.at.localeCompare(a.at)).map((entry) => entry.text); + const newestFirst = [...latest.values()].sort((a, b) => b.at.localeCompare(a.at)); + return newestFirst.map((entry) => entry.text); } const ACTION_LABELS: Record = { @@ -337,19 +417,32 @@ export const MERGE_METHOD_LABELS: Record = { /** The runAction actions to offer: what the host can do and the viewer may, for this state. */ export function offeredActions(detail: PullRequestDetail): readonly { action: PullRequestAction; label: string }[] { - const allowed = new Set(detail.capabilities.actions.filter((action) => detail.viewerPermissions.actions.includes(action))); + const allowed = new Set( + detail.capabilities.actions.filter((action) => detail.viewerPermissions.actions.includes(action)), + ); const byState: readonly PullRequestAction[] = detail.state === "merged" ? ["revert", "delete-branch"] : detail.state === "closed" ? ["reopen", "delete-branch"] - : ["merge", detail.isDraft ? "ready" : "draft", "close", "update-branch", detail.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge", "approve-workflows"]; - return byState.filter((action) => allowed.has(action)).map((action) => ({ action, label: ACTION_LABELS[action] })); + : [ + "merge", + detail.isDraft ? "ready" : "draft", + "close", + "update-branch", + detail.autoMergeEnabled ? "disable-auto-merge" : "enable-auto-merge", + "approve-workflows", + ]; + const offered = byState.filter((action) => allowed.has(action)); + return offered.map((action) => ({ action, label: ACTION_LABELS[action] })); } /** Merge methods to offer, from the host's capabilities as the detail reports them. */ export function offeredMergeMethods(detail: PullRequestDetail): readonly PullRequestMergeMethod[] { - return (["merge", "squash", "rebase"] as const).filter((method) => detail.capabilities.mergeMethods.includes(method) && detail.mergeCapabilities[method]); + const methods: readonly PullRequestMergeMethod[] = ["merge", "squash", "rebase"]; + return methods.filter((method) => { + return detail.capabilities.mergeMethods.includes(method) && detail.mergeCapabilities[method]; + }); } function checkGlyph(status: string): string { @@ -370,7 +463,10 @@ function checkGlyph(status: string): string { /** Body text as plain lines: blank runs collapse, very long bodies stop. */ export function wrapBody(body: string, maxLines = 60): string[] { - const lines = body.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd()); + const lines = body + .replace(/\r\n/g, "\n") + .split("\n") + .map((line) => line.trimEnd()); const out: string[] = []; for (const line of lines) { if (line === "" && out.at(-1) === "") continue; diff --git a/src/model/workspace.ts b/src/model/workspace.ts index fad8d78..d2db103 100644 --- a/src/model/workspace.ts +++ b/src/model/workspace.ts @@ -1,14 +1,31 @@ -import { EDITORS, worktreeSetupStageLabel, type EditorId, type TerminalOpenInput, type TerminalSummary, type ThreadId, type WorktreeSetupSnapshot } from "@t3tools/contracts"; +import { + EDITORS, + worktreeSetupStageLabel, + type EditorId, + type TerminalOpenInput, + type TerminalSummary, + type ThreadId, + type WorktreeSetupSnapshot, +} from "@t3tools/contracts"; import { projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; import { nextTerminalId } from "@t3tools/shared/terminalLabels"; export { resolveBranchSelectionTarget } from "../../vendor/t3code/apps/web/src/components/BranchToolbar.logic.ts"; /** Allocate and launch shells with the web's project environment and terminal numbering. */ -export function newTerminalInput(threadId: ThreadId, projectRoot: string, worktreePath: string | null, terminals: readonly TerminalSummary[], metadataLive: boolean): TerminalOpenInput { +export function newTerminalInput( + threadId: ThreadId, + projectRoot: string, + worktreePath: string | null, + terminals: readonly TerminalSummary[], + metadataLive: boolean, +): TerminalOpenInput { + const existingIds = terminals.map((terminal) => terminal.terminalId); + // Without live metadata the next number is unknowable, so fall back to a fresh id. + const terminalId = nextTerminalId(existingIds, metadataLive ? undefined : crypto.randomUUID()); return { threadId, - terminalId: nextTerminalId(terminals.map((terminal) => terminal.terminalId), metadataLive ? undefined : crypto.randomUUID()), + terminalId, cwd: worktreePath ?? projectRoot, worktreePath, env: projectScriptRuntimeEnv({ project: { cwd: projectRoot }, worktreePath }), @@ -23,11 +40,15 @@ export function preferredEditor(available: readonly EditorId[]): EditorId | null /** Show the active preparation stage without hiding failures after setup stops. */ export function worktreeSetupNote(snapshot: WorktreeSetupSnapshot | null): string | null { if (!snapshot || snapshot.phase === "done") return null; - const stage = snapshot.stages.find((stage) => stage.status === "running") ?? snapshot.stages.find((stage) => stage.status === "failed"); - return [ + const running = snapshot.stages.find((stage) => stage.status === "running"); + const failed = snapshot.stages.find((stage) => stage.status === "failed"); + const stage = running ?? failed; + const percent = stage?.percent !== null && stage?.percent !== undefined ? `${stage.percent}%` : null; + const parts = [ `Worktree setup: ${snapshot.phase}`, stage ? worktreeSetupStageLabel(stage.id) : null, - stage?.percent !== null && stage?.percent !== undefined ? `${stage.percent}%` : null, + percent, snapshot.error ?? stage?.detail, - ].filter(Boolean).join(" · "); + ]; + return parts.filter(Boolean).join(" · "); } diff --git a/src/ui/useAttachments.ts b/src/ui/useAttachments.ts index 056fb2f..5fb2976 100644 --- a/src/ui/useAttachments.ts +++ b/src/ui/useAttachments.ts @@ -40,12 +40,27 @@ export function useAttachments(deps: { const [byComposer, setByComposer] = useState>(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; }, }; diff --git a/src/ui/usePaletteSearch.ts b/src/ui/usePaletteSearch.ts index 1559d6b..6ad3db3 100644 --- a/src/ui/usePaletteSearch.ts +++ b/src/ui/usePaletteSearch.ts @@ -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(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, + }; } diff --git a/src/ui/usePullRequests.ts b/src/ui/usePullRequests.ts index b07cafe..6b4bca7 100644 --- a/src/ui/usePullRequests.ts +++ b/src/ui/usePullRequests.ts @@ -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 }); } diff --git a/src/ui/useThreadFind.ts b/src/ui/useThreadFind.ts index 0fca212..e26881a 100644 --- a/src/ui/useThreadFind.ts +++ b/src/ui/useThreadFind.ts @@ -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(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(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, + }; } diff --git a/src/ui/useThreadLibrary.ts b/src/ui/useThreadLibrary.ts index 2e97813..3dfbe4d 100644 --- a/src/ui/useThreadLibrary.ts +++ b/src/ui/useThreadLibrary.ts @@ -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([]); const [cursor, setCursor] = useState(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(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 }; } diff --git a/src/ui/useWorkspace.ts b/src/ui/useWorkspace.ts index ff48233..ca1ab03 100644 --- a/src/ui/useWorkspace.ts +++ b/src/ui/useWorkspace.ts @@ -38,7 +38,10 @@ export function useWorkspace(input: { const activeThread = useRef(thread?.id); activeThread.current = thread?.id; const lastReady = useRef(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) => { 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>) => { + 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); +}