From a6cfb9a2cdc00de4118ffe5854fce4b846dd8515 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 22:29:31 +1100 Subject: [PATCH 1/3] ui: share truncate and firstLine from text.ts --- src/ui/ComposerMenu.tsx | 6 +----- src/ui/DetailsPanel.tsx | 6 +----- src/ui/QueuePanel.tsx | 6 +----- src/ui/ThreadList.tsx | 6 +----- src/ui/ThreadView.tsx | 6 +----- src/ui/text.ts | 13 +++++++++++++ src/ui/usePullRequests.ts | 6 +----- test/text.test.ts | 28 ++++++++++++++++++++++++++++ 8 files changed, 47 insertions(+), 30 deletions(-) create mode 100644 src/ui/text.ts create mode 100644 test/text.test.ts diff --git a/src/ui/ComposerMenu.tsx b/src/ui/ComposerMenu.tsx index 23ff9dc..cd7b288 100644 --- a/src/ui/ComposerMenu.tsx +++ b/src/ui/ComposerMenu.tsx @@ -1,5 +1,6 @@ import type { ComposerItem } from "../model/composerMenu.ts"; import { ClickRow } from "./Button.tsx"; +import { truncate } from "./text.ts"; import { colors } from "./theme.ts"; const MAX_ROWS = 8; @@ -34,8 +35,3 @@ export function ComposerMenu(props: { readonly items: readonly ComposerItem[]; r ); } - -function truncate(text: string, width: number): string { - const single = text.replace(/\s+/g, " "); - return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; -} diff --git a/src/ui/DetailsPanel.tsx b/src/ui/DetailsPanel.tsx index 94cfe0a..e002414 100644 --- a/src/ui/DetailsPanel.tsx +++ b/src/ui/DetailsPanel.tsx @@ -2,6 +2,7 @@ import type { ReactNode } from "react"; import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts"; import { ClickRow } from "./Button.tsx"; +import { truncate } from "./text.ts"; import { colors, statusColor } from "./theme.ts"; /** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */ @@ -214,11 +215,6 @@ function countsText(insertions: number, deletions: number): string { return [insertions > 0 ? `+${insertions}` : "", deletions > 0 ? `−${deletions}` : ""].filter(Boolean).join(" "); } -function truncate(text: string, width: number): string { - const single = text.replace(/\s+/g, " "); - return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; -} - /** Keeps the end of a path, where the file name is, as the web's StartTruncatedPath does. */ function startTruncate(text: string, width: number): string { return text.length > width ? `…${text.slice(text.length - width + 1)}` : text; diff --git a/src/ui/QueuePanel.tsx b/src/ui/QueuePanel.tsx index f717805..f2690d0 100644 --- a/src/ui/QueuePanel.tsx +++ b/src/ui/QueuePanel.tsx @@ -2,6 +2,7 @@ import type { MouseEvent } from "@opentui/core"; import type { QueuedMessage } from "../model/queue.ts"; import { Button, Buttons, isLeftClick, useHover } from "./Button.tsx"; +import { truncate } from "./text.ts"; import { colors } from "./theme.ts"; export interface QueueActions { @@ -42,11 +43,6 @@ export function QueuePanel(props: { readonly queued: readonly QueuedMessage[]; r ); } -function truncate(text: string, width: number): string { - const single = text.replace(/\s+/g, " ").trim(); - return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; -} - function QueueRow(props: { readonly text: string; readonly width: number; readonly focused: boolean; readonly editing: boolean; readonly index: number; readonly actions: QueueActions }) { const { index, actions } = props; const [hover, hoverProps] = useHover(); diff --git a/src/ui/ThreadList.tsx b/src/ui/ThreadList.tsx index 33f1951..c4181e8 100644 --- a/src/ui/ThreadList.tsx +++ b/src/ui/ThreadList.tsx @@ -4,6 +4,7 @@ import type { ThreadId } from "@t3tools/contracts"; import { useEffect, useState } from "react"; import { ClickRow, wheelStep } from "./Button.tsx"; +import { truncate } from "./text.ts"; import { colors, statusColor } from "./theme.ts"; /** @@ -125,8 +126,3 @@ function SectionHeader({ label }: { readonly label: string }) { ); } - -function truncate(text: string, width: number): string { - const single = text.replace(/\s+/g, " "); - return single.length > width ? `${single.slice(0, Math.max(0, width - 1))}…` : single; -} diff --git a/src/ui/ThreadView.tsx b/src/ui/ThreadView.tsx index ca0a727..0043c24 100644 --- a/src/ui/ThreadView.tsx +++ b/src/ui/ThreadView.tsx @@ -13,6 +13,7 @@ import { CommandOutput } from "./CommandOutput.tsx"; import type { T3Session, ThreadHistory } from "../client/session.ts"; import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; import { blockFor } from "../model/transcript.ts"; +import { firstLine } from "./text.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; /** What a right-click in the conversation was on. */ @@ -337,8 +338,3 @@ function glyphFor(entry: WorkLogEntry): string { if (entry.itemType === "todo_list") return "☐"; return "·"; } - -function firstLine(text: string): string { - const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " "); - return line.length > 200 ? `${line.slice(0, 197)}…` : line; -} diff --git a/src/ui/text.ts b/src/ui/text.ts new file mode 100644 index 0000000..efcb66c --- /dev/null +++ b/src/ui/text.ts @@ -0,0 +1,13 @@ +/** Collapses text to one line and clips it to `width`, so a label never wraps its row. */ +export function truncate(text: string, width: number): string { + const single = text.replace(/\s+/g, " "); + if (single.length <= width) return single; + return `${single.slice(0, Math.max(0, width - 1))}…`; +} + +/** Takes the first line only, so multi-line text can stand in for a short label. */ +export function firstLine(text: string): string { + const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " "); + if (line.length <= 100) return line; + return `${line.slice(0, 99)}…`; +} diff --git a/src/ui/usePullRequests.ts b/src/ui/usePullRequests.ts index 90d70ae..b07cafe 100644 --- a/src/ui/usePullRequests.ts +++ b/src/ui/usePullRequests.ts @@ -38,6 +38,7 @@ import { } from "../model/pullRequests.ts"; import type { Confirmation } from "./ConfirmBar.tsx"; import { editInEditor } from "./editor.ts"; +import { firstLine } from "./text.ts"; import type { PullRequestViewState } from "./PullRequestView.tsx"; export interface PullRequestDeps { @@ -473,11 +474,6 @@ function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) { const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); -function firstLine(text: string): string { - const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " "); - return line.length > 100 ? `${line.slice(0, 99)}…` : line; -} - /** * The composer's `#` search, debounced as the web's (180ms): the recent list (host-searched for * words), plus the exact pull request a typed number names when the list lacks it. diff --git a/test/text.test.ts b/test/text.test.ts new file mode 100644 index 0000000..1ee69da --- /dev/null +++ b/test/text.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, test } from "bun:test"; + +import { firstLine, truncate } from "../src/ui/text.ts"; + +describe("truncate", () => { + test("collapses whitespace and clips with an ellipsis", () => { + expect(truncate("a b\nc", 10)).toBe("a b c"); + expect(truncate("abcdef", 4)).toBe("abc…"); + expect(truncate("abcdef", 0)).toBe("…"); + }); + + test("keeps leading whitespace collapsed to one space", () => { + // The majority of the old copies did not trim; only QueuePanel's did. + expect(truncate(" hi", 10)).toBe(" hi"); + }); +}); + +describe("firstLine", () => { + test("takes the first trimmed line, collapsed", () => { + expect(firstLine(" hello world\nsecond line")).toBe("hello world"); + expect(firstLine("")).toBe(""); + }); + + test("caps at 100 characters", () => { + const long = "x".repeat(150); + expect(firstLine(long)).toBe(`${"x".repeat(99)}…`); + }); +}); From d5b6406caebf8c5c5da4f65cff0969585b0995e2 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 22:37:00 +1100 Subject: [PATCH 2/3] 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); +} From 441d9d6ed396d4dbb411738b7bdad2f9657617b7 Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 22:40:44 +1100 Subject: [PATCH 3/3] lint: add Biome (lint only) and fix its findings --- biome.json | 36 ++++++++++++++++++++++++++++++++++++ bun.lock | 19 +++++++++++++++++++ package.json | 2 ++ src/bin.ts | 9 ++++++--- src/client/session.ts | 5 ++++- src/model/details.ts | 2 +- src/model/diffs.ts | 2 +- src/ui/terminalOut.ts | 1 + src/ui/useQueue.ts | 33 ++++++++++++++++++++++++--------- src/ui/useSecretRequest.ts | 10 ++++++++-- test/commands.test.ts | 14 ++++++++++++-- test/diffs.test.ts | 5 ++++- test/pullRequests.test.ts | 5 ++++- test/workspace.test.ts | 4 +++- 14 files changed, 125 insertions(+), 22 deletions(-) create mode 100644 biome.json diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..ea8dc90 --- /dev/null +++ b/biome.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json", + "formatter": { + "enabled": false + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true, + "a11y": "off", + "correctness": { + "useExhaustiveDependencies": "off" + }, + "style": { + "noNonNullAssertion": "off" + }, + "suspicious": { + "noArrayIndexKey": "off" + } + } + }, + "overrides": [ + { + "includes": [ + "src/ui/App.tsx", + "src/model/hints.ts", + "src/ui/HintBar.tsx", + "src/ui/Palette.tsx", + "src/model/palette.ts" + ], + "linter": { + "enabled": false + } + } + ] +} diff --git a/bun.lock b/bun.lock index c8c515b..17961d1 100644 --- a/bun.lock +++ b/bun.lock @@ -16,6 +16,7 @@ "zustand": "5.0.11", }, "devDependencies": { + "@biomejs/biome": "2.5.15", "@noble/hashes": "1.8.0", "@types/bun": "latest", "@types/react": "^19.3.0", @@ -25,6 +26,24 @@ }, }, "packages": { + "@biomejs/biome": ["@biomejs/biome@2.5.15", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.5.15", "@biomejs/cli-darwin-x64": "2.5.15", "@biomejs/cli-linux-arm64": "2.5.15", "@biomejs/cli-linux-arm64-musl": "2.5.15", "@biomejs/cli-linux-x64": "2.5.15", "@biomejs/cli-linux-x64-musl": "2.5.15", "@biomejs/cli-win32-arm64": "2.5.15", "@biomejs/cli-win32-x64": "2.5.15" }, "bin": { "biome": "bin/biome" } }, "sha512-WZTW4slm/pdkh92K6t/3aEN++44JD1PQ7squ7RCMLI1flHGl43DVOIGXvCjHiZgBMO1V4uYxoFNtqrIA4qGuIQ=="], + + "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.5.15", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BZVzFhJ/mUvTLMYbc9x6el0o2Uv5zP7bACYyhFb6fSc1giroXm7PL0a5KqMJ9F+/BnkYRjagD/ROSDVOZ6eapg=="], + + "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.5.15", "", { "os": "darwin", "cpu": "x64" }, "sha512-V5Kw63V+fVGNFhFrizDxMbGXAzZCh8kYzJpy3GI6gTapWDg7bZK9oYC9CbVgQSEdTnupz0U5Efz8Ev+5vdBBXw=="], + + "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.5.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-XaG7P7eeSLYETD3K9grfB0mQmpLQZjygdbsxekWBJAg4am79fGAtRpfRyNnTvXB2fZFNnJZG3nXm7HBat0+VUw=="], + + "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.5.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-tGzZUTcJCV7tj5Adh/Gn6nR4MycqA3iohq2LEcrarAgRBkU0h0OKd2UzCRkOsOYOuUGaUJb4YmqRqyy2feGGSw=="], + + "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.5.15", "", { "os": "linux", "cpu": "x64" }, "sha512-xE4iEW/3LqlYj9GFgGrFsFSH51dEEpUbYWBfeOv0q87WkUDxK2o/HhreSb7qMJqck70RVM6Lg96hgedcAYcOkA=="], + + "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.5.15", "", { "os": "linux", "cpu": "x64" }, "sha512-IlxUcyxilVGPsE008x13pWdkTbU3nQpP2i9b5UrbOYj6goBkKsRX1XB7yJLcV+O1H9LBchIIm4adOaVLZBX0ZQ=="], + + "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.5.15", "", { "os": "win32", "cpu": "arm64" }, "sha512-2kPKzhNlm8C+Ru3GcO0Me2ODkCBLrVOUNuyi84RJyWDVKAA4+Kjj3jMjL938lF6BRfvltC4vB2nPY9SvN51Ovg=="], + + "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.5.15", "", { "os": "win32", "cpu": "x64" }, "sha512-yAzh4UqEImV6Hcy0zjUqNfJAsUhoD64FBQCdTG8Md/Z2wQeVP/ZmJ3XRYAs1g8J9fjTFyl2fCtc5FB5til47+g=="], + "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], "@opentui/core": ["@opentui/core@0.2.7", "", { "dependencies": { "bun-ffi-structs": "0.2.2", "diff": "9.0.0", "marked": "17.0.1", "string-width": "7.2.0", "strip-ansi": "7.1.2", "yoga-layout": "3.2.1" }, "optionalDependencies": { "@opentui/core-darwin-arm64": "0.2.7", "@opentui/core-darwin-x64": "0.2.7", "@opentui/core-linux-arm64": "0.2.7", "@opentui/core-linux-x64": "0.2.7", "@opentui/core-win32-arm64": "0.2.7", "@opentui/core-win32-x64": "0.2.7" }, "peerDependencies": { "web-tree-sitter": "0.25.10" } }, "sha512-cnN6JcaGC7SeQzobBy/CHzqUAQFtypazuw1CjQBo7WwoOiLMGubt9W5FXeF0zIrSxH2Ed6NLWhPYRg7SD4629Q=="], diff --git a/package.json b/package.json index 2258e44..ec2a363 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "scripts": { "dev": "bun run src/bin.ts", "typecheck": "tsc --noEmit", + "lint": "biome lint src test", "test": "bun test", "postinstall": "bun run scripts/link-vendor.ts" }, @@ -24,6 +25,7 @@ "zustand": "5.0.11" }, "devDependencies": { + "@biomejs/biome": "2.5.15", "@noble/hashes": "1.8.0", "@types/bun": "latest", "@types/react": "^19.3.0", diff --git a/src/bin.ts b/src/bin.ts index a25dbf2..2bf8426 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -1,5 +1,5 @@ #!/usr/bin/env bun -import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; +import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts"; import { T3Session } from "./client/session.ts"; import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.ts"; @@ -88,7 +88,10 @@ async function tmuxCommand(args: string[]) { let pending = false; let syncing = false; const sync = async () => { - if (syncing) return void (pending = true); + if (syncing) { + pending = true; + return; + } syncing = true; try { const latest = session.getShell().snapshot; @@ -115,7 +118,7 @@ async function tmuxCommand(args: string[]) { async function runUi(attachNeedle?: string) { const { session, snapshot } = await connectedSession(); - let attachThreadId; + let attachThreadId: ThreadId | undefined; if (attachNeedle) { const thread = findThread(snapshot, attachNeedle); if (!thread) { diff --git a/src/client/session.ts b/src/client/session.ts index 3262de3..116301e 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -365,7 +365,10 @@ export class T3Session { watchCommandOutput(threadId: ThreadId, itemId: TurnItemId, listener: Listener, onError: Listener): () => void { let view = EMPTY_COMMAND_OUTPUT; const fiber = this.runInScope(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]({ threadId, itemId }).pipe( - Stream.runForEach((frame) => Effect.sync(() => listener(view = applyCommandOutputFrame(view, frame)))), + Stream.runForEach((frame) => Effect.sync(() => { + view = applyCommandOutputFrame(view, frame); + listener(view); + })), Effect.catchCause((cause) => Effect.sync(() => onError(prettyCause(cause)))), )); return () => { Effect.runFork(Fiber.interrupt(fiber)); }; diff --git a/src/model/details.ts b/src/model/details.ts index 9e251bb..bd9e203 100644 --- a/src/model/details.ts +++ b/src/model/details.ts @@ -228,7 +228,7 @@ function automationLine(task: ScheduledTask, now: number, timestampFormat: Tui3C task.schedule.type === "interval" ? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}` : task.schedule.type === "fixed_time" - ? `${task.schedule.weekdays && task.schedule.weekdays.length < 7 ? task.schedule.weekdays.map((day) => WEEKDAYS[day]).join(",") + " " : "daily "}${formatClock(task.schedule.timeOfDay, timestampFormat)}` + ? `${task.schedule.weekdays && task.schedule.weekdays.length < 7 ? `${task.schedule.weekdays.map((day) => WEEKDAYS[day]).join(",")} ` : "daily "}${formatClock(task.schedule.timeOfDay, timestampFormat)}` : "on webhook"; if (!task.enabled) return { task, schedule, status: "off", tone: "muted" }; if (task.lastRunStatus === "running") return { task, schedule, status: "running", tone: "info" }; diff --git a/src/model/diffs.ts b/src/model/diffs.ts index ad2f861..b91aab1 100644 --- a/src/model/diffs.ts +++ b/src/model/diffs.ts @@ -11,7 +11,7 @@ export interface PatchFile { /** Retains both paths so renamed and deleted files expand against the right revisions. */ export function splitPatch(patch: string): PatchFile[] { return patch.split(/^(?=diff --git )/m).filter((chunk) => chunk.startsWith("diff --git ")).map((chunk) => { - let parsed; + let parsed: ReturnType[number] | undefined; try { parsed = parsePatch(chunk.split(/^@@ /m)[0]!)[0]; } catch { /* A truncated preview can end inside a file header. */ } const oldPath = cleanPath(parsed?.oldFileName ?? /^diff --git a\/(.+?) b\//.exec(chunk)?.[1] ?? "file"); const newPath = cleanPath(parsed?.newFileName ?? oldPath); diff --git a/src/ui/terminalOut.ts b/src/ui/terminalOut.ts index 328f3ff..5d4a2d2 100644 --- a/src/ui/terminalOut.ts +++ b/src/ui/terminalOut.ts @@ -18,6 +18,7 @@ export function ring(): void { * either ignore it. In tmux it needs `set -g allow-passthrough on`. */ export function desktopNotify(title: string, body: string): void { + // biome-ignore lint/suspicious/noControlCharactersInRegex: the control characters are what is being stripped const clean = (text: string) => text.replace(/[\x00-\x1f\x7f;]/g, " ").slice(0, 200); const sequence = process.env.KITTY_WINDOW_ID ? `\x1b]99;i=tui3:d=0;${clean(title)}\x1b\\\x1b]99;i=tui3:p=body;${clean(body)}\x1b\\` diff --git a/src/ui/useQueue.ts b/src/ui/useQueue.ts index be46f75..d1cbe92 100644 --- a/src/ui/useQueue.ts +++ b/src/ui/useQueue.ts @@ -114,29 +114,44 @@ export function useQueue(input: { switch (event.name) { case "j": case "down": - return setFocus(Math.min(queued.length - 1, focus + 1)), true; + setFocus(Math.min(queued.length - 1, focus + 1)); + return true; case "k": case "up": - return setFocus(Math.max(0, focus - 1)), true; + setFocus(Math.max(0, focus - 1)); + return true; case "return": case "s": - return sendNow(message), true; + sendNow(message); + return true; case "e": - return beginEdit(message), true; + beginEdit(message); + return true; case "x": case "d": case "backspace": - return remove(message), true; + remove(message); + return true; case "escape": case "q": - return setFocus(null), true; + setFocus(null); + return true; } return false; } - if (mode === "nav" && event.name === "q" && event.shift && queued.length > 0) return setFocus(0), true; + if (mode === "nav" && event.name === "q" && event.shift && queued.length > 0) { + setFocus(0); + return true; + } // The web's alt+↑: edit the last queued message. - if (mode === "input" && event.meta && event.name === "up" && !editing && queued.length > 0) return beginEdit(queued[queued.length - 1]!), true; - if (mode === "input" && event.name === "escape" && editing) return cancelEdit(), true; + if (mode === "input" && event.meta && event.name === "up" && !editing && queued.length > 0) { + beginEdit(queued[queued.length - 1]!); + return true; + } + if (mode === "input" && event.name === "escape" && editing) { + cancelEdit(); + return true; + } return false; }; diff --git a/src/ui/useSecretRequest.ts b/src/ui/useSecretRequest.ts index 18e7d98..d9a8036 100644 --- a/src/ui/useSecretRequest.ts +++ b/src/ui/useSecretRequest.ts @@ -47,8 +47,14 @@ export function useSecretRequest(input: { readonly session: T3Session; readonly if (!request) return false; if (value === null) { if (!nav) return false; - if (event.name === "return") return setValue(""), true; - if (event.name === "x" && !questionPending) return answer({ type: "decline" }), true; + if (event.name === "return") { + setValue(""); + return true; + } + if (event.name === "x" && !questionPending) { + answer({ type: "decline" }); + return true; + } return false; } if (event.ctrl && event.name === "c") return false; diff --git a/test/commands.test.ts b/test/commands.test.ts index 2d7a071..64d5a2b 100644 --- a/test/commands.test.ts +++ b/test/commands.test.ts @@ -78,7 +78,12 @@ describe("commands tui3 dispatches", () => { test("a new thread launches with a payload the server accepts", async () => { const session = new T3Session(); let payload: unknown; - const rpc = { "orchestration.launchThread": (input: unknown) => ((payload = input), Effect.succeed({ threadId: ThreadId.make("new-1") })) }; + const rpc = { + "orchestration.launchThread": (input: unknown) => { + payload = input; + return Effect.succeed({ threadId: ThreadId.make("new-1") }); + }, + }; (session as unknown as { connection: unknown }).connection = { rpc }; const id = await session.launchThread({ projectId: ProjectId.make("p1"), @@ -104,7 +109,12 @@ describe("commands tui3 dispatches", () => { const launching = new T3Session(); let payload: unknown; - const rpc = { "orchestration.launchThread": (input: unknown) => ((payload = input), Effect.succeed({ threadId: ThreadId.make("new-2") })) }; + const rpc = { + "orchestration.launchThread": (input: unknown) => { + payload = input; + return Effect.succeed({ threadId: ThreadId.make("new-2") }); + }, + }; (launching as unknown as { connection: unknown }).connection = { rpc }; await launching.launchThread({ projectId: ProjectId.make("p1"), diff --git a/test/diffs.test.ts b/test/diffs.test.ts index 5614268..cb6f387 100644 --- a/test/diffs.test.ts +++ b/test/diffs.test.ts @@ -5,7 +5,10 @@ import { splitPatch, wholeFilePatch } from "../src/model/diffs.ts"; const changed = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -2 +2 @@\n-old\n+new\n"; test("diff files retain old paths and change types for contents requests", () => { - const files = splitPatch(changed + "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n" + "diff --git a/gone.ts b/gone.ts\ndeleted file mode 100644\n--- a/gone.ts\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n" + "diff --git a/add.ts b/add.ts\nnew file mode 100644\n--- /dev/null\n+++ b/add.ts\n@@ -0,0 +1 @@\n+added\n"); + const renamed = "diff --git a/old.ts b/new.ts\nsimilarity index 100%\nrename from old.ts\nrename to new.ts\n"; + const deleted = "diff --git a/gone.ts b/gone.ts\ndeleted file mode 100644\n--- a/gone.ts\n+++ /dev/null\n@@ -1 +0,0 @@\n-gone\n"; + const added = "diff --git a/add.ts b/add.ts\nnew file mode 100644\n--- /dev/null\n+++ b/add.ts\n@@ -0,0 +1 @@\n+added\n"; + const files = splitPatch(`${changed}${renamed}${deleted}${added}`); expect(files.map(({ path, oldPath, changeType }) => ({ path, oldPath, changeType }))).toEqual([ { path: "a.ts", oldPath: "a.ts", changeType: "change" }, { path: "new.ts", oldPath: "old.ts", changeType: "rename-pure" }, { path: "gone.ts", oldPath: "gone.ts", changeType: "deleted" }, { path: "add.ts", oldPath: "add.ts", changeType: "new" }, diff --git a/test/pullRequests.test.ts b/test/pullRequests.test.ts index 739d76a..8d809b8 100644 --- a/test/pullRequests.test.ts +++ b/test/pullRequests.test.ts @@ -261,7 +261,10 @@ describe("pull request commands and payloads", () => { const payloads = new Map(); const capture = (method: string, result: unknown) => - (input: unknown) => (payloads.set(method, input), Effect.succeed(result)); + (input: unknown) => { + payloads.set(method, input); + return Effect.succeed(result); + }; const rpc = { "pullRequests.list": capture("list", listResult([])), "pullRequests.detail": capture("detail", detail()), diff --git a/test/workspace.test.ts b/test/workspace.test.ts index 58db7ee..e01a39a 100644 --- a/test/workspace.test.ts +++ b/test/workspace.test.ts @@ -77,7 +77,9 @@ describe("workspace RPC payloads (no live mutations)", () => { await session.cancelWorktreeSetup(threadId); expect(sent.map((call) => call.method)).toEqual(["vcs.switchRef", "vcs.createRef", "vcs.pull", "vcs.createWorktree", "vcs.removeWorktree", "shell.openInEditor", "worktreeSetup.cancel"]); const schemas = [VcsSwitchRefInput, VcsCreateRefInput, VcsPullInput, VcsCreateWorktreeInput, VcsRemoveWorktreeInput, LaunchEditorInput, WorktreeSetupCancelInput]; - schemas.forEach((schema, index) => expect(Schema.is(schema)(sent[index]!.input)).toBe(true)); + schemas.forEach((schema, index) => { + expect(Schema.is(schema)(sent[index]!.input)).toBe(true); + }); expect(sent[1]!.input).toMatchObject({ switchRef: true }); expect(sent[3]!.input).toEqual({ cwd: "/repo", refName: "main", newRefName: "new-work", path: null }); expect(sent[4]!.input).not.toHaveProperty("force");