Merge tidy: shared text helpers, hook readability pass, Biome lint

This commit is contained in:
Callum Alpass committed 2026-11-02 23:03:07 +11:00
commit 273feb4294
28 files changed
+955 -321

No files matched your search

+36
View File
@@ -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
}
}
]
}
+19
View File
@@ -16,6 +16,7 @@
"zustand": "5.0.11", "zustand": "5.0.11",
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "2.5.15",
"@noble/hashes": "1.8.0", "@noble/hashes": "1.8.0",
"@types/bun": "latest", "@types/bun": "latest",
"@types/react": "^19.3.0", "@types/react": "^19.3.0",
@@ -25,6 +26,24 @@
}, },
}, },
"packages": { "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=="], "@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=="], "@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=="],
+2
View File
@@ -9,6 +9,7 @@
"scripts": { "scripts": {
"dev": "bun run src/bin.ts", "dev": "bun run src/bin.ts",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"lint": "biome lint src test",
"test": "bun test", "test": "bun test",
"postinstall": "bun run scripts/link-vendor.ts" "postinstall": "bun run scripts/link-vendor.ts"
}, },
@@ -24,6 +25,7 @@
"zustand": "5.0.11" "zustand": "5.0.11"
}, },
"devDependencies": { "devDependencies": {
"@biomejs/biome": "2.5.15",
"@noble/hashes": "1.8.0", "@noble/hashes": "1.8.0",
"@types/bun": "latest", "@types/bun": "latest",
"@types/react": "^19.3.0", "@types/react": "^19.3.0",
+6 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bun #!/usr/bin/env bun
import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; import type { OrchestrationV2ShellSnapshot, ThreadId } from "@t3tools/contracts";
import { T3Session } from "./client/session.ts"; import { T3Session } from "./client/session.ts";
import { findThread, lastActivity, relativeTime, rowTime, shortId, statusLabel, threadRows } from "./model/threads.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 pending = false;
let syncing = false; let syncing = false;
const sync = async () => { const sync = async () => {
if (syncing) return void (pending = true); if (syncing) {
pending = true;
return;
}
syncing = true; syncing = true;
try { try {
const latest = session.getShell().snapshot; const latest = session.getShell().snapshot;
@@ -115,7 +118,7 @@ async function tmuxCommand(args: string[]) {
async function runUi(attachNeedle?: string) { async function runUi(attachNeedle?: string) {
const { session, snapshot } = await connectedSession(); const { session, snapshot } = await connectedSession();
let attachThreadId; let attachThreadId: ThreadId | undefined;
if (attachNeedle) { if (attachNeedle) {
const thread = findThread(snapshot, attachNeedle); const thread = findThread(snapshot, attachNeedle);
if (!thread) { if (!thread) {
+4 -1
View File
@@ -365,7 +365,10 @@ export class T3Session {
watchCommandOutput(threadId: ThreadId, itemId: TurnItemId, listener: Listener<CommandOutputView>, onError: Listener<string>): () => void { watchCommandOutput(threadId: ThreadId, itemId: TurnItemId, listener: Listener<CommandOutputView>, onError: Listener<string>): () => void {
let view = EMPTY_COMMAND_OUTPUT; let view = EMPTY_COMMAND_OUTPUT;
const fiber = this.runInScope(this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]({ threadId, itemId }).pipe( 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)))), Effect.catchCause((cause) => Effect.sync(() => onError(prettyCause(cause)))),
)); ));
return () => { Effect.runFork(Fiber.interrupt(fiber)); }; return () => { Effect.runFork(Fiber.interrupt(fiber)); };
+105 -54
View File
@@ -47,16 +47,17 @@ export function newAutomationTemplate(projects: readonly OrchestrationProjectShe
/** The $EDITOR template for an existing automation, its fields filled in. */ /** The $EDITOR template for an existing automation, its fields filled in. */
export function automationTemplate(task: ScheduledTask, projects: readonly OrchestrationProjectShell[]): string { export function automationTemplate(task: ScheduledTask, projects: readonly OrchestrationProjectShell[]): string {
const project = projects.find((candidate) => candidate.id === task.projectId); const project = projects.find((candidate) => candidate.id === task.projectId);
const strategy = task.workspaceStrategy;
return template({ return template({
title: task.title, title: task.title,
enabled: task.enabled, enabled: task.enabled,
schedule: scheduleText(task), schedule: scheduleText(task),
project: project?.title ?? task.projectId, project: project?.title ?? task.projectId,
thread: task.threadId ?? "", thread: task.threadId ?? "",
workspace: task.workspaceStrategy.type, workspace: strategy.type,
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main", baseRef: strategy.type === "worktree" ? strategy.baseRef : "main",
startFromOrigin: task.workspaceStrategy.type === "worktree" ? (task.workspaceStrategy.startFromOrigin ?? false) : true, startFromOrigin: strategy.type === "worktree" ? (strategy.startFromOrigin ?? false) : true,
checkoutPath: task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath : "", checkoutPath: strategy.type === "existing_worktree" ? strategy.worktreePath : "",
model: `${task.modelSelection.instanceId}:${task.modelSelection.model}`, model: `${task.modelSelection.instanceId}:${task.modelSelection.model}`,
mode: task.runtimeMode, mode: task.runtimeMode,
prompt: task.prompt, prompt: task.prompt,
@@ -107,10 +108,13 @@ function scheduleText(task: ScheduledTask): string {
switch (schedule.type) { switch (schedule.type) {
case "interval": { case "interval": {
const minutes = schedule.everyMs / 60_000; 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": { 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}`; return `fixed ${schedule.timeOfDay}${days}`;
} }
case "webhook": case "webhook":
@@ -127,6 +131,58 @@ export type AutomationParse = { readonly ok: true; readonly input: ScheduledTask
* its signature, dedupe and filters, as the template says. * its signature, dedupe and filters, as the template says.
*/ */
export function parseAutomation(text: string, projects: readonly OrchestrationProjectShell[], existing?: ScheduledTask): AutomationParse { 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<string, string>; prompt: string } {
const fields = new Map<string, string>(); const fields = new Map<string, string>();
const promptLines: string[] = []; const promptLines: string[] = [];
let inPrompt = false; let inPrompt = false;
@@ -146,48 +202,29 @@ export function parseAutomation(text: string, projects: readonly OrchestrationPr
} }
fields.set(key, match[2]!.trim()); fields.set(key, match[2]!.trim());
} }
const get = (key: string) => fields.get(key) ?? ""; return { fields, prompt: promptLines.join("\n").trim() };
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." };
const schedule = parseSchedule(get("schedule"), existing); /** The workspace a template names, or null when it names none of the three. */
if (!schedule.ok) return schedule; function workspaceStrategyFor(
workspace: string,
const workspace = get("workspace") || "worktree"; checkoutPath: string,
const checkoutPath = get("checkout path"); get: (key: string) => string,
if (workspace === "existing_worktree" && !checkoutPath) return { ok: false, error: "Checkout path is required: enter the path of the checkout to run in." }; ): ScheduledTaskUpsertInput["workspaceStrategy"] | null {
if (workspace !== "root" && workspace !== "worktree" && workspace !== "existing_worktree") return { ok: false, error: `Workspace must be worktree, root, or existing_worktree, not "${workspace}".` }; switch (workspace) {
case "root":
const mode = get("mode"); return { type: "root" };
if (!(RUNTIME_MODES as readonly string[]).includes(mode)) return { ok: false, error: `Mode must be one of ${RUNTIME_MODES.join(", ")}, not "${mode}".` }; case "existing_worktree":
return { type: "existing_worktree", worktreePath: checkoutPath };
const threadId = get("thread"); case "worktree":
return { return {
ok: true, type: "worktree",
input: { baseRef: get("base ref") || "main",
...(existing ? { id: existing.id, requireExisting: true } : {}), startFromOrigin: get("start from origin").toLowerCase() !== "false",
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",
},
}; };
default:
return null;
}
} }
function parseModel(text: string, base?: ModelSelection): ModelSelection | 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+/); const [kind = "", ...rest] = text.trim().split(/\s+/);
if (kind === "interval") { if (kind === "interval") {
const match = /^(\d+)\s*(m|h)?$/.exec(rest.join(" ")); 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; const unitMs = match?.[2] === "h" ? 3_600_000 : 60_000;
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 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 } }; return { ok: true, schedule: { type: "interval", everyMs } };
} }
if (kind === "fixed") { if (kind === "fixed") {
const timeOfDay = rest[0] ?? ""; 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.` }; if (!/^([01]?\d|2[0-3]):([0-5]\d)$/.test(timeOfDay)) {
const days = rest.slice(1).join(" ").split(/[,\s]+/).filter(Boolean); 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[] = []; const weekdays: number[] = [];
for (const day of days) { for (const day of dayNames) {
const index = WEEKDAY_BY_NAME.get(day.toLowerCase()); 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); weekdays.push(index);
} }
const everyDay = weekdays.length === 0 || new Set(weekdays).size === 7; const uniqueWeekdays = [...new Set(weekdays)].sort((a, b) => a - b);
return { ok: true, schedule: { type: "fixed_time", timeOfDay, ...(everyDay ? {} : { weekdays: [...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") { if (kind === "webhook") {
const current = existing?.schedule.type === "webhook" ? existing.schedule : null; const current = existing?.schedule.type === "webhook" ? existing.schedule : null;
if (!current) return { ok: true, schedule: { type: "webhook", signature: null, dedupe: {} } }; 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. // 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 { return {
ok: true, ok: true,
schedule: { schedule: {
type: "webhook", 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 } : {}), ...(current.maxDeliveryAgeMinutes !== undefined ? { maxDeliveryAgeMinutes: current.maxDeliveryAgeMinutes } : {}),
dedupe: current.dedupe ?? {}, dedupe: current.dedupe ?? {},
}, },
+1 -1
View File
@@ -228,7 +228,7 @@ function automationLine(task: ScheduledTask, now: number, timestampFormat: Tui3C
task.schedule.type === "interval" task.schedule.type === "interval"
? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}` ? `every ${formatWorkingDurationLabel(task.schedule.everyMs)}`
: task.schedule.type === "fixed_time" : 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"; : "on webhook";
if (!task.enabled) return { task, schedule, status: "off", tone: "muted" }; if (!task.enabled) return { task, schedule, status: "off", tone: "muted" };
if (task.lastRunStatus === "running") return { task, schedule, status: "running", tone: "info" }; if (task.lastRunStatus === "running") return { task, schedule, status: "running", tone: "info" };
+1 -1
View File
@@ -11,7 +11,7 @@ export interface PatchFile {
/** Retains both paths so renamed and deleted files expand against the right revisions. */ /** Retains both paths so renamed and deleted files expand against the right revisions. */
export function splitPatch(patch: string): PatchFile[] { export function splitPatch(patch: string): PatchFile[] {
return patch.split(/^(?=diff --git )/m).filter((chunk) => chunk.startsWith("diff --git ")).map((chunk) => { return patch.split(/^(?=diff --git )/m).filter((chunk) => chunk.startsWith("diff --git ")).map((chunk) => {
let parsed; let parsed: ReturnType<typeof parsePatch>[number] | undefined;
try { parsed = parsePatch(chunk.split(/^@@ /m)[0]!)[0]; } catch { /* A truncated preview can end inside a file header. */ } 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 oldPath = cleanPath(parsed?.oldFileName ?? /^diff --git a\/(.+?) b\//.exec(chunk)?.[1] ?? "file");
const newPath = cleanPath(parsed?.newFileName ?? oldPath); const newPath = cleanPath(parsed?.newFileName ?? oldPath);
+172 -76
View File
@@ -77,51 +77,61 @@ export function rankComposerPullRequests(input: {
const { projectId, repository, query } = input; const { projectId, repository, query } = input;
const linked = composerPullRequestsFromLinks(input.links ?? [], projectId); const linked = composerPullRequestsFromLinks(input.links ?? [], projectId);
const entries = input.result?.entries ?? []; const entries = input.result?.entries ?? [];
const exactEntry: PullRequestListEntry[] = input.exact const exactEntry: PullRequestListEntry[] = input.exact ? [listEntryFromDetail(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,
},
]
: [];
if (/^\d*$/u.test(query)) { if (/^\d*$/u.test(query)) {
return filterComposerPullRequestMatches({ const filtered = filterComposerPullRequestMatches({
entries: [...exactEntry, ...entries], entries: [...exactEntry, ...entries],
linked, linked,
projectId, projectId,
repository, repository,
query, query,
limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
}).map(toComposerPullRequest); });
return filtered.map(toComposerPullRequest);
} }
const matches = rankPullRequestMatches(
entries.filter((entry) => { const inRepository = entries.filter((entry) => {
if (entry.projectId !== projectId || entry.repository.trim().toLowerCase() !== repository.trim().toLowerCase()) return false; 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); const provider = input.result?.providers.find((candidate) => candidate.host === entry.host);
return provider?.searchesOnHost === true || matchesPullRequestQuery(entry, query); return provider?.searchesOnHost === true || matchesPullRequestQuery(entry, query);
}), });
const matches = rankPullRequestMatches(inRepository, query);
const ranked = withLinkedComposerPullRequestsFirst({
matches,
linked,
query, query,
); limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT,
return withLinkedComposerPullRequestsFirst({ matches, linked, query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT }).map(toComposerPullRequest); });
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: { function toComposerPullRequest(entry: {
@@ -151,7 +161,8 @@ export function exactPullRequestNumber(query: string): number | null {
* buildPullRequestReferenceContext + reviewCommentContextRecord build it. * buildPullRequestReferenceContext + reviewCommentContextRecord build it.
*/ */
export function pullRequestContextRecord(meta: PullRequestContextMetadata): { record: ReviewCommentContextRecord; replacement: string } { 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 = { const comment = {
id: `pr-reference:${meta.url}`, id: `pr-reference:${meta.url}`,
sectionId: `pull-request:${meta.number}`, sectionId: `pull-request:${meta.number}`,
@@ -189,7 +200,8 @@ export function pullRequestContextRecord(meta: PullRequestContextMetadata): { re
diff: "", diff: "",
pullRequest: comment.pullRequest, 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 { function boundedField(value: string): string {
@@ -203,16 +215,21 @@ export function resolveLinkInput(input: {
readonly project: OrchestrationProjectShell | undefined; readonly project: OrchestrationProjectShell | undefined;
readonly projects: readonly OrchestrationProjectShell[]; readonly projects: readonly OrchestrationProjectShell[];
}): { link: ThreadPullRequestKey & { url: string } } | { error: string } | null { }): { 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, reference: input.reference,
project: pullRequestLinkProject(input.project?.repositoryIdentity), project: pullRequestLinkProject(input.project?.repositoryIdentity),
hasProject: (reference) => hasProject,
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,
}); });
return resolved;
} }
export type PullRequestLineKind = "title" | "meta" | "body" | "check" | "review" | "comment" | "guide" | "faint"; 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. */ /** 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[] = []; 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 state = detail.state === "open" && detail.isDraft ? "draft" : detail.state;
lines.push({ kind: "title", text: `#${detail.number} ${detail.title}` }); const fileCount = `${detail.changedFiles} ${detail.changedFiles === 1 ? "file" : "files"}`;
lines.push({ const meta = [
kind: "meta",
text: [
state, state,
detail.author ? `by ${detail.author.login}` : "", detail.author ? `by ${detail.author.login}` : "",
`${detail.headBranch} → ${detail.baseBranch}`, `${detail.headBranch} → ${detail.baseBranch}`,
`+${detail.additions} −${detail.deletions} · ${detail.changedFiles} ${detail.changedFiles === 1 ? "file" : "files"}`, `+${detail.additions} −${detail.deletions} · ${fileCount}`,
detail.mergeability !== "unknown" ? detail.mergeability : "", detail.mergeability !== "unknown" ? detail.mergeability : "",
`updated ${ago(detail.updatedAt, now)}`, `updated ${ago(detail.updatedAt, now)}`,
] ];
.filter(Boolean)
.join(" · "), lines.push({ kind: "title", text: `#${detail.number} ${detail.title}` });
}); lines.push({ kind: "meta", text: meta.filter(Boolean).join(" · ") });
lines.push({ kind: "faint", text: detail.url }); 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()) { if (detail.body.trim()) {
lines.push({ kind: "title", text: "Description" }); lines.push({ kind: "title", text: "Description" });
for (const text of wrapBody(detail.body)) lines.push({ kind: "body", text }); 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})` }); lines.push({ kind: "title", text: `Checks (${detail.checks.length})` });
if (detail.checks.length === 0) lines.push({ kind: "faint", text: "No checks reported." }); if (detail.checks.length === 0) lines.push({ kind: "faint", text: "No checks reported." });
for (const check of detail.checks) { 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); const reviews = latestReviews(activity);
lines.push({ kind: "title", text: "Reviews" }); lines.push({ kind: "title", text: "Reviews" });
if (reviews.length === 0) lines.push({ kind: "faint", text: "No reviews yet." }); if (reviews.length === 0) lines.push({ kind: "faint", text: "No reviews yet." });
for (const review of reviews) lines.push({ kind: "review", text: review }); for (const review of reviews) lines.push({ kind: "review", text: review });
const comments = activity?.comments ?? []; 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." }); if (comments.length === 0) lines.push({ kind: "faint", text: "No comments yet." });
for (const comment of comments.slice(-20)) { for (const comment of comments.slice(-20)) {
const who = comment.author?.login ?? "ghost"; 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} · ${commentKindLabel(comment)} · ${ago(comment.createdAt, now)}` });
lines.push({ kind: "comment", text: `${who} · ${kind} · ${ago(comment.createdAt, now)}` });
for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` }); for (const text of wrapBody(comment.body)) lines.push({ kind: "body", text: ` ${text}` });
} }
const threads = activity?.reviewThreads ?? []; const threads = activity?.reviewThreads ?? [];
if (threads.length > 0) { if (threads.length === 0) return;
lines.push({ kind: "title", text: `Review threads (${threads.length})` }); lines.push({ kind: "title", text: `Review threads (${threads.length})` });
for (const thread of threads.slice(-20)) { for (const thread of threads.slice(-20)) {
lines.push({ kind: "comment", text: `${thread.isResolved ? "✓ resolved" : "● open"} ${thread.path}${thread.line ? `:${thread.line}` : ""}` }); 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)) { for (const comment of thread.comments.slice(-3)) {
lines.push({ kind: "comment", text: ` ${comment.author?.login ?? "ghost"} · ${ago(comment.createdAt, now)}` }); 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}` }); 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 ?? []; const commits = activity?.commits ?? [];
if (commits.length > 0) { if (commits.length === 0) return;
lines.push({ kind: "title", text: `Commits (${commits.length})` }); 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}` }); 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. */ /** The review guide's lines, or its run state, as the web's guide tab leads with. */
export function guideLines(guide: PullRequestReviewGuideResult | null): PullRequestLine[] { export function guideLines(guide: PullRequestReviewGuideResult | null): PullRequestLine[] {
if (!guide) return []; 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 === "Running") {
if (guide.run?._tag === "Failed" && !guide.guide) return [{ kind: "title", text: "Review guide" }, { kind: "guide", text: `The review guide failed: ${guide.run.detail}` }]; 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 []; 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) { for (const stop of guide.guide.stops) {
lines.push({ kind: "guide", text: stop.title }); lines.push({ kind: "guide", text: stop.title });
for (const text of wrapBody(stop.summary)) lines.push({ kind: "body", text: ` ${text}` }); 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; if (comment.kind !== "review" || !comment.reviewState) continue;
const who = comment.author?.login ?? "ghost"; const who = comment.author?.login ?? "ghost";
const held = latest.get(who); 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<PullRequestAction, string> = { const ACTION_LABELS: Record<PullRequestAction, string> = {
@@ -337,19 +417,32 @@ export const MERGE_METHOD_LABELS: Record<PullRequestMergeMethod, string> = {
/** The runAction actions to offer: what the host can do and the viewer may, for this state. */ /** 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 }[] { 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[] = const byState: readonly PullRequestAction[] =
detail.state === "merged" detail.state === "merged"
? ["revert", "delete-branch"] ? ["revert", "delete-branch"]
: detail.state === "closed" : detail.state === "closed"
? ["reopen", "delete-branch"] ? ["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. */ /** Merge methods to offer, from the host's capabilities as the detail reports them. */
export function offeredMergeMethods(detail: PullRequestDetail): readonly PullRequestMergeMethod[] { 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 { 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. */ /** Body text as plain lines: blank runs collapse, very long bodies stop. */
export function wrapBody(body: string, maxLines = 60): string[] { 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[] = []; const out: string[] = [];
for (const line of lines) { for (const line of lines) {
if (line === "" && out.at(-1) === "") continue; if (line === "" && out.at(-1) === "") continue;
+28 -7
View File
@@ -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 { projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { nextTerminalId } from "@t3tools/shared/terminalLabels"; import { nextTerminalId } from "@t3tools/shared/terminalLabels";
export { resolveBranchSelectionTarget } from "../../vendor/t3code/apps/web/src/components/BranchToolbar.logic.ts"; 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. */ /** 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 { return {
threadId, threadId,
terminalId: nextTerminalId(terminals.map((terminal) => terminal.terminalId), metadataLive ? undefined : crypto.randomUUID()), terminalId,
cwd: worktreePath ?? projectRoot, cwd: worktreePath ?? projectRoot,
worktreePath, worktreePath,
env: projectScriptRuntimeEnv({ project: { cwd: 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. */ /** Show the active preparation stage without hiding failures after setup stops. */
export function worktreeSetupNote(snapshot: WorktreeSetupSnapshot | null): string | null { export function worktreeSetupNote(snapshot: WorktreeSetupSnapshot | null): string | null {
if (!snapshot || snapshot.phase === "done") return null; if (!snapshot || snapshot.phase === "done") return null;
const stage = snapshot.stages.find((stage) => stage.status === "running") ?? snapshot.stages.find((stage) => stage.status === "failed"); const running = snapshot.stages.find((stage) => stage.status === "running");
return [ 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}`, `Worktree setup: ${snapshot.phase}`,
stage ? worktreeSetupStageLabel(stage.id) : null, stage ? worktreeSetupStageLabel(stage.id) : null,
stage?.percent !== null && stage?.percent !== undefined ? `${stage.percent}%` : null, percent,
snapshot.error ?? stage?.detail, snapshot.error ?? stage?.detail,
].filter(Boolean).join(" · "); ];
return parts.filter(Boolean).join(" · ");
} }
+1 -5
View File
@@ -1,5 +1,6 @@
import type { ComposerItem } from "../model/composerMenu.ts"; import type { ComposerItem } from "../model/composerMenu.ts";
import { ClickRow } from "./Button.tsx"; import { ClickRow } from "./Button.tsx";
import { truncate } from "./text.ts";
import { colors } from "./theme.ts"; import { colors } from "./theme.ts";
const MAX_ROWS = 8; const MAX_ROWS = 8;
@@ -34,8 +35,3 @@ export function ComposerMenu(props: { readonly items: readonly ComposerItem[]; r
</box> </box>
); );
} }
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;
}
+1 -5
View File
@@ -2,6 +2,7 @@ import type { ReactNode } from "react";
import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts"; import { MAX_DETAIL_FILES, type DetailsAction, type ThreadDetails } from "../model/details.ts";
import { ClickRow } from "./Button.tsx"; import { ClickRow } from "./Button.tsx";
import { truncate } from "./text.ts";
import { colors, statusColor } from "./theme.ts"; import { colors, statusColor } from "./theme.ts";
/** Rows stay readable when the panel takes the conversation's place on a narrow terminal. */ /** 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(" "); 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. */ /** Keeps the end of a path, where the file name is, as the web's StartTruncatedPath does. */
function startTruncate(text: string, width: number): string { function startTruncate(text: string, width: number): string {
return text.length > width ? `…${text.slice(text.length - width + 1)}` : text; return text.length > width ? `…${text.slice(text.length - width + 1)}` : text;
+1 -5
View File
@@ -2,6 +2,7 @@ import type { MouseEvent } from "@opentui/core";
import type { QueuedMessage } from "../model/queue.ts"; import type { QueuedMessage } from "../model/queue.ts";
import { Button, Buttons, isLeftClick, useHover } from "./Button.tsx"; import { Button, Buttons, isLeftClick, useHover } from "./Button.tsx";
import { truncate } from "./text.ts";
import { colors } from "./theme.ts"; import { colors } from "./theme.ts";
export interface QueueActions { 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 }) { 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 { index, actions } = props;
const [hover, hoverProps] = useHover(); const [hover, hoverProps] = useHover();
+1 -5
View File
@@ -4,6 +4,7 @@ import type { ThreadId } from "@t3tools/contracts";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { ClickRow, wheelStep } from "./Button.tsx"; import { ClickRow, wheelStep } from "./Button.tsx";
import { truncate } from "./text.ts";
import { colors, statusColor } from "./theme.ts"; import { colors, statusColor } from "./theme.ts";
/** /**
@@ -125,8 +126,3 @@ function SectionHeader({ label }: { readonly label: string }) {
</text> </text>
); );
} }
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;
}
+1 -5
View File
@@ -13,6 +13,7 @@ import { CommandOutput } from "./CommandOutput.tsx";
import type { T3Session, ThreadHistory } from "../client/session.ts"; import type { T3Session, ThreadHistory } from "../client/session.ts";
import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts";
import { blockFor } from "../model/transcript.ts"; import { blockFor } from "../model/transcript.ts";
import { firstLine } from "./text.ts";
import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts";
/** What a right-click in the conversation was on. */ /** What a right-click in the conversation was on. */
@@ -337,8 +338,3 @@ function glyphFor(entry: WorkLogEntry): string {
if (entry.itemType === "todo_list") return "☐"; if (entry.itemType === "todo_list") return "☐";
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;
}
+1
View File
@@ -18,6 +18,7 @@ export function ring(): void {
* either ignore it. In tmux it needs `set -g allow-passthrough on`. * either ignore it. In tmux it needs `set -g allow-passthrough on`.
*/ */
export function desktopNotify(title: string, body: string): void { 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 clean = (text: string) => text.replace(/[\x00-\x1f\x7f;]/g, " ").slice(0, 200);
const sequence = process.env.KITTY_WINDOW_ID 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\\` ? `\x1b]99;i=tui3:d=0;${clean(title)}\x1b\\\x1b]99;i=tui3:p=body;${clean(body)}\x1b\\`
+13
View File
@@ -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)}…`;
}
+24 -5
View File
@@ -40,12 +40,27 @@ export function useAttachments(deps: {
const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map()); const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map());
const pending = byComposer.get(composerKey) ?? []; const pending = byComposer.get(composerKey) ?? [];
const add = (attachment: ChatAttachment) => // Lists are replaced whole, per composer, so switching threads never mixes them.
setByComposer((previous) => new Map(previous).set(composerKey, [...(previous.get(composerKey) ?? []), attachment])); 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) => { const upload = (name: string, bytes: Uint8Array, mimeType?: string) => {
if (maxFileBytes === undefined) return say("Still loading the server's attachment limits.", true); 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); if (!checked.ok) return say(checked.error, true);
say(`Uploading ${checked.upload.name}…`); say(`Uploading ${checked.upload.name}…`);
session.uploadAttachment(checked.upload, bytes).then( session.uploadAttachment(checked.upload, bytes).then(
@@ -91,7 +106,11 @@ export function useAttachments(deps: {
}; };
const remove = (attachment: ChatAttachment) => { 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( session.deleteAttachment(attachment.id).then(
() => say(`Removed ${attachment.name}`), () => say(`Removed ${attachment.name}`),
(error) => say(`Removed ${attachment.name}; deleting the upload failed: ${messageOf(error)}`, true), (error) => say(`Removed ${attachment.name}; deleting the upload failed: ${messageOf(error)}`, true),
@@ -117,7 +136,7 @@ export function useAttachments(deps: {
remove, remove,
take: () => { take: () => {
const taken = byComposer.get(composerKey) ?? []; const taken = byComposer.get(composerKey) ?? [];
if (taken.length > 0) setByComposer((previous) => new Map(previous).set(composerKey, [])); if (taken.length > 0) setPending([]);
return taken; return taken;
}, },
}; };
+25 -5
View File
@@ -10,17 +10,37 @@ export function usePaletteSearch(session: T3Session, snapshot: OrchestrationV2Sh
const before = snapshot?.olderSettled?.before; const before = snapshot?.olderSettled?.before;
const [result, setResult] = useState<{ query: string; value: OrchestrationV2SearchThreadsResult } | null>(null); const [result, setResult] = useState<{ query: string; value: OrchestrationV2SearchThreadsResult } | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
setError(null); setError(null);
if (!normalized) return; if (!normalized) return;
let cancelled = false; let cancelled = false;
const timer = setTimeout(() => { const timer = setTimeout(() => {
session.searchThreads({ query: normalized, ...(before ? { olderSettledBefore: before, ...(messageSearchTokens(normalized).long.length ? {} : { titlesOnly: true }) } : {}) }).then( // Beyond the live shelf a query with no searchable words can only match titles.
(value) => { if (!cancelled) setResult({ query: normalized, value }); }, const titlesOnly = before ? messageSearchTokens(normalized).long.length === 0 : false;
(error) => { if (!cancelled) setError(`Could not search messages: ${String(error)}`); }, 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); }, 120);
return () => { cancelled = true; clearTimeout(timer); }; return () => {
cancelled = true;
clearTimeout(timer);
};
}, [session, normalized, before]); }, [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,
};
} }
+89 -31
View File
@@ -38,6 +38,7 @@ import {
} from "../model/pullRequests.ts"; } from "../model/pullRequests.ts";
import type { Confirmation } from "./ConfirmBar.tsx"; import type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts"; import { editInEditor } from "./editor.ts";
import { firstLine } from "./text.ts";
import type { PullRequestViewState } from "./PullRequestView.tsx"; import type { PullRequestViewState } from "./PullRequestView.tsx";
export interface PullRequestDeps { export interface PullRequestDeps {
@@ -92,7 +93,10 @@ export function usePullRequests(deps: PullRequestDeps) {
const load = async (link: ThreadPullRequestLink, reference: PullRequestRef) => { const load = async (link: ThreadPullRequestLink, reference: PullRequestRef) => {
const token = { link, reference }; const token = { link, reference };
try { 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; let merged = detail;
if (capabilities?.pullRequestChecks === true) { if (capabilities?.pullRequestChecks === true) {
const checks = await session.pullRequestChecks(reference).catch(() => null); const checks = await session.pullRequestChecks(reference).catch(() => null);
@@ -168,7 +172,10 @@ export function usePullRequests(deps: PullRequestDeps) {
const comment = () => { const comment = () => {
const current = loadedRef.current; 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, ""); const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; nothing was posted.", true); if (edited === null) return deps.say("The editor exited with an error; nothing was posted.", true);
const body = edited.trim(); const body = edited.trim();
@@ -190,24 +197,27 @@ export function usePullRequests(deps: PullRequestDeps) {
const current = loadedRef.current; const current = loadedRef.current;
const detail = current?.detail; const detail = current?.detail;
if (!current || !detail) return; 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); if (offered.length === 0) return deps.say("Reviewing is not available on this pull request.", true);
deps.openPicker({
placeholder: "Review verdict", const writeReview = (verdict: (typeof VERDICTS)[number]) => {
groups: [
{
label: "Verdict",
items: offered.map((verdict) => ({
id: `verdict:${verdict.value}`,
title: verdict.label,
run: () => {
const edited = editInEditor(deps.renderer, ""); const edited = editInEditor(deps.renderer, "");
if (edited === null) return deps.say("The editor exited with an error; the review was not submitted.", true); if (edited === null) return deps.say("The editor exited with an error; the review was not submitted.", true);
const body = edited; const body = edited;
const summaryRequired = sourceControlClients.get(detail.provider).reviewSummaryRequired("request-changes"); const summaryRequired = sourceControlClients.get(detail.provider).reviewSummaryRequired("request-changes");
const canSubmit = // Requesting changes can demand a summary; approving never does.
verdict.value === "request-changes" && summaryRequired ? body.trim().length > 0 : verdict.value === "approve" || body.trim().length > 0; const needsSummary = verdict.value === "request-changes" && summaryRequired;
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); 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({ deps.confirm({
title: `${verdict.label} #${detail.number}?`, title: `${verdict.label} #${detail.number}?`,
...(body.trim() ? { detail: firstLine(body) } : {}), ...(body.trim() ? { detail: firstLine(body) } : {}),
@@ -218,7 +228,17 @@ export function usePullRequests(deps: PullRequestDeps) {
reloadQuietly(); reloadQuietly();
}), }),
}); });
}, };
deps.openPicker({
placeholder: "Review verdict",
groups: [
{
label: "Verdict",
items: offered.map((verdict) => ({
id: `verdict:${verdict.value}`,
title: verdict.label,
run: () => writeReview(verdict),
})), })),
}, },
], ],
@@ -306,7 +326,8 @@ export function usePullRequests(deps: PullRequestDeps) {
const setWatching = (link: ThreadPullRequestLink, watching: boolean) => { const setWatching = (link: ThreadPullRequestLink, watching: boolean) => {
if (!threadShell) return; 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 = () => { const linkDialog = () => {
@@ -323,8 +344,15 @@ export function usePullRequests(deps: PullRequestDeps) {
const resolved = resolveLinkInput({ reference: text, project, projects: deps.projects }); 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 (resolved === null) return deps.say("Use a pull request URL, 123, or #123.", true);
if ("error" in resolved) return deps.say(resolved.error, true); if ("error" in resolved) return deps.say(resolved.error, true);
const mutation = planThreadPullRequestMutation({ capabilities, threadId: id, reference: resolved.link, linked: true }); const mutation = planThreadPullRequestMutation({
if (mutation === null || mutation.type !== "thread.pull-request.link") return deps.say("This environment does not support linking this pull request.", true); 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; const { threadId: _threadId, source: _source, url, ...key } = mutation.input;
deps.run(`Linked #${key.number}`, () => session.linkPullRequest(id, key, url)); deps.run(`Linked #${key.number}`, () => session.linkPullRequest(id, key, url));
}, },
@@ -376,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 const view: PullRequestViewState | null = loaded
? { ? {
@@ -441,7 +471,13 @@ export function usePullRequests(deps: PullRequestDeps) {
} }
if (threadShell) { if (threadShell) {
for (const link of links) { 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")) { if (supportsWatch && (link.snapshot === null || link.snapshot.state === "open")) {
const watching = link.watch !== undefined; const watching = link.watch !== undefined;
commands.push({ commands.push({
@@ -466,16 +502,18 @@ export function usePullRequests(deps: PullRequestDeps) {
return { view, isOpen: loaded !== null, open, close, handleKey, commands }; 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. */ /** The project's configured merge method, as the web pre-selects it. */
function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) { function preferredMergeMethod(config: ServerConfig, projectId: ProjectId) {
return resolveProjectSettings(config.settings, projectId).settings.pullRequestMergeMethod ?? undefined; 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);
function firstLine(text: string): string {
const line = (text.trim().split("\n")[0] ?? "").replace(/\s+/g, " ");
return line.length > 100 ? `${line.slice(0, 99)}…` : line;
} }
/** /**
@@ -502,16 +540,36 @@ export function useComposerPullRequests(input: {
const timer = setTimeout(() => { const timer = setTimeout(() => {
void (async () => { void (async () => {
try { 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 number = exactPullRequestNumber(query);
const hasExact = const hasExact =
number !== null && number !== null &&
list.entries.some((entry) => entry.projectId === projectId && entry.repository.trim().toLowerCase() === repository.trim().toLowerCase() && entry.number === number); list.entries.some((entry) => {
const exact = number !== null && !hasExact ? await session.pullRequestDetail({ projectId, repository, number }).catch(() => null) : null; 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; const exactDetail = exact?.number === number ? exact : null;
if (cancelled) return; if (cancelled) return;
const matches = rankComposerPullRequests({ result: list, exact: exactDetail, links: linksRef.current, projectId, repository, query }); const matches = rankComposerPullRequests({
setResult({ key, items: pullRequestItems(matches, repository), failed: list.errors.some((error) => error.projectId === projectId) }); 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 { } catch {
if (!cancelled) setResult({ key, items: [], failed: true }); if (!cancelled) setResult({ key, items: [], failed: true });
} }
+48 -12
View File
@@ -11,45 +11,81 @@ export function useThreadFind(session: T3Session, id: ThreadId | undefined, thre
const [index, setIndex] = useState(0); const [index, setIndex] = useState(0);
const [result, setResult] = useState<{ key: string; value: OrchestrationV2SearchThreadResult } | null>(null); const [result, setResult] = useState<{ key: string; value: OrchestrationV2SearchThreadResult } | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const normalized = query.trim().slice(0, 200).trim(); const normalized = query.trim().slice(0, 200).trim();
const key = open && id && normalized ? JSON.stringify([id, normalized, index]) : null; 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); const latestText = thread?.projection?.visibleTurnItems.at(-1);
useEffect(() => { setQuery(""); setIndex(0); }, [id]);
useEffect(() => {
setQuery("");
setIndex(0);
}, [id]);
useEffect(() => { useEffect(() => {
setError(null); setError(null);
if (!key || !id) return; if (!key || !id) return;
let cancelled = false; let cancelled = false;
const timer = setTimeout(() => { const timer = setTimeout(() => {
session.searchThread({ threadId: id, query: normalized, index }).then( session.searchThread({ threadId: id, query: normalized, index }).then(
(value) => { if (!cancelled) setResult({ key, value }); }, (value) => {
(error) => { if (!cancelled) setError(String(error)); }, if (!cancelled) setResult({ key, value });
},
(searchError) => {
if (!cancelled) setError(String(searchError));
},
); );
}, 100); }, 100);
return () => { cancelled = true; clearTimeout(timer); }; return () => {
cancelled = true;
clearTimeout(timer);
};
}, [session, id, key, latestText]); }, [session, id, key, latestText]);
const data = key && result?.key === key ? result.value : null; const data = key && result?.key === key ? result.value : null;
const match = data?.match ?? null; const match = data?.match ?? null;
// Page in older history until the selected match is on screen, once per cursor.
const requested = useRef<string | null>(null); const requested = useRef<string | null>(null);
useEffect(() => { 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; const history = thread?.history;
if (!history?.hasMore || history.loading || history.error) return; if (!history?.hasMore || history.loading || history.error) return;
const request = `${key}:${history.cursor}`; const request = `${key}:${history.cursor}`;
if (requested.current === request) return; if (requested.current === request) return;
requested.current = request; 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]); }, [session, id, match, timeline, thread?.history, key]);
const step = (delta: number) => { const step = (delta: number) => {
if (data) setIndex(stepThreadFindIndex(data.activeIndex, data.totalMatches, delta)); if (data) setIndex(stepThreadFindIndex(data.activeIndex, data.totalMatches, delta));
}; };
const handleKey = (key: KeyEvent): boolean => {
const handleKey = (keyEvent: KeyEvent): boolean => {
if (!open) return false; if (!open) return false;
if (key.name === "escape") return true; if (keyEvent.name === "escape") return true;
else if (key.name === "return") step(key.shift ? -1 : 1); if (keyEvent.name === "return") step(keyEvent.shift ? -1 : 1);
else if (key.ctrl && key.name === "n") step(1); else if (keyEvent.ctrl && keyEvent.name === "n") step(1);
else if (key.ctrl && key.name === "p") step(-1); else if (keyEvent.ctrl && keyEvent.name === "p") step(-1);
else return false; else return false;
return true; 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,
};
} }
+140 -34
View File
@@ -1,5 +1,11 @@
import type { KeyEvent } from "@opentui/core"; 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 { ThreadId as ThreadIdSchema } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime"; import * as DateTime from "effect/DateTime";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
@@ -10,6 +16,9 @@ import type { PaletteCommand } from "../model/palette.ts";
type Command = PaletteCommand & { readonly run: () => void }; 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. */ /** The sidebar's fetched shelves live separately from its live shell. */
export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string) { export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2ShellSnapshot | null, query: string) {
const [archived, setArchived] = useState(false); const [archived, setArchived] = useState(false);
@@ -17,79 +26,176 @@ export function useThreadLibrary(session: T3Session, snapshot: OrchestrationV2Sh
const [older, setOlder] = useState<readonly OrchestrationV2ThreadShell[]>([]); const [older, setOlder] = useState<readonly OrchestrationV2ThreadShell[]>([]);
const [cursor, setCursor] = useState<OrchestrationV2OlderSettledCursor | null>(null); const [cursor, setCursor] = useState<OrchestrationV2OlderSettledCursor | null>(null);
const [end, setEnd] = useState(false); const [end, setEnd] = useState(false);
const [limit, setLimit] = useState(30); const [limit, setLimit] = useState(SETTLED_PAGE_SIZE);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// A new live cut-off makes every fetched older page stale, so paging starts over.
const cut = snapshot?.olderSettled?.before; const cut = snapshot?.olderSettled?.before;
useEffect(() => { useEffect(() => {
setOlder([]); setOlder([]);
setCursor(null); setCursor(null);
setEnd(false); setEnd(false);
setLimit(30); setLimit(SETTLED_PAGE_SIZE);
}, [cut]); }, [cut]);
const refreshArchive = () => session.archivedThreads().then(setArchive); const refreshArchive = () => session.archivedThreads().then(setArchive);
useEffect(() => { useEffect(() => {
if (!archived) { setLoading(false); return; } if (!archived) {
setLoading(false);
return;
}
let cancelled = false; let cancelled = false;
setLoading(true); setLoading(true);
setError(null); setError(null);
session.archivedThreads().then( session.archivedThreads().then(
(value) => { if (!cancelled) { setArchive(value); setLoading(false); } }, (value) => {
(error) => { if (!cancelled) { setError(String(error)); setLoading(false); } }, if (cancelled) return;
setArchive(value);
setLoading(false);
},
(archiveError) => {
if (cancelled) return;
setError(String(archiveError));
setLoading(false);
},
); );
return () => { cancelled = true; }; return () => {
cancelled = true;
};
}, [session, archived]); }, [session, archived]);
const merged = useMemo(() => mergeThreadShells(snapshot, older), [snapshot, older]); 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]); // The archive keeps the live snapshot's shape so threadRows reads both the same way.
const totalSettled = useMemo(() => threadRows(merged, { query, settledLimit: Infinity }).filter((row) => row.section === "settled").length, [merged, query]); const listSnapshot =
const hasOlder = !archived && (totalSettled > limit || (!end && (snapshot?.olderSettled?.counts.some((count) => count.count > 0) ?? false))); 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 () => { const loadOlder = async () => {
if (loading) return; 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; if (!cut || end || totalSettled > limit) return;
setLoading(true); setLoading(true);
setError(null); setError(null);
try { 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]); setOlder((previous) => [...previous, ...page.threads]);
const last = page.threads.at(-1); const last = page.threads.at(-1);
if (last?.settledAt) setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id }); if (last?.settledAt) {
setEnd(page.threads.length < 30); setCursor({ settledAt: DateTime.formatIso(last.settledAt), threadId: last.id });
} catch (error) { }
setError(String(error)); setEnd(page.threads.length < SETTLED_PAGE_SIZE);
} catch (loadError) {
setError(String(loadError));
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const toggle = () => { setError(null); setArchived((value) => !value); };
const toggle = () => {
setError(null);
setArchived((value) => !value);
};
const unarchive = async (id: ThreadId) => { const unarchive = async (id: ThreadId) => {
await session.unarchiveThread(id); await session.unarchiveThread(id);
await refreshArchive(); await refreshArchive();
}; };
const reorder = async (id: ThreadId, delta: 1 | -1) => { 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. // 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; } if (row?.section === "active") {
const plan = threadReorder(allRows, id, delta, threadRows(listSnapshot, { archived, settledLimit: limit })); 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; if (!plan || archived) return;
try { try {
for (const assignment of plan.assignments) await session.reorderThread(ThreadIdSchema.make(assignment.id), plan.section, assignment.orderKey); for (const assignment of plan.assignments) {
} catch (error) { setError(String(error)); } 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 }, const commands = (id: ThreadId | undefined): Command[] => {
...(hasOlder ? [{ id: "older-settled", title: "Show more settled threads", keywords: ["older", "history", "load"], run: () => void loadOlder() }] : []), const list: Command[] = [
...(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: "archived",
{ id: "reorder-up", title: "Move pinned thread up", shortcut: "K", keywords: ["reorder", "sort"], run: () => void reorder(id, -1) }, title: archived ? "Show active threads" : "Show archived threads",
{ id: "reorder-down", title: "Move pinned thread down", shortcut: "J", keywords: ["reorder", "sort"], run: () => void reorder(id, 1) }, shortcut: "A",
] : []), keywords: ["archive", "history", "restore"],
run: toggle,
},
]; ];
const key = (key: KeyEvent, id: ThreadId | undefined): boolean => { if (hasOlder) {
if (key.name === "a" && key.shift) return toggle(), true; list.push({
if (id && key.shift && (key.name === "j" || key.name === "k")) return void reorder(id, key.name === "j" ? 1 : -1), true; 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 false;
}; };
return { archived, allRows, merged, archive, commands, key, hasOlder, loadOlder, loading, error }; return { archived, allRows, merged, archive, commands, key, hasOlder, loadOlder, loading, error };
} }
+185 -61
View File
@@ -38,7 +38,10 @@ export function useWorkspace(input: {
const activeThread = useRef(thread?.id); const activeThread = useRef(thread?.id);
activeThread.current = thread?.id; activeThread.current = thread?.id;
const lastReady = useRef<string | null>(null); const lastReady = useRef<string | null>(null);
useEffect(() => live ? session.watchTerminals(setTerminals) : undefined, [session, live]); useEffect(() => {
if (!live) return undefined;
return session.watchTerminals(setTerminals);
}, [session, live]);
useEffect(() => { useEffect(() => {
setSetup(null); setSetup(null);
setSetupError(null); setSetupError(null);
@@ -48,26 +51,39 @@ export function useWorkspace(input: {
setSetupError(state.status === "error" ? state.error ?? "Could not load worktree setup." : null); setSetupError(state.status === "error" ? state.error ?? "Could not load worktree setup." : null);
}); });
}, [session, live, thread?.id]); }, [session, live, thread?.id]);
useEffect(() => session.watchServerLifecycle((state) => { // 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; const event: ServerLifecycleStreamEvent | null = state.event;
if (event?.type === "ready" && event.payload.at !== lastReady.current) { 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; const restarted = lastReady.current !== null;
lastReady.current = event.payload.at; lastReady.current = event.payload.at;
const outcome = event.payload.updateOutcome; const outcome = event.payload.updateOutcome;
sayRef.current(outcome if (outcome) {
? `Server update ${outcome.targetVersion}: ${outcome.status}${outcome.reason ? ` · ${outcome.reason}` : ""}` const reason = outcome.reason ? ` · ${outcome.reason}` : "";
: `Server ${restarted ? "restarted" : "ready"} · ${event.payload.environment.serverVersion}`, outcome !== undefined && outcome.status !== "committed"); sayRef.current(`Server update ${outcome.targetVersion}: ${outcome.status}${reason}`, outcome.status !== "committed");
} else if (event?.type === "legacyThreadMigration") { return;
sayRef.current(`Thread migration ${event.payload.status} · ${event.payload.totalThreadCount} threads`);
} }
}), [session]); 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 threadTerminals = (terminals?.items ?? []).filter((terminal) => terminal.threadId === thread?.id);
const cwd = thread?.worktreePath ?? project?.workspaceRoot; const cwd = thread?.worktreePath ?? project?.workspaceRoot;
const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal); const label = (terminal: TerminalSummary) => resolveTerminalSessionLabel(terminal.terminalId, terminal);
const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => { const enterTerminal = (terminal: Pick<TerminalSummary, "terminalId" | "cwd" | "worktreePath" | "label">) => {
if (!thread) return; 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); if (message) say(message);
}); });
}; };
@@ -81,27 +97,53 @@ export function useWorkspace(input: {
}; };
const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => { const terminalMutation = (terminal: TerminalSummary, action: "close" | "clear") => {
if (!thread) return; 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)}`, 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), 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 = () => { const terminalPicker = () => {
if (!thread || input.draft) return say("Open a thread first.", true); if (!thread || input.draft) return say("Open a thread first.", true);
openPicker({ placeholder: "Terminals · type close or clear for actions", groups: [ const openItems = threadTerminals.map((terminal) => ({
{ label: "Terminals", items: threadTerminals.map((terminal) => ({ id: `terminal:${terminal.terminalId}`, title: label(terminal), hint: terminal.hasRunningSubprocess ? "busy" : terminal.status, run: () => enterTerminal(terminal) })) }, id: `terminal:${terminal.terminalId}`,
{ label: "Actions", items: [ title: label(terminal),
{ id: "terminal:new", title: "New terminal", run: newTerminal }, hint: terminal.hasRunningSubprocess ? "busy" : terminal.status,
...(["close", "clear"] as const).flatMap((action) => { run: () => enterTerminal(terminal),
const items = terminalItems(action); }));
return items.length ? [ openPicker({
{ id: `terminal:${action}`, title: `${action === "close" ? "Close" : "Clear"} terminal…`, run: () => openPicker({ placeholder: `${action === "close" ? "Close" : "Clear"} terminal`, groups: [{ label: "Terminals", items }] }) }, placeholder: "Terminals · type close or clear for actions",
...items.map((item) => ({ ...item, searchOnly: true })), groups: [
] : []; { label: "Terminals", items: openItems },
}), { label: "Actions", items: terminalActionItems() },
] }, ],
] }); });
}; };
const openTerminal = () => { const openTerminal = () => {
if (!thread || input.draft) return say("Open a thread first.", true); if (!thread || input.draft) return say("Open a thread first.", true);
@@ -113,48 +155,88 @@ export function useWorkspace(input: {
const branchPicker = () => { const branchPicker = () => {
if (!thread || !cwd || !project || input.draft) return say("Open a thread with a repository first.", true); if (!thread || !cwd || !project || input.draft) return say("Open a thread with a repository first.", true);
say("Loading refs…"); say("Loading refs…");
session.listRefs(cwd).then((refs) => { session.listRefs(cwd).then(
(refs) => {
if (activeThread.current !== thread.id) return; if (activeThread.current !== thread.id) return;
const updateWorkspace = (branch: string | null, path: string | null) => session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath); openRefPicker(refs);
const promptBranch = (worktree: boolean) => confirm({ },
(error) => say(`Could not list refs: ${messageOf(error)}`, true),
);
};
const openRefPicker = (refs: Awaited<ReturnType<T3Session["listRefs"]>>) => {
if (!thread || !cwd || !project) return;
const updateWorkspace = (branch: string | null, path: string | null) =>
session.setThreadWorkspace(thread.id, branch, path, thread.worktreePath);
const promptBranch = (worktree: boolean) =>
confirm({
title: worktree ? "Create a new worktree?" : "Create and switch ref", 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, 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) => { run: (raw) => {
const name = sanitizeNewRefName(raw); const name = sanitizeNewRefName(raw);
if (!name) return say("Enter a branch name.", true); if (!name) return say("Enter a branch name.", true);
run(worktree ? "Worktree created" : "Branch created", async () => { run(worktree ? "Worktree created" : "Branch created", async () => {
if (worktree) { if (worktree) {
const result = await session.createWorktree(cwd, thread.branch ?? "HEAD", name); const created = await session.createWorktree(cwd, thread.branch ?? "HEAD", name);
await updateWorkspace(result.worktree.refName, result.worktree.path); await updateWorkspace(created.worktree.refName, created.worktree.path);
} else { } else {
const result = await session.createRef(cwd, name); const created = await session.createRef(cwd, name);
await updateWorkspace(result.refName, thread.worktreePath); await updateWorkspace(created.refName, thread.worktreePath);
} }
}); });
}, },
}); });
openPicker({ placeholder: "Select ref", groups: [
{ label: "Refs", items: refs.map((ref) => ({ const selectRef = (ref: (typeof refs)[number]) => {
id: `ref:${ref.isRemote ? "remote:" : ""}${ref.name}`, title: ref.name, run("Ref selected", async () => {
hint: ref.current ? "current" : ref.worktreePath ? "worktree" : ref.isRemote ? "remote" : ref.isDefault ? "default" : "local", const target = resolveBranchSelectionTarget({
run: () => run("Ref selected", async () => { activeProjectCwd: project.workspaceRoot,
const target = resolveBranchSelectionTarget({ activeProjectCwd: project.workspaceRoot, activeWorktreePath: thread.worktreePath, refName: ref }); activeWorktreePath: thread.worktreePath,
const result = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name); refName: ref,
await updateWorkspace(ref.isRemote ? result?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name) : ref.name, target.nextWorktreePath); });
}), const switched = target.reuseExistingWorktree ? null : await session.switchRef(target.checkoutCwd, ref.name);
})) }, const branch = ref.isRemote ? (switched?.refName ?? deriveLocalBranchNameFromRemoteRef(ref.name)) : ref.name;
{ label: "Actions", items: [ 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:create", title: "Create and switch ref…", run: () => promptBranch(false) },
{ id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) }, { id: "branch:pull", title: "Pull", run: () => run("Pulled", () => session.pull(cwd)) },
{ id: "worktree:create", title: "Create worktree…", run: () => promptBranch(true) }, { 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", if (thread.worktreePath) {
run: () => run("Worktree removed", () => session.removeThreadWorktree(thread.id, project.workspaceRoot, thread.worktreePath!)), const worktreePath = thread.worktreePath;
}) }] : []), actionItems.push({
] }, id: "worktree:remove",
] }); title: "Remove worktree…",
}, (error) => say(`Could not list refs: ${messageOf(error)}`, true)); 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)),
}),
});
}
openPicker({
placeholder: "Select ref",
groups: [
{ label: "Refs", items: refItems },
{ label: "Actions", items: actionItems },
],
});
}; };
const openInEditor = () => { const openInEditor = () => {
@@ -167,11 +249,22 @@ export function useWorkspace(input: {
if (diff.path) return open(resolvePathLinkTarget(diff.path, diff.cwd)); if (diff.path) return open(resolvePathLinkTarget(diff.path, diff.cwd));
const files = splitPatch(diff.patch ?? ""); const files = splitPatch(diff.patch ?? "");
if (!files.length) return say("No file to open in this diff.", true); 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 = () => { const cancelSetup = () => {
if (!setup || setup.threadId !== thread?.id || setup.phase !== "running") return; 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 ? [ const commands: Command[] = thread && !input.draft ? [
{ id: "terminal", title: "Open terminal", shortcut: "ctrl+j", keywords: ["shell", "console"], run: openTerminal }, { 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 }, { 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 }] : []), ...(setup?.threadId === thread.id && setup.phase === "running" ? [{ id: "setup-cancel", title: "Cancel worktree setup…", keywords: ["preparation", "stop"], run: cancelSetup }] : []),
] : []; ] : [];
const key = (key: KeyEvent): boolean => { const key = (keyEvent: KeyEvent): boolean => {
if (key.ctrl || key.meta) return false; if (keyEvent.ctrl || keyEvent.meta) return false;
if (key.name === "t" && key.shift) return terminalPicker(), true; if (keyEvent.name === "t" && keyEvent.shift) {
if (key.name === "b" && !key.shift) return branchPicker(), true; terminalPicker();
if (key.name === "e" && key.shift) return openInEditor(), true; return true;
}
if (keyEvent.name === "b" && !keyEvent.shift) {
branchPicker();
return true;
}
if (keyEvent.name === "e" && keyEvent.shift) {
openInEditor();
return true;
}
return false; 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);
}
+12 -2
View File
@@ -78,7 +78,12 @@ describe("commands tui3 dispatches", () => {
test("a new thread launches with a payload the server accepts", async () => { test("a new thread launches with a payload the server accepts", async () => {
const session = new T3Session(); const session = new T3Session();
let payload: unknown; 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 }; (session as unknown as { connection: unknown }).connection = { rpc };
const id = await session.launchThread({ const id = await session.launchThread({
projectId: ProjectId.make("p1"), projectId: ProjectId.make("p1"),
@@ -104,7 +109,12 @@ describe("commands tui3 dispatches", () => {
const launching = new T3Session(); const launching = new T3Session();
let payload: unknown; 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 }; (launching as unknown as { connection: unknown }).connection = { rpc };
await launching.launchThread({ await launching.launchThread({
projectId: ProjectId.make("p1"), projectId: ProjectId.make("p1"),
+4 -1
View File
@@ -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"; 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", () => { 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([ 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: "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" }, { path: "gone.ts", oldPath: "gone.ts", changeType: "deleted" }, { path: "add.ts", oldPath: "add.ts", changeType: "new" },
+4 -1
View File
@@ -261,7 +261,10 @@ describe("pull request commands and payloads", () => {
const payloads = new Map<string, unknown>(); const payloads = new Map<string, unknown>();
const capture = const capture =
(method: string, result: unknown) => (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 = { const rpc = {
"pullRequests.list": capture("list", listResult([])), "pullRequests.list": capture("list", listResult([])),
"pullRequests.detail": capture("detail", detail()), "pullRequests.detail": capture("detail", detail()),
+28
View File
@@ -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)}…`);
});
});
+3 -1
View File
@@ -77,7 +77,9 @@ describe("workspace RPC payloads (no live mutations)", () => {
await session.cancelWorktreeSetup(threadId); 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"]); 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]; 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[1]!.input).toMatchObject({ switchRef: true });
expect(sent[3]!.input).toEqual({ cwd: "/repo", refName: "main", newRefName: "new-work", path: null }); expect(sent[3]!.input).toEqual({ cwd: "/repo", refName: "main", newRefName: "new-work", path: null });
expect(sent[4]!.input).not.toHaveProperty("force"); expect(sent[4]!.input).not.toHaveProperty("force");