diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 587c434964da6..4f3f8aaaded6e 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,5 +1,6 @@ import { CommandId, + type EnvironmentId, type RunId, isProviderAvailable, MessageId, @@ -747,13 +748,14 @@ function threadPullRequests( } function listItemFromShell( + environmentId: EnvironmentId, shell: OrchestrationV2ThreadShell, nowMs: number, ): OrchestratorMcpThreadListItem { return { threadId: shell.id, title: shell.title, - link: formatThreadLink(shell.id, shell.title), + link: formatThreadLink({ environmentId, threadId: shell.id }), createdBy: shell.createdBy, creationSource: shell.creationSource, status: shell.activityRunStatus ?? shell.status, @@ -775,6 +777,7 @@ function listItemFromShell( } function threadDetail( + environmentId: EnvironmentId, projection: Pick, itemCount: number, shell: OrchestrationV2ThreadShell, @@ -786,7 +789,7 @@ function threadDetail( threadId: projection.thread.id, projectId: projection.thread.projectId, title: projection.thread.title, - link: formatThreadLink(projection.thread.id, projection.thread.title), + link: formatThreadLink({ environmentId, threadId: projection.thread.id }), createdBy: projection.thread.createdBy, creationSource: projection.thread.creationSource, status: active?.status ?? latest?.status ?? "idle", @@ -1517,7 +1520,10 @@ const make = Effect.gen(function* () { const result = { taskId: task.id, childThreadId: task.childThreadId, - link: formatThreadLink(task.childThreadId, childControls.thread.title), + link: formatThreadLink({ + environmentId: scope.environmentId, + threadId: task.childThreadId, + }), childRunId: childRun?.id ?? null, childNodeId: task.id, status, @@ -1673,7 +1679,9 @@ const make = Effect.gen(function* () { return { taskId: task.id, childThreadId: null, - ...(task.remoteChild === undefined ? {} : { remoteChild: task.remoteChild }), + ...(task.remoteChild === undefined + ? {} + : { remoteChild: task.remoteChild, link: formatThreadLink(task.remoteChild) }), childRunId: null, childNodeId: task.id, status, @@ -2738,7 +2746,7 @@ const make = Effect.gen(function* () { ); return { threadId, - link: formatThreadLink(threadId, projection.thread.title), + link: formatThreadLink({ environmentId: scope.environmentId, threadId }), runId: run?.id ?? null, status: run?.status ?? "idle", title: projection.thread.title, @@ -2791,7 +2799,7 @@ const make = Effect.gen(function* () { return { projectId, currentThreadId: parent?.thread.id ?? null, - threads: page.map((shell) => listItemFromShell(shell, nowMs)), + threads: page.map((shell) => listItemFromShell(scope.environmentId, shell, nowMs)), nextCursor, total: filtered.length, } satisfies OrchestratorMcpThreadListResult; @@ -2871,7 +2879,13 @@ const make = Effect.gen(function* () { } } return { - thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis), + thread: threadDetail( + scope.environmentId, + target, + timeline.totalItems, + shell, + yield* Clock.currentTimeMillis, + ), recentRuns: target.runs .toSorted((left, right) => right.ordinal - left.ordinal) .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT) @@ -2930,7 +2944,7 @@ const make = Effect.gen(function* () { ); return { threadId: input.threadId, - link: formatThreadLink(input.threadId, target.thread.title), + link: formatThreadLink({ environmentId: scope.environmentId, threadId: input.threadId }), messageId, runId: result.run.id, ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }), diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index d51836d886718..d0ea6437cd1c3 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -184,7 +184,7 @@ it.effect( expect(belowCeiling.result).toMatchObject({ projectId: belowCeiling.projectId, modelSelection: belowCeiling.modelSelection, - link: `[Fix](t3-thread://v1/${belowCeiling.launched[0]?.threadId})`, + link: ``, }); expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index f5a67ae025a85..950cb38c6c4fd 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -240,7 +240,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { const run = result.projection.runs.find((run) => run.userMessageId === messageId); return { threadId: thread.id, - link: formatThreadLink(thread.id, thread.title), + link: formatThreadLink({ environmentId: scope.environmentId, threadId: thread.id }), projectId: thread.projectId, modelSelection: thread.modelSelection, runId: run?.id ?? null, diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 8d7d1359e8c9e..8ad9afa435193 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -11,6 +11,7 @@ import * as Effect from "effect/Effect"; import { modelSelectionCommandType } from "@t3tools/shared/model"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; import { dispatchFailure, @@ -103,9 +104,11 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { const { task, threadId } = yield* scheduler .runNow({ id: input.taskId }) .pipe(Effect.mapError(unavailable)); + const { environmentId } = yield* McpInvocationContext.McpInvocationContext; return { taskId: task.id, threadId, + ...(threadId === null ? {} : { link: formatThreadLink({ environmentId, threadId }) }), lastRunStatus: task.lastRunStatus, runCount: task.runCount, nextRunAt: task.nextRunAt, @@ -115,6 +118,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { t3_thread_search: McpToolAccess.reads((input) => Effect.gen(function* () { const { caller } = yield* readCaller(); + const { environmentId } = yield* McpInvocationContext.McpInvocationContext; const threadSearch = yield* ThreadSearch.ThreadSearch; const { matches } = yield* threadSearch .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId }) @@ -122,7 +126,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { return { matches: matches.map((match) => ({ ...match, - link: formatThreadLink(match.threadId, match.title), + link: formatThreadLink({ environmentId, threadId: match.threadId }), })), }; }), diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index b14b1bd387f1a..4b566c44a69d1 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -226,6 +226,7 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", { success: Schema.Struct({ taskId: ScheduledTaskId, threadId: ScheduledTask.fields.threadId, + link: Schema.optional(Schema.String), lastRunStatus: ScheduledTask.fields.lastRunStatus, runCount: NonNegativeInt, nextRunAt: ScheduledTask.fields.nextRunAt, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index a2c1ecd6a345d..79aec7697ed79 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -4275,7 +4275,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* client.handleServerNotification("account/rateLimits/updated", (payload) => Effect.gen(function* () { - yield* Ref.update(rateLimitSnapshot, (previous) => + const previous = yield* Ref.getAndUpdate(rateLimitSnapshot, (previous) => mergeCodexRateLimits(previous, payload.rateLimits), ); const resetAt = codexUsageLimitResetAt(yield* Ref.get(rateLimitSnapshot)); @@ -4295,7 +4295,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( turnItem: updated, }); } - const update = codexRateLimitsToUpdate(payload.rateLimits); + const update = codexRateLimitsToUpdate(payload.rateLimits, previous); if (update && adapterOptions.onUsageLimits) { const checkedAt = DateTime.formatIso(yield* DateTime.now); yield* adapterOptions.onUsageLimits({ ...update, checkedAt }); diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts index 7f887e79388bf..22f6f8493c95c 100644 --- a/apps/server/src/orchestration-v2/WireProjection.test.ts +++ b/apps/server/src/orchestration-v2/WireProjection.test.ts @@ -294,6 +294,15 @@ describe("orchestration V2 wire projection", () => { expect(projected).not.toHaveProperty("newStr"); expect(projected).toMatchObject({ fileName: "src/main.ts", additions: 3, deletions: 1 }); expect(item.diffStr).toBe("+new code"); + expect(projectTurnItemForDetail(item)).toMatchObject({ diffStr: "+new code" }); + expect(projectTurnItemForDetail(item)).not.toHaveProperty("oldStr"); + expect(projectTurnItemForDetail(item)).not.toHaveProperty("newStr"); + const { diffStr: _diff, ...contentOnly } = item; + expect(projectTurnItemForDetail(contentOnly)).toMatchObject({ + oldStr: "old code", + newStr: "new code", + }); + expect(projectTurnItemForWire(contentOnly)).not.toHaveProperty("newStr"); const failed = projectTurnItemForWire({ ...item, status: "failed", diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.ts index c7be67ca84ca2..f33e3a04c0e44 100644 --- a/apps/server/src/orchestration-v2/WireProjection.ts +++ b/apps/server/src/orchestration-v2/WireProjection.ts @@ -208,8 +208,20 @@ export function projectTurnItemForDetail(item: OrchestrationV2TurnItem): Orchest result: item.result === null ? null : (truncateDetail(item.result, MAX_ON_DEMAND_BYTES) ?? null), }; - case "handoff": case "file_change": + return { + ...projectTurnItemForWire(item), + ...(item.diffStr === undefined + ? {} + : { diffStr: truncateDetail(item.diffStr, MAX_ON_DEMAND_BYTES) }), + ...(!item.diffStr?.trim() && item.oldStr !== undefined + ? { oldStr: truncateDetail(item.oldStr, MAX_ON_DEMAND_BYTES) } + : {}), + ...(!item.diffStr?.trim() && item.newStr !== undefined + ? { newStr: truncateDetail(item.newStr, MAX_ON_DEMAND_BYTES) } + : {}), + }; + case "handoff": return projectTurnItemForWire(item); default: return item; diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts index 093777e67db5d..2bbcea20faa91 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.test.ts @@ -121,8 +121,10 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { '{"models":["shared"]}\n', ); yield* writeTextFile(path.join(sharedHome, "auth.json"), '{"shared":true}\n'); + yield* writeTextFile(path.join(sharedHome, "auth.lock"), ""); yield* fileSystem.makeDirectory(shadowHome, { recursive: true }); yield* writeTextFile(path.join(shadowHome, "auth.json"), '{"shadow":true}\n'); + yield* writeTextFile(path.join(shadowHome, "auth.lock"), ""); yield* fileSystem.symlink( path.join(sharedHome, "models_cache.json"), path.join(shadowHome, "models_cache.json"), @@ -149,6 +151,9 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { .readLink(path.join(shadowHome, "auth.json")) .pipe(Effect.result); const authContents = yield* fileSystem.readFileString(path.join(shadowHome, "auth.json")); + const authLockLinkResult = yield* fileSystem + .readLink(path.join(shadowHome, "auth.lock")) + .pipe(Effect.result); expect(sessionsTarget).toBe(path.join(sharedHome, "sessions")); expect(configTarget).toBe(path.join(sharedHome, "config.toml")); @@ -156,6 +161,7 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { expect(modelsCacheExists).toBe(false); expect(authLinkResult._tag).toBe("Failure"); expect(authContents).toContain("shadow"); + expect(authLockLinkResult._tag).toBe("Failure"); }), ); @@ -221,6 +227,40 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => { }), ); + it.effect.skipIf(!symlinksSupported)( + "shares local thread writer locks once no writer still holds one", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const sharedHome = yield* makeTempDir("t3code-codex-shared-"); + const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-"); + const shadowHome = path.join(shadowRoot, "shadow"); + const shadowLocks = path.join(shadowHome, "thread-writer-locks"); + const threadLock = path.join(shadowLocks, "019a0000-0000-7000-8000-000000000000.lock"); + + yield* writeTextFile(path.join(shadowLocks, ".coordination.lock"), ""); + yield* writeTextFile(path.join(shadowLocks, ".DS_Store"), ""); + yield* writeTextFile(threadLock, ""); + + const layout = yield* resolveCodexHomeLayout( + decodeCodexSettings({ + homePath: sharedHome, + shadowHomePath: shadowHome, + }), + ); + + yield* materializeCodexShadowHome(layout); + expect(yield* fileSystem.exists(threadLock)).toBe(true); + + yield* fileSystem.remove(threadLock); + yield* materializeCodexShadowHome(layout); + expect(yield* fileSystem.readLink(shadowLocks)).toBe( + path.join(sharedHome, "thread-writer-locks"), + ); + }), + ); + it.effect.skipIf(!symlinksSupported)( "accepts Codex-created shadow-local runtime directories", () => diff --git a/apps/server/src/provider/Drivers/CodexHomeLayout.ts b/apps/server/src/provider/Drivers/CodexHomeLayout.ts index f175a0fdd00a9..f6d2ba9d44cf5 100644 --- a/apps/server/src/provider/Drivers/CodexHomeLayout.ts +++ b/apps/server/src/provider/Drivers/CodexHomeLayout.ts @@ -26,13 +26,19 @@ const KNOWN_SHARED_DIRECTORIES = [ "cache", "logs", "mcp-oauth-locks", + "thread-writer-locks", ] as const; -const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]); +// auth.lock guards the shadow home's private auth.json. +const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "auth.lock", "models_cache.json"]); // Finder maintains metadata separately for each directory, including shadow homes. const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp", ".DS_Store"]); // Shadow homes may create local runtime locks first; replace them with shared links because they guard shared state. -const REPLACEABLE_SHARED_RUNTIME_ENTRIES = new Set(["mcp-oauth-locks", ".sqlite-maintenance.lock"]); +const REPLACEABLE_SHARED_RUNTIME_ENTRIES = new Set([ + "mcp-oauth-locks", + "thread-writer-locks", + ".sqlite-maintenance.lock", +]); function resolveHomePath(path: Path.Path, home: string, value: string | undefined): string { const expanded = @@ -253,6 +259,30 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu }); } + if (input.entryName === "thread-writer-locks") { + const lockNames = yield* input.fileSystem.readDirectory(link).pipe( + Effect.catchTags({ + PlatformError: (cause) => + new CodexShadowHomeFileSystemError({ + sharedHomePath: input.sharedHomePath, + effectiveHomePath: input.effectiveHomePath, + operation: "readDirectory", + path: link, + entryName: input.entryName, + cause, + }), + }), + ); + // Codex deletes a thread lock on release, so one that is left may still guard a live + // writer. Keep the local directory until a later setup finds none. + if (lockNames.some((name) => name.endsWith(".lock") && name !== ".coordination.lock")) { + return yield* Effect.logWarning( + "Codex shadow home still has thread writer locks; it will share them on a later setup.", + { path: link }, + ); + } + } + yield* input.fileSystem.remove(link, { recursive: true }).pipe( Effect.catchTags({ PlatformError: (cause) => diff --git a/apps/server/src/provider/codexUsageLimits.test.ts b/apps/server/src/provider/codexUsageLimits.test.ts index 934412bd3bb41..9c863f54c0867 100644 --- a/apps/server/src/provider/codexUsageLimits.test.ts +++ b/apps/server/src/provider/codexUsageLimits.test.ts @@ -128,6 +128,29 @@ describe("codexRateLimitsToLimits", () => { }); describe("codexRateLimitsToUpdate", () => { + it("does not republish cached windows over a newer account probe", () => { + const cached = { + primary: { usedPercent: 0, resetsAt: 1_784_000_000, windowDurationMins: 300 }, + secondary: { usedPercent: 20, resetsAt: 1_784_500_000, windowDurationMins: 10080 }, + }; + expect(codexRateLimitsToUpdate(cached)?.windows).toHaveLength(2); + expect(codexRateLimitsToUpdate(structuredClone(cached), cached)).toBeUndefined(); + + const changed = { ...cached, secondary: { ...cached.secondary, usedPercent: 21 } }; + expect(codexRateLimitsToUpdate(changed, cached)?.windows.map((window) => window.id)).toEqual([ + "secondary", + ]); + expect(codexRateLimitsToUpdate({ primary: cached.primary }, cached)).toBeUndefined(); + expect( + codexRateLimitsToUpdate({ primary: { ...cached.primary, resetsAt: 1_784_001_000 } }, cached) + ?.windows, + ).toHaveLength(1); + expect( + codexRateLimitsToUpdate({ primary: { ...cached.primary, usedPercent: 76 } }, cached) + ?.windows[0]?.usedPercent, + ).toBe(76); + }); + it("carries only the windows the notification names", () => { expect( codexRateLimitsToUpdate({ diff --git a/apps/server/src/provider/codexUsageLimits.ts b/apps/server/src/provider/codexUsageLimits.ts index f8718cdda03d9..d4f9c621119df 100644 --- a/apps/server/src/provider/codexUsageLimits.ts +++ b/apps/server/src/provider/codexUsageLimits.ts @@ -135,8 +135,20 @@ export function codexRateLimitsToLimits(input: { export function codexRateLimitsToUpdate( snapshot: CodexRateLimitSnapshot, + previous?: CodexRateLimitSnapshot, ): ProviderUsageLimitsUpdate | undefined { - const windows = codexRateLimitsToWindows(snapshot); + const previousWindows = previous ? codexRateLimitsToWindows(previous) : []; + // Token ticks repeat session-cached limits that may predate an account probe or reset. + const windows = codexRateLimitsToWindows(snapshot).filter((window) => { + const existing = previousWindows.find((candidate) => candidate.id === window.id); + return ( + !existing || + existing.kind !== window.kind || + existing.usedPercent !== window.usedPercent || + existing.resetsAt !== window.resetsAt || + existing.windowDurationMins !== window.windowDurationMins + ); + }); return windows.length > 0 ? { windows } : undefined; } diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d8ce9095f5b79..cf9445c4e2549 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -134,6 +134,7 @@ const layerVcs = Layer.empty.pipe( Layer.provideMerge(layerGitWorkflow), Layer.provideMerge(layerReview), Layer.provideMerge(layerSourceControlRepositoryService), + // Coder: no GitHub app sign-in service; GitLab uses the workspace's `glab` login. Layer.provideMerge(layerProjectCloneTracker), Layer.provideMerge( VcsStatusBroadcaster.layer.pipe( diff --git a/apps/server/src/sourceControl/ServerSourceControlHost.ts b/apps/server/src/sourceControl/ServerSourceControlHost.ts index aed4011bf1ad6..9208997f67fc0 100644 --- a/apps/server/src/sourceControl/ServerSourceControlHost.ts +++ b/apps/server/src/sourceControl/ServerSourceControlHost.ts @@ -15,6 +15,7 @@ export const layer = Layer.effect( const git = yield* GitVcsDriver.GitVcsDriver; const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry; return SourceControlHost.SourceControlHost.of({ + // Coder: no `update`; see SourceControlHost. settings: { get: serverSettings.getSettings }, process: { run: process.run }, git: { diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index ef5c93384e0e9..354cc10b16402 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -435,6 +435,133 @@ it.layer( }), ); + // Which client owns the shared PTY size is left open by the issue, so this only asserts + // that every attached renderer is told the grid the PTY actually has. + it.effect("tells every attached stream the shared PTY size when attaches disagree", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const wideEvents: TerminalAttachStreamEvent[] = []; + const narrowEvents: TerminalAttachStreamEvent[] = []; + const stopWide = yield* manager.attachStream(openInput({ cols: 130, rows: 15 }), (event) => + Effect.sync(() => { + wideEvents.push(event); + }), + ); + yield* Effect.addFinalizer(() => Effect.sync(stopWide)); + const stopNarrow = yield* manager.attachStream(openInput({ cols: 54, rows: 15 }), (event) => + Effect.sync(() => { + narrowEvents.push(event); + }), + ); + yield* Effect.addFinalizer(() => Effect.sync(stopNarrow)); + + const spawned = ptyAdapter.spawnInputs[0]!; + const ptySize = ptyAdapter.processes[0]!.resizeCalls.at(-1) ?? { + cols: spawned.cols, + rows: spawned.rows, + }; + const lastReportedSize = (events: ReadonlyArray) => { + for (const event of events.toReversed()) { + const source: Record = + event.type === "snapshot" ? event.snapshot : event; + if (typeof source.cols === "number" && typeof source.rows === "number") { + return { cols: source.cols, rows: source.rows }; + } + } + return null; + }; + + expect({ + wide: lastReportedSize(wideEvents), + narrow: lastReportedSize(narrowEvents), + }).toEqual({ wide: ptySize, narrow: ptySize }); + }), + ); + + it.effect("gives the PTY back to the remaining viewer when the narrowest one detaches", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const restored = yield* Deferred.make(); + const stopWide = yield* manager.attachStream( + openInput({ cols: 130, rows: 15 }), + (event) => + event.type === "activity" && event.cols === 130 && event.rows === 15 + ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid) + : Effect.void, + undefined, + "wide", + ); + yield* Effect.addFinalizer(() => Effect.sync(stopWide)); + const stopNarrow = yield* manager.attachStream( + openInput({ cols: 54, rows: 15 }), + () => Effect.void, + undefined, + "narrow", + ); + const process = ptyAdapter.processes[0]!; + + yield* manager.resize( + { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 80, rows: 12 }, + "narrow", + ); + // A resize from a client with no attached stream cannot override attached viewers. + yield* manager.resize({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cols: 200, + rows: 50, + }); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 80, rows: 12 }); + + stopNarrow(); + yield* Deferred.await(restored); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 }); + }), + ); + + // Client retries resend the first attach's size, which a later resize may have replaced. + it.effect("keeps a viewer's resized grid when the same viewer attaches again", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const restored = yield* Deferred.make(); + const stopWide = yield* manager.attachStream( + openInput({ cols: 130, rows: 15 }), + (event) => + event.type === "activity" && event.cols === 130 && event.rows === 15 + ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid) + : Effect.void, + undefined, + "wide", + ); + yield* Effect.addFinalizer(() => Effect.sync(stopWide)); + const stopFirst = yield* manager.attachStream( + openInput({ cols: 54, rows: 15 }), + () => Effect.void, + undefined, + "phone", + ); + const process = ptyAdapter.processes[0]!; + yield* manager.resize( + { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 100, rows: 15 }, + "phone", + ); + + const stopRetry = yield* manager.attachStream( + { ...openInput({ cols: 54, rows: 15 }), resume: true }, + () => Effect.void, + undefined, + "phone", + ); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 100, rows: 15 }); + + stopRetry(); + stopFirst(); + yield* Deferred.await(restored); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 }); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); + it.effect("resumed attaches after close never respawn until the terminal is reopened", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); @@ -1541,6 +1668,53 @@ it.layer( }).pipe(Effect.scoped), ); + it.effect.each([ + { recovered: true, label: "after recovery" }, + { recovered: false, label: "when cancelled before recovery" }, + ])("keeps a stalled viewer's size until its attach stream ends ($label)", ({ recovered }) => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const restored = yield* Deferred.make(); + const stopWide = yield* manager.attachStream( + openInput({ cols: 130, rows: 15 }), + (event) => + event.type === "activity" && event.cols === 130 && event.rows === 15 + ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid) + : Effect.void, + undefined, + "wide", + ); + yield* Effect.addFinalizer(() => Effect.sync(stopWide)); + const process = ptyAdapter.processes[0]!; + + yield* Effect.gen(function* () { + const pull = yield* Stream.toPull( + manager.attachOutputStream(openInput({ cols: 54, rows: 15 }), "narrow"), + ); + expect(yield* pull).toMatchObject([{ type: "snapshot" }]); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 54, rows: 15 }); + // Overflow releases the inner subscription before any recovery pull. + yield* publishPastOutputBudget(manager, process); + yield* manager.resize( + { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 50, rows: 12 }, + "narrow", + ); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 50, rows: 12 }); + if (!recovered) return; + + expect(yield* pull).toMatchObject([{ type: "snapshot" }]); + yield* manager.resize( + { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 48, rows: 12 }, + "narrow", + ); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 48, rows: 12 }); + }).pipe(Effect.scoped); + + yield* Deferred.await(restored); + expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 }); + }).pipe(Effect.scoped), + ); + it.effect("does not replay in-flight output already included in an observer snapshot", () => Effect.gen(function* () { const { manager, ptyAdapter } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 0f2edfcc69f22..0fd300dbd8a0f 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -54,6 +54,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; import * as ServerConfig from "../config.ts"; @@ -64,6 +65,7 @@ import { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceReg import * as ServerSettings from "../serverSettings.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ProcessRunner from "../processRunner.ts"; +import { terminalOutputStream } from "./OutputProtocol.ts"; import * as PtyAdapter from "@t3tools/shared/PtyAdapter"; export { @@ -158,12 +160,27 @@ export class TerminalManager extends Context.Service< input: TerminalOpenInput, ) => Effect.Effect; + /** + * Attached viewers share one PTY sized to the smallest of them, so a narrow client + * still sees the whole TUI. Streams and resizes with the same `viewerId` (one client + * connection) count as one viewer; streams without one are each their own viewer. + */ readonly attachStream: ( input: TerminalAttachInput, listener: (event: TerminalAttachStreamEvent) => Effect.Effect, registerCleanup?: (stop: () => void) => void, + viewerId?: string, ) => Effect.Effect<() => void, TerminalError>; + /** + * The `terminal.attach` RPC stream. Overflow recovery swaps the inner subscription, so + * `viewerId` and the size it reported stay attached until the whole stream ends. + */ + readonly attachOutputStream: ( + input: TerminalAttachInput, + viewerId: string, + ) => Stream.Stream; + readonly observeStream: ( input: TerminalObserveInput, listener: (event: TerminalAttachStreamEvent) => Effect.Effect, @@ -178,7 +195,10 @@ export class TerminalManager extends Context.Service< readonly write: (input: TerminalWriteInput) => Effect.Effect; - readonly resize: (input: TerminalResizeInput) => Effect.Effect; + readonly resize: ( + input: TerminalResizeInput, + viewerId?: string, + ) => Effect.Effect; readonly clear: (input: TerminalClearInput) => Effect.Effect; @@ -273,6 +293,17 @@ interface TerminalSessionState { runtimeEnv: Record | null; } +interface TerminalGrid { + readonly cols: number; + readonly rows: number; +} + +/** One client connection attached to a terminal, possibly through several streams. */ +interface TerminalViewer { + streams: number; + grid: TerminalGrid | null; +} + interface PersistHistoryRequest { history: BoundedTerminalHistory; immediate: boolean; @@ -355,6 +386,8 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { updatedAt: session.updatedAt, sequence: session.eventSequence, attachEpoch: session.attachEpoch, + cols: session.cols, + rows: session.rows, }; } @@ -1683,6 +1716,104 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func effect: Effect.Effect, ): Effect.Effect => threadLocks.withLock(threadId, effect); + const terminalViewers = new Map>(); + let anonymousViewerCount = 0; + + const retainViewer = (sessionKey: string, viewerId: string, grid: TerminalGrid | null) => { + let viewers = terminalViewers.get(sessionKey); + if (!viewers) { + viewers = new Map(); + terminalViewers.set(sessionKey, viewers); + } + const viewer = viewers.get(viewerId); + if (viewer) { + viewer.streams += 1; + // After a viewer's first size, resizes own it; attach retries resend the original size. + viewer.grid ??= grid; + } else { + viewers.set(viewerId, { streams: 1, grid }); + } + }; + + /** Returns whether the viewer left, which can grow the shared grid. */ + const releaseViewer = (sessionKey: string, viewerId: string) => { + const viewers = terminalViewers.get(sessionKey); + const viewer = viewers?.get(viewerId); + if (!viewers || !viewer) return false; + viewer.streams -= 1; + if (viewer.streams > 0) return false; + viewers.delete(viewerId); + if (viewers.size === 0) terminalViewers.delete(sessionKey); + return true; + }; + + // The smallest attached viewer bounds each axis, so every viewer can draw the whole grid. + const sharedViewerGrid = (sessionKey: string): TerminalGrid | null => { + let shared: TerminalGrid | null = null; + for (const viewer of terminalViewers.get(sessionKey)?.values() ?? []) { + if (!viewer.grid) continue; + shared = shared + ? { + cols: Math.min(shared.cols, viewer.grid.cols), + rows: Math.min(shared.rows, viewer.grid.rows), + } + : viewer.grid; + } + return shared; + }; + + /** Attached viewers own the size; a caller's own size only applies when none has reported one. */ + const withSharedGrid = < + A extends { readonly cols?: number | undefined; readonly rows?: number | undefined }, + >( + sessionKey: string, + input: A, + ): A => { + const shared = sharedViewerGrid(sessionKey); + return shared ? { ...input, cols: shared.cols, rows: shared.rows } : input; + }; + + // Renderers draw the PTY grid, so every size change reaches them. It rides on activity + // because older clients reject unknown event types. + const resizeSession = Effect.fnUntraced(function* ( + session: TerminalSessionState, + process: PtyAdapter.PtyProcess, + cols: number, + rows: number, + ) { + yield* resizePtyProcess(session, process, cols, rows); + session.cols = cols; + session.rows = rows; + session.updatedAt = yield* nowIso; + const eventStamp = advanceEventSequence(session); + yield* publishEvent({ + type: "activity", + threadId: session.threadId, + terminalId: session.terminalId, + sequence: eventStamp.sequence, + hasRunningSubprocess: session.hasRunningSubprocess, + label: terminalWireLabel(session), + cols, + rows, + }); + }); + + const applySharedGrid = Effect.fnUntraced(function* (threadId: string, terminalId: string) { + const session = yield* getSession(threadId, terminalId); + if (Option.isNone(session)) return; + const process = session.value.process; + const shared = sharedViewerGrid(toSessionKey(threadId, terminalId)); + if ( + !process || + session.value.status !== "running" || + !shared || + (shared.cols === session.value.cols && shared.rows === session.value.rows) + ) { + return; + } + yield* resizeSession(session.value, process, shared.cols, shared.rows); + }); + const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* ( process: PtyAdapter.PtyProcess | null, ) { @@ -2704,12 +2835,13 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* ( - input: TerminalOpenInput, + requestedInput: TerminalOpenInput, ) { - const terminalId = input.terminalId; - yield* assertValidCwd(input.cwd); + const terminalId = requestedInput.terminalId; + yield* assertValidCwd(requestedInput.cwd); - const sessionKey = toSessionKey(input.threadId, terminalId); + const sessionKey = toSessionKey(requestedInput.threadId, terminalId); + const input = withSharedGrid(sessionKey, requestedInput); const existing = yield* getSession(input.threadId, terminalId); if (Option.isNone(existing)) { yield* flushPersist(input.threadId, terminalId); @@ -2825,10 +2957,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func } if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { - yield* resizePtyProcess(liveSession, liveSession.process, targetCols, targetRows); - liveSession.cols = targetCols; - liveSession.rows = targetRows; - liveSession.updatedAt = yield* nowIso; + yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows); } return snapshot(liveSession); @@ -2846,8 +2975,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)), ); - const openOrAttachForStream = Effect.fnUntraced(function* (input: TerminalAttachInput) { - const terminalId = input.terminalId; + const openOrAttachForStream = Effect.fnUntraced(function* (requestedInput: TerminalAttachInput) { + const terminalId = requestedInput.terminalId; + const input = withSharedGrid(toSessionKey(requestedInput.threadId, terminalId), requestedInput); const existing = yield* getSession(input.threadId, terminalId); if (Option.isNone(existing)) { @@ -2887,11 +3017,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func session.status === "running" && (session.cols !== targetCols || session.rows !== targetRows) ) { - const process = session.process; - yield* resizePtyProcess(session, process, targetCols, targetRows); - session.cols = targetCols; - session.rows = targetRows; - session.updatedAt = yield* nowIso; + yield* resizeSession(session, session.process, targetCols, targetRows); } return snapshot(session); @@ -3059,11 +3185,61 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func ); }; + /** Retains `viewer` and returns its release, which runs at most once. */ + const retainViewerOnce = ( + input: TerminalObserveInput, + viewer: string, + grid: TerminalGrid | null, + ) => { + const sessionKey = toSessionKey(input.threadId, input.terminalId); + retainViewer(sessionKey, viewer, grid); + let retained = true; + return () => { + if (!retained) return; + retained = false; + if (releaseViewer(sessionKey, viewer)) { + runFork(withThreadLock(input.threadId, applySharedGrid(input.threadId, input.terminalId))); + } + }; + }; + const attachStream: TerminalManager["Service"]["attachStream"] = ( input, listener, registerCleanup, - ) => streamSession(input, openOrAttachForStream(input), listener, registerCleanup, input); + viewerId, + ) => { + const viewer = viewerId ?? `stream:${++anonymousViewerCount}`; + let detach = () => {}; + const initial = Effect.suspend(() => { + detach = retainViewerOnce( + input, + viewer, + input.cols !== undefined && input.rows !== undefined + ? { cols: input.cols, rows: input.rows } + : null, + ); + return openOrAttachForStream(input); + }); + return streamSession( + input, + initial, + listener, + registerCleanup && + ((stop) => + registerCleanup(() => { + stop(); + detach(); + })), + input, + ).pipe( + Effect.map((stop) => () => { + stop(); + detach(); + }), + Effect.onError(() => Effect.sync(detach)), + ); + }; const observeStream: TerminalManager["Service"]["observeStream"] = ( input, @@ -3091,6 +3267,21 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func registerCleanup, ); + const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = (input, viewerId) => + Stream.unwrap( + Effect.acquireRelease( + Effect.sync(() => retainViewerOnce(input, viewerId, null)), + (release) => Effect.sync(release), + ).pipe( + Effect.as( + terminalOutputStream( + (listener, registerCleanup) => attachStream(input, listener, registerCleanup, viewerId), + (listener, registerCleanup) => resyncStream(input, listener, registerCleanup), + ), + ), + ), + ); + const metadataEventFromTerminalEvent = ( event: TerminalEvent, ): Effect.Effect => { @@ -3197,23 +3388,36 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func }); }); - const resizeLocked = Effect.fn("terminal.resize")(function* (input: TerminalResizeInput) { + const resizeLocked = Effect.fn("terminal.resize")(function* ( + input: TerminalResizeInput, + viewerId: string | undefined, + ) { + const sessionKey = toSessionKey(input.threadId, input.terminalId); + const viewer = + viewerId === undefined ? undefined : terminalViewers.get(sessionKey)?.get(viewerId); + if (viewer) { + viewer.grid = { cols: input.cols, rows: input.rows }; + return yield* applySharedGrid(input.threadId, input.terminalId); + } + // A caller that is not attached cannot override the viewers that are. + if (sharedViewerGrid(sessionKey)) return; const session = yield* getSession(input.threadId, input.terminalId); if (Option.isNone(session)) { return; } const process = session.value.process; - if (!process || session.value.status !== "running") { + if ( + !process || + session.value.status !== "running" || + (session.value.cols === input.cols && session.value.rows === input.rows) + ) { return; } - yield* resizePtyProcess(session.value, process, input.cols, input.rows); - session.value.cols = input.cols; - session.value.rows = input.rows; - session.value.updatedAt = yield* nowIso; + yield* resizeSession(session.value, process, input.cols, input.rows); }); - const resize: TerminalManager["Service"]["resize"] = (input) => - withThreadLock(input.threadId, resizeLocked(input)); + const resize: TerminalManager["Service"]["resize"] = (input, viewerId) => + withThreadLock(input.threadId, resizeLocked(input, viewerId)); const clear: TerminalManager["Service"]["clear"] = (input) => withThreadLock( @@ -3301,6 +3505,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func return TerminalManager.of({ open, attachStream, + attachOutputStream, observeStream, resyncStream, write, diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index a63eeb3134c0a..d78c494481575 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -148,6 +148,74 @@ it.live.each(["thread", "shell"] as const)( }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); +it.effect("coalesces streaming replay before synchronization and the live tail", () => + Effect.gen(function* () { + const store = yield* OrchestrationEventStore.OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + const threadId = ThreadId.make("thread:streaming-replay"); + const now = "2026-10-27T00:00:00.000Z"; + const insert = (version: number, text: string, streaming: boolean) => sql<{ + sequence: number; + }>` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + ${`streaming-replay:${version}`}, 'thread', ${threadId}, ${version}, 'message.updated', + ${now}, 'server', ${JSON.stringify({ + createdBy: "agent", + creationSource: "web", + id: "message:streaming-replay", + threadId, + runId: null, + nodeId: null, + role: "assistant", + text, + attachments: [], + streaming, + createdAt: now, + updatedAt: now, + })}, '{}', 2 + ) RETURNING sequence + `; + yield* insert(0, "H", true); + yield* insert(1, "He", true); + const [latest] = yield* insert(2, "Hello", true); + const [completed] = yield* insert(3, "Hello!", false); + const items = yield* subscribeOrchestrationV2Thread({ + threadId, + afterSequence: 0, + requestCompletionMarker: true, + }).pipe( + Effect.flatMap(Stream.runCollect), + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => + Stream.unwrap( + insert(4, "Next", false).pipe( + Effect.map(() => + store.readAgentEvents({ threadId, afterSequence: completed!.sequence }), + ), + ), + ), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + assert.deepEqual( + items.map((item) => + item.kind === "event" + ? [item.sequence, item.event.type === "message.updated" ? item.event.payload.text : null] + : [item.kind], + ), + [ + [latest!.sequence, "Hello"], + [completed!.sequence, "Hello!"], + ["synchronized"], + [completed!.sequence + 1, "Next"], + ], + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + it.effect("shell snapshots omit idle children and older settled threads only on request", () => Effect.gen(function* () { const shell = ( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index deb67d732a2fc..9cc46ebde85c5 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -87,7 +87,10 @@ import { type ShellApplicationEvent, } from "./orchestration-v2/ShellStream.ts"; import { ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION } from "./orchestration-v2/ProjectionStore.ts"; -import { coalesceThreadLiveStream } from "./orchestration-v2/ThreadLiveEventCoalescer.ts"; +import { + coalesceLiveUpdatedEvents, + coalesceThreadLiveStream, +} from "./orchestration-v2/ThreadLiveEventCoalescer.ts"; import { buildBoundedThreadStreamSnapshot, decideThreadResume, @@ -561,7 +564,9 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs // Retained creation events may describe deleted threads; replace replay only if a snapshot exists. if (shell !== null) return yield* snapshotThenLive(); } - const replay = yield* loadReplayThrough(input.afterSequence, highWater); + const replay = coalesceLiveUpdatedEvents( + yield* loadReplayThrough(input.afterSequence, highWater), + ); const plan = decideThreadResume({ afterSequence: input.afterSequence, highWater, @@ -872,6 +877,10 @@ const layerWsRpc = () => const pullRequestSync = yield* PullRequestSyncReactor.PullRequestSyncReactor; const orchestrationEngine = yield* Orchestrator.OrchestratorV2; const crypto = yield* Crypto.Crypto; + // RPC client ids are only unique within one socket; terminals share viewers across sockets. + const terminalViewerPrefix = yield* crypto.randomUUIDv4().pipe(Effect.orDie); + const terminalViewerId = (metadata: { readonly client: { readonly id: number } }) => + `${terminalViewerPrefix}:${metadata.client.id}`; const serverCommandId = (tag: string) => crypto.randomUUIDv4().pipe( Effect.orDie, @@ -1474,6 +1483,7 @@ const layerWsRpc = () => sourceControlRepositories.lookupRepository(input), [WS_METHODS.sourceControlCloneRepository]: (input) => sourceControlRepositories.cloneRepository(input), + // Coder: no GitHub app sign-in or app access; GitLab uses the workspace's `glab` login. [WS_METHODS.projectCloneStart]: (input) => projectCloneTracker.start(input, { createProject: (project) => @@ -1782,15 +1792,11 @@ const layerWsRpc = () => vcsProvisioning.initRepository(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input), [WS_METHODS.terminalOpen]: (input) => terminalManager.open(input), - [WS_METHODS.terminalAttach]: (input) => - terminalOutputStream( - (listener, registerCleanup) => - terminalManager.attachStream(input, listener, registerCleanup), - (listener, registerCleanup) => - terminalManager.resyncStream(input, listener, registerCleanup), - ), + [WS_METHODS.terminalAttach]: (input, metadata) => + terminalManager.attachOutputStream(input, terminalViewerId(metadata)), [WS_METHODS.terminalWrite]: (input) => terminalManager.write(input), - [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input), + [WS_METHODS.terminalResize]: (input, metadata) => + terminalManager.resize(input, terminalViewerId(metadata)), [WS_METHODS.terminalClear]: (input) => terminalManager.clear(input), [WS_METHODS.terminalClose]: (input) => terminalManager.close(input), [WS_METHODS.terminalObserve]: (input) => diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 1812d2f6064ca..da7ff1e2c2cb5 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -352,7 +352,7 @@ function SidebarControl() { export function AppSidebarLayout({ children }: { children: ReactNode }) { const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads"); - // Coder: no legacy sidebar and no desktop window bridge (fullscreen insets, menu actions). + // Coder: no desktop window bridge (fullscreen insets, menu actions). const [sidebarRouteReveal] = useState(() => ({ observedKey: null, pendingKey: null, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index c970ff8d3129f..11d839875a8fc 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -877,13 +877,15 @@ const CHAT_MARKDOWN_COMPONENTS = { const text = use(ChatMarkdownTextContext); const citation = href ? parseAssistantCitationHref(href) : null; if (citation) return ; - const linkedThreadId = href ? parseThreadLinkHref(href) : null; - if (linkedThreadId) { - const label = hastPlainTextDeep(node) || linkedThreadId; + const threadLink = href ? parseThreadLinkHref(href) : null; + if (threadLink) { + const written = hastPlainTextDeep(node); + // An autolink's text is its own URL, which is no label. + const label = written && parseThreadLinkHref(written) === null ? written : null; return environmentId ? ( - + ) : ( - {label} + {label ?? "Thread"} ); } const contextReference = href ? parseComposerContextHref(href) : null; @@ -1235,6 +1237,7 @@ const CHAT_MARKDOWN_COMPONENTS = { /> ); } + // Coder: no guest page, so no host image route (#26323); images load from the workspace. if (imageSource._tag === "WorkspaceFile" && threadRef) { return ( >( + () => new Set(), + ); + const onHeldRequestIdsChange = useStableCallback((requestIds: ReadonlySet) => { + setHeldApprovalRequestIds((current) => (shallow(current, requestIds) ? current : requestIds)); + }); const activeProposedPlan = (() => { if (!latestRunSettled) { return null; @@ -2121,6 +2128,7 @@ export default function ChatView(props: ChatViewProps) { closePreviewPanelStable, copyRightPanelFilePathStable, moveRightPanelSurfaceStable, + onOpenToolDiffStable, onOpenTurnDiffStable, openChangesFromThreadPanelStable, openFileSurfaceStable, @@ -2932,6 +2940,11 @@ export default function ChatView(props: ChatViewProps) { className="relative flex min-h-0 flex-1 flex-col bg-background" > selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef), ); + const toolCallSelection = diffSelection.kind === "tool-call" ? diffSelection : null; + const isGitSelection = diffSelection.kind === "branch" || diffSelection.kind === "unstaged"; + const toolCallItems = useQuietThreadVisibleTurnItems(toolCallSelection ? routeThreadRef : null); + const toolCallDetail = useTurnItemDetail( + toolCallSelection && routeThreadRef + ? { + ...resolveToolCallDiffTarget(toolCallSelection, toolCallItems), + environmentId: routeThreadRef.environmentId, + } + : null, + ); + const toolCallItem = toolCallDetail.data?.item; const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadRef); const orderedTurnDiffSummaries = turnDiffSummaries.toSorted((left, right) => { @@ -288,24 +307,31 @@ export default function DiffPanel({ orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn?.checkpointTurnCount; const latestTurn = orderedTurnDiffSummaries[0]; - const selectedScopeLabel = - selectedRunId === null + const selectedScopeLabel = toolCallSelection + ? "Tool call" + : selectedRunId === null ? selectedGitScope === "unstaged" ? "Uncommitted" : "Changes" : selectedTurn?.runId === latestTurn?.runId ? "Latest turn" : `Turn ${selectedCheckpointTurnCount ?? "?"}`; - const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope; + const reviewSectionId = toolCallSelection + ? `tool-call:${toolCallSelection.threadId}:${toolCallSelection.itemId}` + : selectedTurn + ? `turn:${selectedTurn.runId}` + : selectedGitScope; const collapseScopeKey = routeThreadRef ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` : null; const codeViewMountKey = `${collapseScopeKey ?? reviewSectionId}:${codeViewRevision}`; - const reviewSectionTitle = selectedTurn - ? `Turn ${selectedCheckpointTurnCount ?? "?"}` - : selectedGitScope === "unstaged" - ? "Uncommitted" - : "Changes"; + const reviewSectionTitle = toolCallSelection + ? "Tool call" + : selectedTurn + ? `Turn ${selectedCheckpointTurnCount ?? "?"}` + : selectedGitScope === "unstaged" + ? "Uncommitted" + : "Changes"; const selectedCheckpointRange = typeof selectedCheckpointTurnCount === "number" ? { @@ -325,7 +351,7 @@ export default function DiffPanel({ { enabled: isGitRepo && selectedTurn !== undefined }, ); const branchDiffPreviewInput = - canReadFiles && selectedRunId === null && activeThread && activeCwd + canReadFiles && isGitSelection && activeThread && activeCwd ? { cwd: activeCwd, ...(selectedBaseRef ? { baseRef: selectedBaseRef } : {}), @@ -336,7 +362,7 @@ export default function DiffPanel({ } : undefined; const canRefreshGitDiff = - isGitRepo && selectedRunId === null && activeThread != null && activeCwd != null; + isGitRepo && isGitSelection && activeThread != null && activeCwd != null; // Read under the workspace mutation id, so each mutation refetches the diff; the panel stays // mounted while hidden, so a mutation made then is already reflected when it shows. const branchDiffPreview = useEnvironmentQuery( @@ -363,25 +389,52 @@ export default function DiffPanel({ const preview = branchDiffPreview.data; const gitDiff = selectedGitSource?.diff; - const selectedPatch = selectedTurn ? activeCheckpointDiff.data?.diff : gitDiff; - const isSelectedPatchTruncated = !selectedTurn && selectedGitSource?.truncated === true; - const selectedPatchQuery = selectedTurn ? activeCheckpointDiff : branchDiffPreview; + const toolCallPreview = + toolCallSelection && toolCallItem?.type === "file_change" ? toolCallDiff(toolCallItem) : null; + const selectedPatch = toolCallSelection + ? toolCallPreview?.patch + : selectedTurn + ? activeCheckpointDiff.data?.diff + : gitDiff; + const isSelectedPatchTruncated = + toolCallPreview?.truncated === true || + (isGitSelection && selectedGitSource?.truncated === true); + const selectedPatchQuery = toolCallSelection + ? toolCallDetail + : selectedTurn + ? activeCheckpointDiff + : branchDiffPreview; const isLoadingSelectedPatch = selectedPatchQuery.isPending && selectedPatchQuery.data === null; - const selectedPatchError = selectedTurn ? activeCheckpointDiff.error : branchDiffPreview.error; + const selectedPatchError = toolCallSelection + ? toolCallDetail.error + : selectedTurn + ? activeCheckpointDiff.error + : branchDiffPreview.error; const hasResolvedPatch = typeof selectedPatch === "string"; const hasNoNetChanges = hasResolvedPatch && selectedPatch.trim().length === 0; const lazySource = - !selectedTurn && selectedGitSource?.truncated && selectedGitSource.files + isGitSelection && selectedGitSource?.truncated && selectedGitSource.files ? selectedGitSource : null; const renderablePatch = getRenderablePatch( lazySource ? undefined : selectedPatch, `diff-panel:${resolvedTheme}`, - { compactPartialHunkOffsets: selectedRunId === null }, + { + compactPartialHunkOffsets: isGitSelection, + ...(toolCallSelection ? { ignoreWhitespace: diffIgnoreWhitespace } : {}), + }, ); + const recordedToolCallFileCount = + toolCallSelection && toolCallItem?.type === "file_change" + ? (toolCallItem.changes?.length ?? 0) + : 0; + const omittedToolCallFiles = + renderablePatch?.kind === "files" + ? Math.max(0, recordedToolCallFileCount - renderablePatch.files.length) + : 0; const fileStats = new Map(lazySource?.files?.map((file) => [file.path, file])); const sourceLineStat = - !selectedTurn && selectedGitSource?.files + isGitSelection && selectedGitSource?.files ? selectedGitSource.files.reduce( (total, file) => ({ additions: total.additions + file.additions, @@ -396,7 +449,7 @@ export default function DiffPanel({ : null; // Coder: expanded context is read in bounded chunks over the helper RPC. const currentLoadDiffFiles = - selectedRunId === null && + isGitSelection && activeThread && preview && selectedGitSource && @@ -440,10 +493,7 @@ export default function DiffPanel({ return currentLoadDiffFiles(fileDiff); }); const localBranchRefs = useEnvironmentQuery( - selectedRunId === null && - selectedGitScope === "branch" && - activeThread && - branchDiffPreview.data?.cwd + isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { @@ -457,10 +507,7 @@ export default function DiffPanel({ : null, ); const remoteBranchRefs = useEnvironmentQuery( - selectedRunId === null && - selectedGitScope === "branch" && - activeThread && - branchDiffPreview.data?.cwd + isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { @@ -655,8 +702,9 @@ export default function DiffPanel({ useDiffPanelStore.getState().selectBranchBaseRef(routeThreadRef, baseRef); }; const selectedTurnValue = selectedTurn ? `turn:${selectedTurn.runId}` : ""; - const selectedScopeValue = - selectedRunId === null + const selectedScopeValue = toolCallSelection + ? "" + : selectedRunId === null ? selectedGitScope : selectedTurn?.runId === latestTurn?.runId ? "latest" @@ -723,7 +771,7 @@ export default function DiffPanel({ - {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && ( + {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
- {codeViewFiles.length > 0 || (!selectedTurn && selectedGitSource?.files?.length) ? ( + {codeViewFiles.length > 0 || (isGitSelection && selectedGitSource?.files?.length) ? ( Select a thread to inspect turn diffs.
- ) : !isGitRepo ? ( + ) : !isGitRepo && !toolCallSelection ? (
Turn diffs are unavailable because this project is not a git repository.
@@ -1006,7 +1054,7 @@ export default function DiffPanel({
No completed turns yet.
- ) : selectedRunId === null && !canReadFiles ? ( + ) : isGitSelection && !canReadFiles ? ( fileAccess.isPending ? ( ) : ( @@ -1020,7 +1068,13 @@ export default function DiffPanel({ {isSelectedPatchTruncated && !lazySource && (

This preview exceeds the size limit. Changes shown are incomplete. - {selectedGitSource?.files ? " Totals include all changes." : ""} + {isGitSelection && selectedGitSource?.files ? " Totals include all changes." : ""} +

+ )} + {omittedToolCallFiles > 0 && ( +

+ This tool call changed {recordedToolCallFileCount} files. The recorded patch omits{" "} + {omittedToolCallFiles} of them.

)} {selectedPatchError && !renderablePatch && ( @@ -1028,15 +1082,36 @@ export default function DiffPanel({

{selectedPatchError}

)} - {!renderablePatch && !lazySource ? ( + {!renderablePatch && toolCallPreview && toolCallPreview.content.length > 0 ? ( +
+

+ The provider recorded file content without a diff. +

+ {toolCallPreview.content.map(({ label, text }) => ( +
+

{label}

+
+                      {text === "" ? "Empty content." : text}
+                    
+
+ ))} +
+ ) : !renderablePatch && !lazySource ? ( isLoadingSelectedPatch ? ( ) : ( diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 1bf7a930c1f24..93f3fb342fb9e 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -32,7 +32,11 @@ import { type SidebarListMarker, type SidebarSection, resolveSidebarDropVerb, + groupSidebarThreadsByProject, + resolveSidebarFolderDot, + sidebarFolderExpansionKeys, } from "./Sidebar.logic"; +import { resolveProjectExpanded } from "../uiStateStore"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts"; @@ -1348,3 +1352,97 @@ describe("resolveSidebarRouteReveal", () => { ).toEqual({ pendingKey: hiddenKey, widensScope: false }); }); }); + +describe("sidebarFolderExpansionKeys", () => { + it("honors a collapse the legacy sidebar saved under a member's cwd", () => { + const keys = sidebarFolderExpansionKeys({ + projectKey: "github.com/pingdotgg/t3code", + memberProjects: [{ physicalProjectKey: "local:/code/t3code", workspaceRoot: "/code/t3code" }], + }); + const cwdKey = keys.at(-1)!; + + expect(resolveProjectExpanded({}, keys)).toBe(true); + expect(resolveProjectExpanded({ [cwdKey]: false }, keys)).toBe(false); + expect(resolveProjectExpanded({ [keys[0]!]: true, [cwdKey]: false }, keys)).toBe(true); + }); +}); + +describe("groupSidebarThreadsByProject", () => { + it("puts each thread in its project's folder and keeps empty projects", () => { + const remoteEnvironmentId = EnvironmentId.make("environment-remote"); + const t3code = ProjectId.make("t3code"); + const t3codeRemote = ProjectId.make("t3code-remote"); + const fleet = ProjectId.make("fleet"); + const thread = (id: string, environmentId: EnvironmentId, projectId: ProjectId) => ({ + id, + environmentId, + projectId, + }); + const groups = [ + { + projectKey: "t3code", + memberProjectRefs: [ + { environmentId: localEnvironmentId, projectId: t3code }, + { environmentId: remoteEnvironmentId, projectId: t3codeRemote }, + ], + }, + { + projectKey: "fleet", + memberProjectRefs: [{ environmentId: localEnvironmentId, projectId: fleet }], + }, + ]; + + const folders = groupSidebarThreadsByProject(groups, [ + thread("a", localEnvironmentId, t3code), + thread("orphan", localEnvironmentId, ProjectId.make("deleted")), + thread("b", remoteEnvironmentId, t3codeRemote), + ]); + + expect( + folders.map((folder) => ({ + projectKey: folder.group.projectKey, + threads: folder.threads.map((entry) => entry.id), + })), + ).toEqual([ + { projectKey: "t3code", threads: ["a", "b"] }, + { projectKey: "fleet", threads: [] }, + ]); + }); +}); + +describe("resolveSidebarFolderDot", () => { + it("flags the most urgent hidden thread and stays quiet otherwise", () => { + const idle = { + hasActionableProposedPlan: false, + hasPendingApprovals: false, + hasPendingUserInput: false, + interactionMode: "default" as const, + latestRun: makeLatestRun(), + lastVisitedAt: "2026-03-09T10:06:00.000Z", + runtime: null, + }; + const runtime = { + status: "running" as const, + activeRunId: null, + providerInstanceId: ProviderInstanceId.make("codex"), + providerName: "Codex", + lastError: null, + updatedAt: "2026-03-09T10:00:00.000Z", + }; + const working = { ...idle, runtime }; + const unread = { ...idle, lastVisitedAt: "2026-03-09T10:04:00.000Z" }; + const limited = { + ...idle, + runtime: { ...runtime, status: "failed" as const, lastErrorClass: "usage_limit" as const }, + }; + + expect(resolveSidebarFolderDot([idle])).toBeNull(); + // A waiting thread stays quiet even with an unread completion, like its row. + expect( + resolveSidebarFolderDot([{ ...unread, runtime: { ...runtime, status: "idle" as const } }]), + ).toBeNull(); + expect(resolveSidebarFolderDot([idle, working])).toBe("working"); + expect(resolveSidebarFolderDot([working, unread])).toBe("unread"); + expect(resolveSidebarFolderDot([unread, limited])).toBe("attention"); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index e77fef5ef162f..2a5895bbb6d5b 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -35,6 +35,7 @@ import { isLatestRunSettled } from "../session-logic"; import { observeIntersection } from "../lib/observeIntersection"; import { deadlineAfter, deadlineStore } from "@t3tools/client-runtime/clock"; import { useDeadlinePassed } from "../hooks/useDeadline"; +import { legacyProjectCwdPreferenceKey } from "../uiStateStore"; export function shouldNavigateAfterThreadPark(input: { readonly threadKey: string; @@ -52,7 +53,6 @@ export function shouldNavigateAfterThreadPark(input: { ); } -const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]"; const THREAD_JUMP_HINT_SHOW_DELAY_MS = 200; export function resolveSidebarRowAccessibility(input: { @@ -68,8 +68,6 @@ export function resolveSidebarRowAccessibility(input: { } // Each prewarm retains growing thread detail and a live subscription, multiplying heap and server load. -const SIDEBAR_THREAD_PREWARM_LIMIT = 3; - const SIDEBAR_ROW_SUBSCRIPTION_OVERSCAN_PX = 160; export function useSidebarRowSubscriptionLease(isActive: boolean): { @@ -544,21 +542,6 @@ export async function archiveSelectedThreadEntries< return { archivedThreadKeys, mutationFailure: null, followupFailures }; } -export function buildMultiSelectThreadContextMenuItems(input: { - count: number; - hasRunningThread: boolean; -}): readonly ContextMenuItem<"mark-unread" | "archive" | "delete">[] { - return [ - { id: "mark-unread", label: `Mark unread (${input.count})` }, - { - id: "archive", - label: `Archive (${input.count})`, - disabled: input.hasRunningThread, - }, - { id: "delete", label: `Delete (${input.count})`, destructive: true }, - ]; -} - export function isSidebarSubagentThread(thread: Pick): boolean { return thread.lineage.relationshipToParent === "subagent"; } @@ -722,11 +705,6 @@ function hasUnseenFailure(thread: ThreadStatusInput): boolean { return completedAt > lastVisitedAt; } -export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null): boolean { - if (target === null) return true; - return !target.closest(THREAD_SELECTION_SAFE_SELECTOR); -} - // Suppress trailing double-click navigation; keyboard and synthetic clicks use detail 0. export function isTrailingDoubleClick(detail: number): boolean { return detail > 1; @@ -795,13 +773,6 @@ export function orderItemsByPreferredIds(input: { return [...ordered, ...remaining]; } -export function getSidebarThreadIdsToPrewarm( - visibleThreadIds: readonly TThreadId[], - limit = SIDEBAR_THREAD_PREWARM_LIMIT, -): TThreadId[] { - return visibleThreadIds.slice(0, Math.max(0, limit)); -} - export function resolveAdjacentThreadId(input: { threadIds: readonly T[]; currentThreadId: T | null; @@ -829,15 +800,6 @@ export function resolveAdjacentThreadId(input: { return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null; } -export function isContextMenuPointerDown(input: { - button: number; - ctrlKey: boolean; - isMac: boolean; -}): boolean { - if (input.button === 2) return true; - return input.isMac && input.button === 0 && input.ctrlKey; -} - export type SidebarThreadStatus = | "approval" | "input" @@ -909,6 +871,92 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si return "ready"; } +/** + * The dot on a closed boring-sidebar folder: the most urgent state among its + * hidden threads. Waiting threads stay quiet, like their rows. + */ +export function resolveSidebarFolderDot( + threads: ReadonlyArray, +): "attention" | "failed" | "unread" | "working" | null { + const statuses = new Set(threads.map(resolveSidebarThreadStatus)); + if ( + statuses.has("input") || + statuses.has("approval") || + statuses.has("request") || + statuses.has("limited") + ) { + return "attention"; + } + if (statuses.has("failed")) return "failed"; + // Rows show Done only for ready threads, so the dot follows the same rule. + const hasUnread = threads.some( + (thread) => resolveSidebarThreadStatus(thread) === "ready" && hasUnseenCompletion(thread), + ); + if (hasUnread) return "unread"; + if (statuses.has("working")) return "working"; + return null; +} + +/** + * Keys the old per-project sidebar saved folder open state under, most + * specific first, for `resolveProjectExpanded`. Boring folders read and write + * the same keys, so a legacy user's closed folders stay closed after regrouping. + */ +export function sidebarFolderExpansionKeys(group: { + readonly projectKey: string; + readonly memberProjects: ReadonlyArray<{ + readonly physicalProjectKey: string; + readonly workspaceRoot: string; + }>; +}): string[] { + return [ + group.projectKey, + ...group.memberProjects.map((member) => member.physicalProjectKey), + ...group.memberProjects.map((member) => legacyProjectCwdPreferenceKey(member.workspaceRoot)), + ]; +} + +/** + * Boring sidebar folders. Folders follow `groups` order and include empty + * projects so each one can start a thread. Threads keep their input order. + * A thread whose project is in no group has no folder and is left out. + */ +export function groupSidebarThreadsByProject< + TGroup extends { + readonly memberProjectRefs: ReadonlyArray<{ + readonly environmentId: EnvironmentId; + readonly projectId: string; + }>; + }, + TThread extends Pick, +>( + groups: readonly TGroup[], + threads: readonly TThread[], +): Array<{ group: TGroup; threads: TThread[] }> { + const folders = groups.map((group) => ({ group, threads: [] as TThread[] })); + const folderByProject = new Map(); + for (const folder of folders) { + for (const ref of folder.group.memberProjectRefs) { + folderByProject.set(`${ref.environmentId}:${ref.projectId}`, folder); + } + } + for (const thread of threads) { + folderByProject.get(`${thread.environmentId}:${thread.projectId}`)?.threads.push(thread); + } + return folders; +} + +export type SidebarV2TopStatusKind = + | "approval" + | "done" + | "failed" + | "limited" + | "input" + | "request" + | "waiting" + | "woke" + | "working"; + export function firstValidTimestampMs( ...candidates: ReadonlyArray ): number { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8c9816fb50f41..ea094db865adb 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -110,7 +110,7 @@ import { getSidebarProjectSettingsKey, type SidebarProjectSnapshot, } from "../sidebarProjectGrouping"; -import { useUiStateStore } from "../uiStateStore"; +import { resolveProjectExpanded, useUiStateStore } from "../uiStateStore"; import { getThreadKeysToDeselectAfterDelete, useThreadSelectionStore, @@ -122,7 +122,7 @@ import { useTerminalFocus } from "../hooks/useTerminalFocus"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; import { startNewThreadFromContext } from "../lib/chatThreadActions"; -import { useClientSettings } from "../hooks/useSettings"; +import { useBoringSidebarEnabled, useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; @@ -165,6 +165,8 @@ import { import { applySidebarThreadDrop, filterSidebarV2VisibleThreads, + groupSidebarThreadsByProject, + sidebarFolderExpansionKeys, buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, deleteSelectedThreadEntries, @@ -243,6 +245,10 @@ import { type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; import { SidebarDraftBlock } from "./sidebar/SidebarDraftBlock"; +import { + SidebarProjectFolderHeader, + sidebarFolderRowId, +} from "./sidebar/SidebarProjectFolderHeader"; import { SidebarDragBoundary, SidebarSectionHeader, @@ -388,6 +394,8 @@ function useSidebarThreads(input: { readonly threads: readonly EnvironmentThreadShell[]; readonly delegatedUnderParent: ReadonlySet; readonly routeRowThreadKey: string | null; + // Set in boring mode: the project groups to fold active threads into, in order. + readonly folderGroups: readonly SidebarProjectSnapshot[] | null; }) { const { projectScopeKey, @@ -397,8 +405,11 @@ function useSidebarThreads(input: { threads, delegatedUnderParent, routeRowThreadKey, + folderGroups, } = input; - const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled); + // Folders already separate the work, so boring mode has no Working shelf. + const workingShelfEnabled = + useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; const inboxReturnsVersion = useSyncExternalStore( inboxReturns.subscribe, inboxReturns.getSnapshot, @@ -421,6 +432,9 @@ function useSidebarThreads(input: { false, Schema.Boolean, ); + // Shared with the old per-project sidebar, so folders keep their open state. + const projectExpandedById = useUiStateStore((store) => store.projectExpandedById); + const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded); const [settledTail, setSettledTail] = useState({ scopeKey: projectScopeKey, count: SETTLED_TAIL_INITIAL_COUNT, @@ -475,9 +489,31 @@ function useSidebarThreads(input: { const visibleWorkingThreads = workingShelfExpanded ? workingThreads : routeThreadOnly(workingThreads, routeRowThreadKey); + const projectFolders = + folderGroups === null + ? null + : groupSidebarThreadsByProject(folderGroups, activeThreads).map((folder) => { + const collapsed = !resolveProjectExpanded( + projectExpandedById, + sidebarFolderExpansionKeys(folder.group), + ); + return { + group: folder.group, + collapsed, + // A closed folder still shows the open thread, and hints at the rest. + threads: collapsed + ? routeThreadOnly(folder.threads, routeRowThreadKey) + : folder.threads, + hiddenThreads: collapsed + ? folder.threads.filter((thread) => threadShellKey(thread) !== routeRowThreadKey) + : EMPTY_THREADS, + }; + }); const orderedThreads = [ ...pinnedThreads, - ...activeThreads, + ...(projectFolders === null + ? activeThreads + : projectFolders.flatMap((folder) => folder.threads)), ...visibleWorkingThreads, ...visibleSnoozedThreads, ...renderedSettledThreads, @@ -518,6 +554,11 @@ function useSidebarThreads(input: { toggleSnoozedShelf: () => setSnoozedShelfExpanded((value) => !value), workingShelfExpanded, toggleWorkingShelf: () => setWorkingShelfExpanded((value) => !value), + projectFolders, + toggleProjectFolder: (group: SidebarProjectSnapshot) => { + const keys = sidebarFolderExpansionKeys(group); + setProjectExpanded(keys, !resolveProjectExpanded(projectExpandedById, keys)); + }, renderedSettledThreads, visibleSnoozedThreads, visibleWorkingThreads, @@ -908,6 +949,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); }, }); + const boringSidebarEnabled = useBoringSidebarEnabled(); const newThreadContext = useHandleNewThread(); // Row callbacks capture only the handler; the rest of the context changes with the route. const { handleNewThread } = newThreadContext; @@ -1142,6 +1184,40 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve openProjectSettings(projectGroup); }, ); + const startThreadInProjectFolder = useStableCallback((group: SidebarProjectSnapshot) => { + if (isMobile) setOpenMobile(false); + void handleNewThread(scopeProjectRef(group.environmentId, group.id)); + }); + const handleProjectFolderContextMenu = useStableCallback( + (group: SidebarProjectSnapshot, position: { x: number; y: number }) => { + const api = readLocalApi(); + if (!api) return; + void (async () => { + const clicked = await settlePromise(() => + api.contextMenu.show( + [ + { id: "new-thread", label: "New thread" }, + { id: "copy-path", label: "Copy path" }, + { id: "project-settings", label: "Project settings", icon: "settings" }, + ], + position, + ), + ); + if (clicked._tag === "Failure") return; + switch (clicked.value) { + case "new-thread": + startThreadInProjectFolder(group); + return; + case "copy-path": + copyPathToClipboard(group.workspaceRoot, { path: group.workspaceRoot }); + return; + case "project-settings": + openProjectSettings(group); + return; + } + })(); + }, + ); const { workingShelfEnabled, @@ -1165,6 +1241,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve toggleSnoozedShelf, workingShelfExpanded, toggleWorkingShelf, + projectFolders, + toggleProjectFolder, renderedSettledThreads, visibleSnoozedThreads, visibleWorkingThreads, @@ -1185,6 +1263,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threads, delegatedUnderParent, routeRowThreadKey, + folderGroups: boringSidebarEnabled + ? scopedProjectGroups.length === 0 + ? projectGroups + : scopedProjectGroups + : null, }); // Ranked across environments as the palette ranks them, so one @@ -1745,6 +1828,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve event.activatorEvent instanceof PointerEvent ? event.activatorEvent.clientY : null, }); }; + const hasProjectFolders = projectFolders !== null && projectFolders.length > 0; const sidebarListItemsFresh = ((): readonly SidebarListItem[] => { const rowsOf = ( list: readonly EnvironmentThreadShell[], @@ -1754,13 +1838,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const key = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); return { kind: "thread", key, section }; }); + // Boring mode keeps empty project folders, so each can start a thread. if ( + !hasProjectFolders && pinnedThreads.length + activeThreads.length + workingThreads.length + snoozedThreads.length + settledCount === - 0 + 0 ) { return []; } @@ -1810,6 +1896,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve // Only order, section, or draft changes need layout reads and motion. const listMotionLayoutKey = [ sidebarListItemsKey, + projectFolders + ?.map((folder) => `${folder.group.projectKey}:${folder.threads.length}`) + .join("\n") ?? "", visibleDraftSessionCount, routeDraftIdForRows ?? "", ].join("\0"); @@ -2733,7 +2822,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const showJumpHints = useThreadJumpHintsVisible(shouldShowJumpHintsNow); const handleNewThreadClick = (event?: ReactMouseEvent) => { - if (shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length)) { + if ( + boringSidebarEnabled || + shouldCreateNewThreadInCurrentProject(event?.shiftKey ?? false, projectGroups.length) + ) { if (isMobile) setOpenMobile(false); void startNewThreadFromContext({ activeDraftThread: newThreadContext.activeDraftThread, @@ -2933,7 +3025,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel} - showNewThreadInProjectHint={projectGroups.length > 1} + showNewThreadInProjectHint={!boringSidebarEnabled && projectGroups.length > 1} searchInputRef={threadSearchInputRef} searchQuery={threadSearchQuery} onSearchQueryChange={(value) => { @@ -3049,19 +3141,22 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const renderThreadRow = ( thread: EnvironmentThreadShell, section: SidebarSection, + // The tree row of the project folder this row sits in. + folderRow?: string, ) => { const threadKey = scopedThreadKey( scopeThreadRef(thread.environmentId, thread.id), ); const isCard = section === "active" || section === "pinned" || section === "working"; - const rowVariant = isCard ? "card" : "slim"; + const rowVariant = folderRow ? "folder" : isCard ? "card" : "slim"; return ( , + ); + for (const thread of folder.threads) { + items.push( + renderThreadRow( + thread, + "active", + sidebarFolderRowId(folder.group.projectKey), + ), + ); + } + } + continue; + } switch (item.marker) { case "pinned-header": items.push( @@ -3321,6 +3444,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : null} {!isSearchingThreads && + !hasProjectFolders && visibleDraftSessionCount === 0 && pinnedThreads.length + activeThreads.length + diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 6832d0e2046f1..4100f74b9cf0c 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -441,7 +441,7 @@ export function ChangeRequestStatusIcon({ return ; } -export function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) { +function PrStatusTooltipContent({ status }: { status: PrStatusIndicator }) { return ( {status.tooltipLead} @@ -601,7 +601,7 @@ export function ThreadWorktreeIndicator({ ); } -export function ThreadStatusLabel({ +function ThreadStatusLabel({ status, compact = false, }: { diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index aeef386331b81..8247ab63ee44e 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -665,6 +665,7 @@ function TerminalSessionViewport({ void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size)); } const latestSession = readTerminalSession(); + terminal.setSharedGrid(latestSession.grid); const initialOutput = readTerminalOutputUpdate( latestSession.output, INITIAL_TERMINAL_OUTPUT_CURSOR, @@ -690,6 +691,7 @@ function TerminalSessionViewport({ } const previous = previousSession; previousSession = session; + terminal.setSharedGrid(session.grid); synchronizeTerminalStatus(terminal, session.status, session.version); outputCursorRef.current = synchronizeTerminalSession( terminal, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 020f6e732e22d..43f2cd2e3448c 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -15,7 +15,6 @@ import type { EnvironmentId, ModelSelection, ProjectId, - ProviderApprovalDecision, ThreadContextRecord, ProviderInteractionMode, ResolvedKeybindingsConfig, @@ -175,7 +174,6 @@ import { ComposerCommandMenu, composerSuggestionOptionId, } from "./ComposerCommandMenu"; -import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; import { ComposerAttachButton, ComposerAttachmentFileList, @@ -186,7 +184,6 @@ import { } from "./ComposerAttachmentStrip"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; import { ComposerFooterPrimaryActions, type RuntimeModeOption } from "./ComposerFooterControls"; -import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; @@ -231,7 +228,7 @@ const isThreadTranscriptTooLargeError = Schema.is(OrchestrationThreadTranscriptT const COMPOSER_SCROLL_COLLAPSE_THRESHOLD_PX = 24; const COMPOSER_SCROLL_GESTURE_RESET_MS = 120; import { toastManager } from "../ui/toast"; -import { PlayIcon, ShieldIcon } from "lucide-react"; +import { PlayIcon } from "lucide-react"; import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; @@ -387,6 +384,7 @@ export interface ChatComposerProps { activePendingApproval: PendingApproval | null; pendingApprovals: PendingApproval[]; + onHeldRequestIdsChange: (requestIds: ReadonlySet) => void; pendingUserInputs: PendingUserInput[]; activePendingProgress: { questionIndex: number; @@ -467,10 +465,6 @@ export interface ChatComposerProps { onResume: () => void; onInterrupt: () => void; onImplementPlanInNewThread: () => void; - onRespondToApproval: ( - requestId: RuntimeRequestId, - decision: ProviderApprovalDecision, - ) => Promise; onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; onAdvanceActivePendingUserInput: () => void; onDismissActivePendingUserInput: (requestId: RuntimeRequestId) => void; @@ -535,6 +529,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentUnavailable, activePendingApproval: incomingPendingApproval, pendingApprovals, + onHeldRequestIdsChange, pendingUserInputs: incomingPendingUserInputs, activePendingProgress: incomingPendingProgress, activePendingResolvedAnswers, @@ -586,7 +581,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onResume, onInterrupt, onImplementPlanInNewThread, - onRespondToApproval, onSelectActivePendingUserInputOption, onAdvanceActivePendingUserInput, onDismissActivePendingUserInput, @@ -617,6 +611,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ...pendingApprovals.map((request) => request.requestId), ...incomingPendingUserInputs.map((request) => request.requestId), ]); + // A layout effect so the timeline never paints a held approval as answerable. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes held requests to the timeline without lifting per-keystroke typing state + useLayoutEffect(() => { + onHeldRequestIdsChange(heldRequestIds); + }, [heldRequestIds, onHeldRequestIdsChange]); const activePendingApproval = incomingPendingApproval && !heldRequestIds.has(incomingPendingApproval.requestId) ? incomingPendingApproval @@ -1118,7 +1117,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const isChoiceOnlyPendingQuestion = activePendingProgress?.activeQuestion?.allowCustomAnswer === false; const showComposerTopDrawer = - isComposerApprovalState || pendingUserInputs.length > 0 || (!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null); const showCollapsedMobilePromptRow = isComposerCollapsedMobile; @@ -2140,8 +2138,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) importContextRecords, expandMobileComposer: expandMobileComposerStable, }); - const hasBlockingComposerTopDrawer = - activePendingApproval !== null || pendingUserInputs.length > 0; + const hasBlockingComposerTopDrawer = pendingUserInputs.length > 0; const hasImageAttachmentAttention = standaloneComposerImages.some((image) => { const upload = uploadsByImageId[image.id]; const failedInCurrentEnvironment = @@ -2398,7 +2395,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) getModelDisabledReason={getModelDisabledReason} /> ); - // An open approval or question owns the space above the composer. Only a machine problem, + // An open question owns the space above the composer. Only a machine problem, // which is why an answer could not go through, stays beside it. const shelfItems = hasBlockingComposerTopDrawer ? props.bannerItems.filter( @@ -3220,39 +3217,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {showComposerTopDrawer ? ( - - {activePendingApproval ? ( - - - - - - - - - - - - ) : pendingUserInputs.length > 0 ? ( + + {pendingUserInputs.length > 0 ? ( ; export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({ + presentation = "composer", requestId, isResponding, canRespond, @@ -47,23 +49,42 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro return ( <> {primaryOptions.map((option) => { - const button = ( - + + {option.label} + + ); + const button = + presentation === "inline" ? ( + + {content} + + ) : ( + + ); return option.warning ? ( @@ -76,20 +97,26 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro {moreOptions.length > 0 ? ( } + disabled={disabled || isResponding || !canRespond} + render={ + presentation === "inline" ? ( + + ) : ( + ) : ( diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 49c2b8c411eb6..a8d5e3e68de77 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -1,3 +1,4 @@ +import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow"; import { WorkLogDetails, WorkLogRow } from "./WorkLog"; import { getQuestionAnswerPreview, @@ -198,6 +199,11 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { setExpanded(next); }; const failureItem = workEntry.projectedItem?.item; + const pendingApproval = + failureItem?.type === "approval_request" + ? ctx.pendingApprovals.get(failureItem.requestId) + : undefined; + if (pendingApproval) return ; if (failureItem?.type === "error" && failureItem.status === "failed") { const warning = failureItem.failure.class === "usage_limit"; const resetAt = failureItem.failure.resetAt; @@ -530,7 +536,7 @@ function WorkEntryLogRow(props: WorkEntryRowProps) { environmentId={ctx.activeThreadEnvironmentId} cwd={ctx.markdownCwd} workspaceRoot={workspaceRoot} - onOpenTurnDiff={ctx.onOpenTurnDiff} + onOpenToolDiff={ctx.onOpenToolDiff} onImageExpand={ctx.onImageExpand} source={ctx.turnItemSource} /> diff --git a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx index 1cbb5b818c0d0..a440b62a584d2 100644 --- a/apps/web/src/components/chat/TimelineWorkGroupRows.tsx +++ b/apps/web/src/components/chat/TimelineWorkGroupRows.tsx @@ -1,3 +1,4 @@ +import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow"; import { WorkLogButton, WorkLogList, WorkLogRow } from "./WorkLog"; import type { WorktreeSetupSnapshot } from "@t3tools/contracts"; import { type ToolActivityIcon } from "@t3tools/contracts"; @@ -66,12 +67,17 @@ export const WorkGroupSection = memo(function WorkGroupSection({ isExpandedToolGroup: boolean; displayLabel?: string | undefined; }) { - const { workspaceRoot, routeThreadKey, onToggleWorkEntry } = use(TimelineRowCtx); + const { workspaceRoot, routeThreadKey, onToggleWorkEntry, pendingApprovals } = + use(TimelineRowCtx); const onToggleStandaloneEntry = (collapsed: boolean) => onToggleWorkEntry(disclosureAnchorKey, collapsed); - const nonEmptyEntries = groupedEntries.filter((entry) => - workEntryIsVisibleInGroup(entry, isExpandedToolGroup), - ); + const nonEmptyEntries = groupedEntries.filter((entry) => { + const item = entry.projectedItem?.item; + return ( + (item?.type === "approval_request" && pendingApprovals.has(item.requestId)) || + workEntryIsVisibleInGroup(entry, isExpandedToolGroup) + ); + }); if (nonEmptyEntries.length === 0) return null; if (isExpandedToolGroup && nonEmptyEntries.every((entry) => entry.itemType === "reasoning")) { @@ -271,12 +277,12 @@ const workEntryKey = (entry: TimelineWorkEntry) => entry.id; export function WorkingTimelineRow({ row }: { row: Extract }) { const { isCompacting, isPreparingWorktree, backgroundWorktreeSetup } = use(TimelineRowActivityCtx); - const compacting = row.compacting ?? (isCompacting ? "Compacting…" : undefined); - const shimmer = isPreparingWorktree || compacting !== undefined; + const compacting = row.compacting === true || isCompacting; + const shimmer = isPreparingWorktree || compacting; const label = isPreparingWorktree ? ( "Setting up worktree…" - ) : compacting !== undefined ? ( - + ) : compacting ? ( + ) : row.createdAt ? ( <> Working for @@ -336,11 +342,17 @@ function BackgroundWorktreeSetupChip({ snapshot }: { snapshot: WorktreeSetupSnap ); } -function CompactingLabel({ label }: { label: string }) { +function CompactingLabel({ createdAt }: { createdAt: string | null }) { return ( ); } @@ -349,7 +361,11 @@ export function ThinkingTimelineRow({ row }: { row: Extract; - const activity = ; + // A failed group keeps this disclosure while an approval waits, but nothing is thinking then. + const live = ctx.pendingApprovals.size === 0; + const activity = ( + + ); const { groupId } = row; if (groupId === undefined) return activity; return ( @@ -478,6 +494,11 @@ export function LiveWorkEntryTimelineRow({ const label = liveWorkEntryLabel(row.entry, ctx.workspaceRoot, row.active); const threadLabel = threadReadLabel(label, threadTarget); + const item = row.entry.projectedItem?.item; + const pendingApproval = + item?.type === "approval_request" ? ctx.pendingApprovals.get(item.requestId) : undefined; + if (pendingApproval) return ; + const failed = workEntryDisplayIndicatesToolFailure(row.entry); const thoughtLine = row.thought && !row.expanded ? liveThoughtLine(row.thought.detail ?? "") : ""; const thoughtIsStatus = thoughtLine !== "" && row.entry === row.thought; diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx index 958a56077e51a..ee6072b926b7e 100644 --- a/apps/web/src/components/chat/V2ItemInspector.tsx +++ b/apps/web/src/components/chat/V2ItemInspector.tsx @@ -1,4 +1,5 @@ -import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, RunId } from "@t3tools/contracts"; +import type { ToolCallDiffTarget } from "../../diffPanelStore"; +import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts"; import { toolCallLines, turnItemDetailRevision, @@ -32,7 +33,7 @@ interface V2ItemInspectorProps { readonly environmentId: EnvironmentId; readonly cwd?: string | undefined; readonly workspaceRoot?: string | undefined; - readonly onOpenTurnDiff?: ((runId: RunId, filePath?: string) => void) | undefined; + readonly onOpenToolDiff?: ((target: ToolCallDiffTarget) => void) | undefined; readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; readonly source?: TurnItemSource | undefined; } @@ -289,11 +290,17 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec -{formatDiffCount(item.deletions ?? 0)} ) : null} - {item.runId !== null && props.onOpenTurnDiff ? ( + {props.onOpenToolDiff ? ( diff --git a/apps/web/src/components/chat/composerTypingGuard.test.ts b/apps/web/src/components/chat/composerTypingGuard.test.ts index b9138362f42ed..e98b7c80087dc 100644 --- a/apps/web/src/components/chat/composerTypingGuard.test.ts +++ b/apps/web/src/components/chat/composerTypingGuard.test.ts @@ -19,6 +19,9 @@ describe("composer typing guard", () => { }); state = updateComposerTypingGuard(state, { type }); expect([...state.held]).toEqual([]); + const released = state.held; + state = updateComposerTypingGuard(state, { type }); + expect(state.held).toBe(released); state = updateComposerTypingGuard(state, { type: "focus" }); state = updateComposerTypingGuard(state, { type: "type", now: 2000 }); state = updateComposerTypingGuard(state, { type: "requests", requestIds: [], now: 2100 }); @@ -37,13 +40,16 @@ describe("composer typing guard", () => { requestIds: ["question"], now: 0, }); + const held = state.held; state = updateComposerTypingGuard(state, { type: "focus" }); state = updateComposerTypingGuard(state, { type: "type", now: 1000 }); + expect(state.held).toBe(held); state = updateComposerTypingGuard(state, { type: "requests", requestIds: ["question"], now: 1100, }); expect([...state.held]).toEqual([]); + expect(state.held).toBe(held); }); }); diff --git a/apps/web/src/components/chat/composerTypingGuard.ts b/apps/web/src/components/chat/composerTypingGuard.ts index 01c9cca77d4c3..1f72b98b14011 100644 --- a/apps/web/src/components/chat/composerTypingGuard.ts +++ b/apps/web/src/components/chat/composerTypingGuard.ts @@ -32,7 +32,14 @@ export function updateComposerTypingGuard( } seen.add(id); } - return { ...state, seen, held }; + return { + ...state, + seen, + held: + held.size === state.held.size && [...held].every((id) => state.held.has(id)) + ? state.held + : held, + }; } case "type": return { ...state, lastTypedAt: event.now }; @@ -43,7 +50,7 @@ export function updateComposerTypingGuard( case "idle": return { ...state, - held: new Set(), + held: state.held.size === 0 ? state.held : new Set(), lastTypedAt: -Infinity, focused: event.type === "blur" ? false : state.focused, }; diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.ts new file mode 100644 index 0000000000000..20d4c75997b1d --- /dev/null +++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveTimelineMinimapPreview } from "./timelineMinimapItems"; + +describe("resolveTimelineMinimapPreview", () => { + it("previews a thread autolink as prose, not its URL", () => { + const preview = resolveTimelineMinimapPreview({ + id: "turn-1", + rowIndex: 0, + userText: null, + assistantText: + "Started and [Fix CI](t3-thread://v2/env-1/t2).", + }); + expect(preview?.assistantText).toBe("Started a thread and Fix CI."); + }); +}); diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index faf6af9415405..099c58379ccf6 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -1,3 +1,4 @@ +import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; import type { Nodes } from "mdast"; import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; @@ -82,7 +83,9 @@ function markdownNodeText(node: Nodes): string { if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; if (!("children" in node)) return ""; const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; - return node.children.map(markdownNodeText).join(separator); + const text = node.children.map(markdownNodeText).join(separator); + // A thread autolink's only text is its URL. + return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; } function compactMinimapPreview(text: string | null | undefined) { diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index e38dfecffd044..6334ef53bd050 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,4 +1,9 @@ -import type { WorktreeSetupSnapshot } from "@t3tools/contracts"; +import type { ToolCallDiffTarget } from "../../diffPanelStore"; +import type { + ProviderApprovalDecision, + RuntimeRequestId, + WorktreeSetupSnapshot, +} from "@t3tools/contracts"; import { type EnvironmentId, type MessageId, @@ -16,6 +21,7 @@ import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRunt import { createContext, type MouseEvent, type ReactNode } from "react"; import { type LegendListRef } from "@legendapp/list/react"; import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates"; +import type { PendingApproval } from "../../session-logic"; import { type ChatFileAttachment } from "../../types"; import { ExpandedImagePreview } from "./ExpandedImagePreview"; import { type AssistantCitationTarget } from "./AssistantCitationSource"; @@ -37,6 +43,12 @@ export interface TurnItemSource { } export interface TimelineRowSharedState { + pendingApprovals: ReadonlyMap; + respondingRequestIds: ReadonlyArray; + canOperateThread: boolean; + onRespondToApproval: + | ((requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => Promise) + | undefined; citationRequest: AssistantCitationTarget | null; listRef: React.RefObject; timestampFormat: TimestampFormat; @@ -56,6 +68,7 @@ export interface TimelineRowSharedState { findActive: boolean; onImageExpand: (preview: ExpandedImagePreview) => void; displayThreadKey?: string; + onOpenToolDiff: ((target: ToolCallDiffTarget) => void) | undefined; /** Unset where there is no diff to open, so the timeline shows no "Open diff" button. */ onOpenTurnDiff: ((runId: RunId, filePath?: string) => void) | undefined; /** diff --git a/apps/web/src/components/chat/useComposerMenuItems.ts b/apps/web/src/components/chat/useComposerMenuItems.ts index f1801cbd1516b..e47718f104305 100644 --- a/apps/web/src/components/chat/useComposerMenuItems.ts +++ b/apps/web/src/components/chat/useComposerMenuItems.ts @@ -12,6 +12,7 @@ import type { import { composerPullRequestsFromLinks, filterComposerPullRequestMatches, + withLinkedComposerPullRequestsFirst, } from "@t3tools/shared/composerPullRequestMatches"; import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; @@ -276,24 +277,30 @@ export function useComposerMenuItems({ query: composerTrigger.query, limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, }) - : rankPullRequestMatches( - (pullRequestLookup.data?.entries ?? []).filter((entry) => { - if ( - entry.projectId !== pullRequestProjectId || - entry.repository.trim().toLowerCase() !== pullRequestRepository.trim().toLowerCase() - ) { - return false; - } - const provider = pullRequestLookup.data?.providers.find( - (candidate) => candidate.host === entry.host, - ); - return ( - provider?.searchesOnHost === true || - matchesPullRequestQuery(entry, composerTrigger.query) - ); - }), - composerTrigger.query, - ).slice(0, COMPOSER_PULL_REQUEST_RESULT_LIMIT); + : withLinkedComposerPullRequestsFirst({ + matches: rankPullRequestMatches( + (pullRequestLookup.data?.entries ?? []).filter((entry) => { + if ( + entry.projectId !== pullRequestProjectId || + entry.repository.trim().toLowerCase() !== + pullRequestRepository.trim().toLowerCase() + ) { + return false; + } + const provider = pullRequestLookup.data?.providers.find( + (candidate) => candidate.host === entry.host, + ); + return ( + provider?.searchesOnHost === true || + matchesPullRequestQuery(entry, composerTrigger.query) + ); + }), + composerTrigger.query, + ), + linked: linkedPullRequests, + query: composerTrigger.query, + limit: COMPOSER_PULL_REQUEST_RESULT_LIMIT, + }); return matches.map((pullRequest) => ({ id: `pull-request:${pullRequest.projectId}:${pullRequest.repository}:${pullRequest.number}`, type: "pull-request", diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.ts index f60ae3d0e3b4a..d7abfd526a8cb 100644 --- a/apps/web/src/components/chat/useRightPanelActions.ts +++ b/apps/web/src/components/chat/useRightPanelActions.ts @@ -1,3 +1,4 @@ +import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions"; import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; @@ -213,6 +214,15 @@ export function useRightPanelActions(input: RightPanelActionsInput) { useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); }; + const onOpenToolDiffStable = useStableCallback((target: ToolCallDiffTarget) => { + if (!isServerThread || !activeThreadRef) return; + const diffOpen = + selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff"; + explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef; + useDiffPanelStore.getState().selectToolCall(activeThreadRef, target); + useRightPanelStore.getState().open(activeThreadRef, "diff"); + onDiffPanelOpen?.(); + }); const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff); const shortcuts = { @@ -238,6 +248,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) { closePreviewPanelStable, copyRightPanelFilePathStable, moveRightPanelSurfaceStable, + onOpenToolDiffStable, onOpenTurnDiffStable, onToggleDiffStable, openChangesFromThreadPanelStable, diff --git a/apps/web/src/components/contextChipParts.tsx b/apps/web/src/components/contextChipParts.tsx index b510c1275ee84..a1112d037d908 100644 --- a/apps/web/src/components/contextChipParts.tsx +++ b/apps/web/src/components/contextChipParts.tsx @@ -167,7 +167,9 @@ export function ImageChipButton({ )} - {middleTruncateAttachmentName(name)} + + {middleTruncateAttachmentName(name)} + {size} {suffix ? {suffix} : null} @@ -314,7 +316,9 @@ function FileChipContent(props: { )} - {middleTruncateAttachmentName(props.name)} + + {middleTruncateAttachmentName(props.name)} + {props.size} {props.suffix ? {props.suffix} : null} diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index fb876688dad79..9879edfeedbd8 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -51,6 +51,7 @@ import { boundedZip } from "@t3tools/client-runtime/zip/bounded-zip"; import BinaryViewer from "./BinaryViewer"; import { decodeImagePreview } from "./decodeImagePreview"; import type { BinaryWorkerResult } from "./binaryPreviewProtocol"; +import type { TextPreviewResult } from "./largeTextProtocol"; // Real worker imports and WASM initialization can exceed waitFor's default second // when the full browser project runs concurrently on CI. @@ -462,12 +463,20 @@ describe("large text preview recovery", () => { const original = URL.createObjectURL(new Blob(["original\n".repeat(1000)])); const changed = URL.createObjectURL(new Blob(["changed\n".repeat(1000)])); const workers: Worker[] = []; + const indexed: Promise[] = []; using _worker = stubGlobal( "Worker", class extends Worker { constructor(...args: ConstructorParameters) { super(...args); workers.push(this); + indexed.push( + new Promise((resolve) => + this.addEventListener("message", (event: MessageEvent) => { + if (event.data.type === "meta" && event.data.complete) resolve(); + }), + ), + ); } }, ); @@ -499,6 +508,8 @@ describe("large text preview recovery", () => { await using screen = await render(preview("first")); await vi.waitFor(() => expect(workers).toHaveLength(1)); await vi.waitFor(() => expect(screen.container.textContent).toContain("original")); + // A cold worker can take longer than waitFor allows to load and index on CI. + await indexed[0]; await vi.waitFor(() => expect(screen.container.textContent).toContain("1,000 lines")); const viewport = screen.container.querySelector('[tabindex="0"]')!; await act(() => @@ -2143,8 +2154,10 @@ it("refreshes authorization and retries a failed streamed attachment", async () asset={{ environmentId: EnvironmentId.make("test"), attachmentId: "retry" }} />, ); - await vi.waitFor(() => - expect(screen.container.textContent).toContain("This file contains binary data."), + // A cold large-text worker can take longer than waitFor's default to boot on CI. + await vi.waitFor( + () => expect(screen.container.textContent).toContain("This file contains binary data."), + { timeout: 10_000 }, ); await act(() => screen.container.querySelector('[role="alert"] button')!.click(), @@ -2206,7 +2219,10 @@ it("copies every indexed line rather than the mounted preview rows", async () => , ); await vi.waitFor(() => expect(screen.container.textContent).toContain("line-0")); - await vi.waitFor(async () => expect(await copyContents.current!()).toBe(text)); + // Copy rejects until the worker finishes indexing, which a cold worker can delay past waitFor's default on CI. + await vi.waitFor(async () => expect(await copyContents.current!()).toBe(text), { + timeout: 10_000, + }); const first = copyContents.current!(); await expect(copyContents.current!()).rejects.toThrow("Another copy is in progress."); expect(await first).toBe(text); @@ -2281,12 +2297,16 @@ it("loads a font attachment through the lazy preview", async () => { file={file} />, ); - await vi.waitFor(() => { - const frame = screen.container.querySelector("iframe"); - expect(frame?.title).toBe("Carlito.ttf"); - expect(frame?.srcdoc).toContain("@font-face"); - expect(frame?.srcdoc).toContain("The quick brown fox"); - }); + // Two cold lazy chunks plus decoding a 600 KB font can take longer than waitFor's default on CI. + await vi.waitFor( + () => { + const frame = screen.container.querySelector("iframe"); + expect(frame?.title).toBe("Carlito.ttf"); + expect(frame?.srcdoc).toContain("@font-face"); + expect(frame?.srcdoc).toContain("The quick brown fox"); + }, + { timeout: 10_000 }, + ); expect(screen.container.querySelector('[role="alert"]')).toBeNull(); }); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index d1f0f40a8f8e6..2ee5de1a9483c 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -106,6 +106,7 @@ import { toViewerSide, } from "./PullRequestReviewAnnotation"; import { + getFileViewedRange, isFileDiffCollapsed, isLineInFileDiff, toggleFileDiffFoldForViewed, @@ -175,7 +176,7 @@ interface FileViewedToggleState { readonly enabled: boolean; readonly isViewed: (path: string) => boolean; readonly isStale: (path: string) => boolean; - readonly setFileViewed: (fileKey: string, path: string, viewed: boolean) => void; + readonly setFileViewed: (fileKey: string, viewed: boolean, extendRange: boolean) => void; } // Context updates viewed toggles without invalidating memoized header portals. @@ -205,7 +206,13 @@ function FileViewedToggle({ viewedFiles.setFileViewed(fileKey, path, next === true)} + onCheckedChange={(next, details) => + viewedFiles.setFileViewed( + fileKey, + next === true, + "shiftKey" in details.event && details.event.shiftKey === true, + ) + } /> {stale ? ( @@ -287,6 +294,7 @@ function PullRequestCodeTab({ wordWrap: settings.wordWrap, })); const [toggledFiles, setToggledFiles] = useState>(() => new Set()); + const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); const [foldOverride, setFoldOverride] = useState(null); const effectiveFoldOverride = @@ -326,6 +334,7 @@ function PullRequestCodeTab({ const [stateScopeKey, setStateScopeKey] = useState(scopeKey); if (stateScopeKey !== scopeKey) { setStateScopeKey(scopeKey); + setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); setToggledFiles(new Set()); @@ -689,10 +698,20 @@ function PullRequestCodeTab({ return next; }); - const setFileViewed = (fileKey: string, path: string, viewed: boolean) => { - setViewed(path, viewed); + const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { + const range = getFileViewedRange( + annotatedFiles, + fileKey, + extendRange ? lastViewedFileKey : null, + ); + setLastViewedFileKey(fileKey); + for (const file of range) setViewed(file.path, viewed); setToggledFiles((current) => - toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current), + range.reduce( + (next, file) => + toggleFileDiffFoldForViewed(file.fileKey, viewed, effectiveFoldOverride, next), + current, + ), ); }; const fileViewedToggle = { diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts index 4e11e04e1d784..552fa748f07f6 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts @@ -2,6 +2,7 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import { describe, expect, it } from "vite-plus/test"; import { + getFileViewedRange, isFileDiffCollapsed, isLineInFileDiff, toggleFileDiffFoldForViewed, @@ -54,3 +55,19 @@ describe("toggleFileDiffFoldForViewed", () => { expect(toggleFileDiffFoldForViewed("a.ts", false, "expanded", new Set()).size).toBe(0); }); }); + +describe("getFileViewedRange", () => { + const files = ["c.ts", "a.ts", "b.ts", "d.ts"].map((fileKey) => ({ fileKey })); + + it("includes both endpoints in displayed order in either direction", () => { + expect(getFileViewedRange(files, "b.ts", "c.ts")).toEqual(files.slice(0, 3)); + expect(getFileViewedRange(files, "c.ts", "b.ts")).toEqual(files.slice(0, 3)); + expect(getFileViewedRange(files, "a.ts", "a.ts")).toEqual([files[1]]); + }); + + it("changes only the clicked file without a current anchor", () => { + expect(getFileViewedRange(files, "a.ts", null)).toEqual([files[1]]); + expect(getFileViewedRange(files, "a.ts", "removed.ts")).toEqual([files[1]]); + expect(getFileViewedRange(files, "removed.ts", "a.ts")).toEqual([]); + }); +}); diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts index 37fbfe30e9ab4..f175c0151431a 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts @@ -39,3 +39,15 @@ export function toggleFileDiffFoldForViewed( else next.add(fileKey); return next; } + +export function getFileViewedRange( + files: ReadonlyArray, + fileKey: string, + anchorFileKey: string | null, +): ReadonlyArray { + const index = files.findIndex((file) => file.fileKey === fileKey); + if (index === -1) return []; + const anchorIndex = files.findIndex((file) => file.fileKey === anchorFileKey); + if (anchorIndex === -1) return files.slice(index, index + 1); + return files.slice(Math.min(index, anchorIndex), Math.max(index, anchorIndex) + 1); +} diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index aef61caa7f7e6..1ca96cc35d446 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -1,5 +1,6 @@ import { Link } from "@tanstack/react-router"; +import { Switch } from "../ui/switch"; import { ScopedSwitch } from "./ScopedSwitch"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { searchableSetting } from "./settingsSearch"; @@ -11,6 +12,7 @@ export function LabsSettingsPanel() { return ( + {/* Coder: no guest links row; guest links need T3 Connect, which is not carried. */} @@ -19,6 +21,27 @@ export function LabsSettingsPanel() { ); } +function BoringSidebarRow() { + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + return ( + + updateSettings({ boringSidebarEnabled: Boolean(checked), legacySidebarEnabled: false }) + } + aria-label="Boring sidebar (group by project)" + /> + } + /> + ); +} + function LinkedEnvironmentsRow() { const settings = useScopedSettings(); const updateSettings = useUpdateScopedSettings(); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index a2c27f990f7a5..142db2d37a8a9 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -183,9 +183,6 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.inAppNotificationsEnabled !== DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled ? ["In-app notifications"] : []), - ...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount - ? ["Visible threads"] - : []), ...(settings.sidebarProjectGroupingMode !== DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode ? ["Project Grouping"] : []), @@ -361,7 +358,6 @@ export function useSettingsRestore(onRestored?: () => void) { environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, - sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount, sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled, @@ -596,7 +592,7 @@ export function GeneralSettingsPanel() { /> +

{label}

diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index bcdaaf2f02ed4..1450aea5fcc3e 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -156,7 +156,7 @@ describe("settings search targets", () => { const streaming = getSettingsSearchTargetScope("response-streaming")!; expect(streaming.scope).toBe("project-defaults"); expect(isSettingsSearchScopeAvailable(streaming.scope, "project")).toBe(true); - for (const id of ["legacy-plan-mode", "legacy-context-window-indicator"]) { + for (const id of ["legacy-plan-mode", "legacy-context-window-indicator", "boring-sidebar"]) { expect(getSettingsSearchTargetScope(id)!.scope).toBeNull(); } }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index fe652a02cbb1d..616c4e2dbc175 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -398,6 +398,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: ["hide fold running monitoring threads inbox sidebar shelf"], }, + { + id: "boring-sidebar", + title: "Boring sidebar (group by project)", + to: "/settings/labs", + searchTerms: ["beta folders project tree legacy old classic sidebar"], + }, // Coder: no guest links entry; guest links are not carried. { id: "linked-environments-beta", diff --git a/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx new file mode 100644 index 0000000000000..1ee152533a75b --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarProjectFolderHeader.tsx @@ -0,0 +1,115 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models"; +import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { ChevronDownIcon, SquarePenIcon } from "lucide-react"; +import { memo } from "react"; + +import { cn } from "~/lib/utils"; +import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping"; +import { useUiStateStore } from "../../uiStateStore"; +import { resolveSidebarFolderDot, resolveThreadLastVisitedAt } from "../Sidebar.logic"; +import { ProjectFavicon } from "../ProjectFavicon"; +import { Button } from "../ui/button"; + +const FOLDER_DOT_CLASS_NAME = { + attention: "bg-warning", + failed: "bg-error", + unread: "bg-success", + working: "bg-info", +} as const; + +const FOLDER_DOT_LABEL = { + attention: ", needs you", + failed: ", failed", + unread: ", done", + working: ", working", +} as const; + +/** The folder's sidebar tree row; its thread rows name it as their parent. */ +export function sidebarFolderRowId(projectKey: string) { + return `folder:${projectKey}`; +} + +/** + * A project folder in the boring sidebar. It reads like a shelf header: a trailing + * count and chevron, with the count and a status dot only while it is closed, so a + * closed folder still says when a hidden thread needs you. + */ +export const SidebarProjectFolderHeader = memo(function SidebarProjectFolderHeader(props: { + group: SidebarProjectSnapshot; + collapsed: boolean; + hiddenThreads: readonly EnvironmentThreadShell[]; + onToggle: (group: SidebarProjectSnapshot) => void; + onNewThread: (group: SidebarProjectSnapshot) => void; + onContextMenu: (group: SidebarProjectSnapshot, position: { x: number; y: number }) => void; +}) { + const { group, collapsed, hiddenThreads } = props; + const rowId = sidebarFolderRowId(group.projectKey); + const localLastVisitedAtById = useUiStateStore((state) => state.threadLastVisitedAtById); + const dot = collapsed + ? resolveSidebarFolderDot( + hiddenThreads.map((thread) => ({ + ...thread, + lastVisitedAt: resolveThreadLastVisitedAt( + thread.lastVisitedAt, + localLastVisitedAtById[ + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) + ], + ), + })), + ) + : null; + return ( +
  • + + {/* Sits over the count, which hides on hover, and left of the chevron. */} + + + +
  • + ); +}); diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 6bd916afe3406..bf4d9872c2edb 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -514,9 +514,26 @@ const dropVerbBadge: Record = { ), }; +const TOP_STATUS_ICONS = { + working: CircleDashedIcon, + waiting: CircleDotDashedIcon, + input: MessageCircleQuestionIcon, + // Coder: no guest "request" status; guest sharing is not carried. + approval: ShieldQuestionIcon, + failed: CircleAlertIcon, + done: CircleCheckIcon, + woke: AlarmClockIcon, +} as const; + +function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: string }) { + const Icon = TOP_STATUS_ICONS[props.icon]; + return ; +} + type SidebarThreadRowProps = { thread: SidebarThreadSummary; - variant: "card" | "slim"; + // "folder" is a one-line row inside a boring sidebar project folder. + variant: "card" | "slim" | "folder"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; @@ -991,7 +1008,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn( "min-w-0 flex-1 text-start text-sm transition-opacity motion-reduce:transition-none", shouldRecede ? "font-normal" : "font-medium", - variant === "card" + variant !== "slim" ? cn( "truncate", shouldRecede @@ -1098,7 +1115,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) ) : null; - if (variant === "slim") { + if (variant !== "card") { + const inFolder = variant === "folder"; return (
  • {accessibleTitle} - - {props.project ? : null} - + {inFolder ? null : ( + + {props.project ? ( + + ) : null} + + )} {draftIndicator} {title} {pinIndicator} @@ -1170,7 +1197,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP {props.snoozeWakeLabelText} - ) : isWoke ? ( + ) : (inFolder ? isWokeStatus : isWoke) ? ( Dismiss Woke notification + ) : inFolder && topStatus ? ( + // Folder rows have no status line, so the status takes the time slot. + + + {topStatus.label} + ) : ( - {topStatus.icon === "working" ? ( - - ) : topStatus.icon === "waiting" ? ( - - ) : topStatus.icon === "input" ? ( - - ) : topStatus.icon === "approval" ? ( - - ) : topStatus.icon === "failed" ? ( - - ) : topStatus.icon === "done" ? ( - - ) : null} + {/* Not a live region: a collapsed sidebar is inert, so BackgroundThreadAnnouncer and the open thread's timeline speak status changes instead. */} diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsx index 7d4acf4d392f1..6060a867fed7a 100644 --- a/apps/web/src/components/ui/sidebar.tsx +++ b/apps/web/src/components/ui/sidebar.tsx @@ -97,7 +97,7 @@ function useSidebarVisibility() { return isMobile ? openMobile : open; } -// Same breakpoint as useIsMobile, also read when a shortcut fires. +// The `max-md` breakpoint, also read when a shortcut fires. const SIDEBAR_MOBILE_QUERY = "(max-width: 767px)"; function isMobileViewport(): boolean { @@ -720,8 +720,8 @@ const sidebarMenuButtonVariants = cva( default: "h-8 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-1.5 text-sm", icon: "size-8 justify-center rounded-[var(--control-radius)] p-0", - lg: "h-12 rounded-lg p-2 text-sm group-data-[collapsible=icon]:p-0!", - sm: "h-7 rounded-lg p-2 text-xs", + lg: "h-12 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-sm group-data-[collapsible=icon]:p-0!", + sm: "h-7 rounded-[var(--control-radius)] px-[var(--sidebar-row-content-inset)] py-2 text-xs", }, variant: { default: "font-medium text-sidebar-muted-foreground/80", diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.ts index b7238e8edf906..82065c86fe3aa 100644 --- a/apps/web/src/diffPanelStore.test.ts +++ b/apps/web/src/diffPanelStore.test.ts @@ -1,6 +1,13 @@ +import { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { beforeEach, describe, expect, it } from "vite-plus/test"; -import { useDiffPanelSessionStore, useDiffPanelStore } from "./diffPanelStore"; +import { + resolveToolCallDiffTarget, + useDiffPanelSessionStore, + useDiffPanelStore, +} from "./diffPanelStore"; describe("diffPanelStore", () => { beforeEach(() => { @@ -11,6 +18,73 @@ describe("diffPanelStore", () => { useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); }); + it("keeps a tool call selection independent of checkpoints and allows returning to Git changes", () => { + const ref = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; + const target = { + threadId: ThreadId.make("child"), + itemId: TurnItemId.make("edit"), + revision: "1", + }; + const store = useDiffPanelStore.getState(); + store.selectToolCall(ref, target); + store.reconcileTurnSelection(ref, []); + expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({ + kind: "tool-call", + ...target, + }); + store.selectGitScope(ref, "branch"); + expect(useDiffPanelStore.getState().byThreadKey[scopedThreadKey(ref)]).toEqual({ + kind: "branch", + baseRef: null, + }); + }); + + it("refreshes a live tool-call target when its source item completes", () => { + const target = { + threadId: ThreadId.make("child"), + itemId: TurnItemId.make("edit"), + revision: "live", + }; + const now = DateTime.makeUnsafe("2026-10-28T00:00:00Z"); + const row = { + position: 0, + visibility: "local" as const, + sourceThreadId: target.threadId, + sourceItemId: target.itemId, + item: { + id: target.itemId, + threadId: target.threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "running" as const, + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + type: "file_change" as const, + fileName: "a.ts", + }, + }; + expect(resolveToolCallDiffTarget(target, [row])).toBe(target); + const completed = { + ...row, + item: { ...row.item, status: "completed" as const, completedAt: now }, + }; + expect(resolveToolCallDiffTarget(target, [completed])).toEqual({ + ...target, + revision: DateTime.formatIso(now), + }); + expect( + resolveToolCallDiffTarget(target, [{ ...completed, sourceThreadId: ThreadId.make("other") }]), + ).toBe(target); + expect(resolveToolCallDiffTarget(target, [])).toBe(target); + }); + it("retains fold choices when a panel consumer returns with fresh defaults", () => { const scopeKey = "environment-1:thread-1:branch"; const defaults = new Set(["src/app.ts", "src/index.ts"]); diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.ts index eb6f0e9d455c8..11d96a3909ce7 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -1,11 +1,20 @@ +import type { ThreadStructureVisibleTurnItem } from "@t3tools/client-runtime/state/shell"; +import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; -import type { RunId, ScopedThreadRef } from "@t3tools/contracts"; +import type { RunId, ScopedThreadRef, ThreadId, TurnItemId } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; import { resolveStorage } from "./lib/storage"; +export interface ToolCallDiffTarget { + readonly threadId: ThreadId; + readonly itemId: TurnItemId; + readonly revision: string; +} + export type DiffPanelSelection = + | ({ kind: "tool-call" } & ToolCallDiffTarget) | { kind: "branch"; baseRef: string | null } | { kind: "unstaged" } | { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number }; @@ -17,6 +26,7 @@ interface DiffPanelStoreState { branchBaseRefByThreadKey: Record; selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void; selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void; + selectToolCall: (ref: ScopedThreadRef, target: ToolCallDiffTarget) => void; selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void; reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray) => void; removeThread: (ref: ScopedThreadRef) => void; @@ -69,6 +79,13 @@ export const useDiffPanelStore = create()( }, }; }), + selectToolCall: (ref, target) => + set((state) => ({ + byThreadKey: { + ...state.byThreadKey, + [scopedThreadKey(ref)]: { kind: "tool-call", ...target }, + }, + })), selectTurn: (ref, turnId, filePath) => set((state) => { const threadKey = scopedThreadKey(ref); @@ -160,3 +177,15 @@ export function selectThreadDiffPanelSelection( if (!ref) return DEFAULT_SELECTION; return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_SELECTION; } + +export function resolveToolCallDiffTarget( + target: ToolCallDiffTarget, + items: ReadonlyArray, +): ToolCallDiffTarget { + const row = items.find( + (row) => row.sourceThreadId === target.threadId && row.sourceItemId === target.itemId, + ); + if (row?.item.type !== "file_change") return target; + const revision = turnItemDetailRevision(row.item); + return revision === target.revision ? target : { ...target, revision }; +} diff --git a/apps/web/src/hooks/useMediaQuery.ts b/apps/web/src/hooks/useMediaQuery.ts index ec6ee4fa51160..f3df1b3a4b1de 100644 --- a/apps/web/src/hooks/useMediaQuery.ts +++ b/apps/web/src/hooks/useMediaQuery.ts @@ -77,7 +77,3 @@ export function useMediaQuery(query: BreakpointQuery | MediaQueryInput | (string return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } - -export function useIsMobile(): boolean { - return useMediaQuery("max-md"); -} diff --git a/apps/web/src/hooks/useScratchProject.test.ts b/apps/web/src/hooks/useScratchProject.test.ts new file mode 100644 index 0000000000000..103f66ba5077f --- /dev/null +++ b/apps/web/src/hooks/useScratchProject.test.ts @@ -0,0 +1,49 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { AtomRegistry } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import { createScratchProjectActions } from "./useScratchProject"; + +const local = "local" as EnvironmentId; +const remote = "remote" as EnvironmentId; +const other = "other" as EnvironmentId; + +function scratchEnvironment(environmentId: EnvironmentId, scratchWorkspaceRoot: string | null) { + return { + environmentId, + connection: { phase: "connected" }, + serverConfig: { scratchWorkspaceRoot }, + } as never; +} + +function actions( + primary: EnvironmentId | null, + localRoot: string | null, + remoteRoot: string | null = "/remote/scratch", +) { + const environments = [ + scratchEnvironment(local, localRoot), + scratchEnvironment(remote, remoteRoot), + scratchEnvironment(other, "/other/scratch"), + ]; + return createScratchProjectActions({ + environments: () => environments, + primaryEnvironmentId: () => primary, + registry: AtomRegistry.make(), + handleNewThread: async () => null, + }); +} + +describe("scratchEnvironmentId", () => { + it("prefers the primary environment over the one on screen", () => { + expect(actions(local, "/local/scratch").scratchEnvironmentId(remote)).toBe(local); + expect(actions(local, "/local/scratch").scratchEnvironmentId(null)).toBe(local); + }); + + it("falls back when the primary environment offers no scratch root", () => { + expect(actions(local, null).scratchEnvironmentId(remote)).toBe(remote); + expect(actions(null, null).scratchEnvironmentId(remote)).toBe(remote); + expect(actions(null, null, null).scratchEnvironmentId(remote)).toBe(other); + expect(actions(local, null).scratchEnvironmentId(null)).toBeNull(); + }); +}); diff --git a/apps/web/src/hooks/useScratchProject.ts b/apps/web/src/hooks/useScratchProject.ts index 936da40965981..9c46302351856 100644 --- a/apps/web/src/hooks/useScratchProject.ts +++ b/apps/web/src/hooks/useScratchProject.ts @@ -12,7 +12,11 @@ import type { AtomRegistry } from "effect/reactivity"; import { useContext } from "react"; import { stackedThreadToast, toastManager } from "~/components/ui/toast"; -import { type EnvironmentPresentation, useEnvironments } from "~/state/environments"; +import { + type EnvironmentPresentation, + useEnvironments, + usePrimaryEnvironmentId, +} from "~/state/environments"; import { projectEnvironment } from "~/state/projects"; import { type NewThreadHandler, useNewThreadHandler } from "./useHandleNewThread"; @@ -32,6 +36,7 @@ type ScratchEnvironment = Pick Iterable; + readonly primaryEnvironmentId: () => EnvironmentId | null; readonly registry: AtomRegistry.AtomRegistry; readonly handleNewThread: NewThreadHandler; }) { @@ -43,8 +48,11 @@ export function createScratchProjectActions(input: { return availableScratchWorkspaceRoot(environment?.connection.phase, environment?.serverConfig); }; - const scratchEnvironmentId = (current: EnvironmentId | null): EnvironmentId | null => { - if (current !== null) return scratchWorkspaceRootFor(current) !== null ? current : null; + // The primary (local) environment wins; `fallback` only applies when it offers no scratch root. + const scratchEnvironmentId = (fallback: EnvironmentId | null): EnvironmentId | null => { + const primary = input.primaryEnvironmentId(); + if (primary !== null && scratchWorkspaceRootFor(primary) !== null) return primary; + if (fallback !== null && scratchWorkspaceRootFor(fallback) !== null) return fallback; const offering = [...input.environments()].filter( (entry) => scratchWorkspaceRootFor(entry.environmentId) !== null, ); @@ -85,10 +93,12 @@ export function createScratchProjectActions(input: { export function useScratchProject() { const { environments } = useEnvironments(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); const registry = useContext(RegistryContext); const handleNewThread = useNewThreadHandler(); return createScratchProjectActions({ environments: () => environments, + primaryEnvironmentId: () => primaryEnvironmentId, registry, handleNewThread, }); diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index 457d016628d74..0ca71e34bc491 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -437,7 +437,12 @@ export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMod }); } -// Coder: no legacy sidebar, so there is no `useLegacySidebarEnabled`. +/** Legacy sidebar opt-ins still count, so those users land in the boring sidebar. */ +export function useBoringSidebarEnabled(): boolean { + return useClientSettings( + (settings) => settings.boringSidebarEnabled || settings.legacySidebarEnabled, + ); +} export async function prepareModelPreferencesPatch( settings: ServerSettings, diff --git a/apps/web/src/lib/contextChipAccents.ts b/apps/web/src/lib/contextChipAccents.ts index 0270fa0a61ad7..d5ba1c526ff5b 100644 --- a/apps/web/src/lib/contextChipAccents.ts +++ b/apps/web/src/lib/contextChipAccents.ts @@ -1,5 +1,5 @@ export const CONTEXT_CHIP_ACCENTS = { - image: "oklch(0.62 0.16 16)", + image: "oklch(0.62 0.136 237)", video: "oklch(0.62 0.16 48)", file: "oklch(0.62 0.136 237)", mention: "oklch(0.62 0.11 215)", diff --git a/apps/web/src/lib/toolCallDiff.test.ts b/apps/web/src/lib/toolCallDiff.test.ts new file mode 100644 index 0000000000000..cb33dd45cfb5a --- /dev/null +++ b/apps/web/src/lib/toolCallDiff.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; +import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering"; +import { toolCallDiff } from "./toolCallDiff"; + +describe("toolCallDiff", () => { + it("renders recorded hunks without reading a repository, including renamed paths", () => { + for (const changes of [ + undefined, + [{ operation: "update", oldPath: "old.ts", path: "new.ts" }], + ]) { + const { patch } = toolCallDiff({ + fileName: "old.ts", + diffStr: "@@ -1 +1 @@\n-before\n+after\n", + ...(changes ? { changes } : {}), + }); + const rendered = getRenderablePatch(patch); + expect(rendered?.kind).toBe("files"); + if (rendered?.kind !== "files") throw new Error("Expected a file diff"); + expect(rendered.files).toHaveLength(1); + expect(resolveFileDiffPath(rendered.files[0]!)).toBe(changes ? "new.ts" : "old.ts"); + expect(rendered.files[0]!.additionLines.join("")).toContain("after"); + expect(rendered.files[0]!.deletionLines.join("")).toContain("before"); + } + }); + + it("renders added and deleted file contents as a file diff", () => { + for (const operation of ["add", "delete"]) { + for (const [content, ending] of [ + ["first\nsecond", ""], + ["@@ -0,0 +1 @@\n+content", "\n"], + ["@@ -1 +0,0 @@\n-content", "\n"], + ["first\nsecond", "\n"], + ["--- notes\nsecond", "\n"], + ["diff --git notes\nsecond", "\n"], + ["--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", "\n"], + [ + "diff --git a/embedded.ts b/embedded.ts\n--- a/embedded.ts\n+++ b/embedded.ts\n@@ -1 +1 @@\n-before\n+after", + "\n", + ], + ] as const) { + const recordedContent = `${content}${ending}`; + const rendered = getRenderablePatch( + toolCallDiff({ + fileName: "file with spaces.ts", + diffStr: recordedContent, + changes: [{ operation, path: "file with spaces.ts" }], + }).patch, + ); + expect(rendered?.kind).toBe("files"); + if (rendered?.kind !== "files") throw new Error("Expected a file diff"); + expect(resolveFileDiffPath(rendered.files[0]!)).toBe("file with spaces.ts"); + const file = rendered.files[0]!; + const lines = content.split("\n").length; + expect(file.additionLines).toHaveLength(operation === "add" ? lines : 0); + expect(file.deletionLines).toHaveLength(operation === "delete" ? lines : 0); + expect((operation === "add" ? file.additionLines : file.deletionLines).join("")).toBe( + recordedContent.replace(/\n$/, ""), + ); + } + } + }); + + it("keeps content-only writes out of the patch and preserves empty recorded content", () => { + for (const operation of ["add", "delete"]) { + expect( + toolCallDiff({ + fileName: "empty.ts", + diffStr: "", + changes: [{ operation, path: "empty.ts" }], + }).content, + ).toEqual([ + { + label: operation === "add" ? "Recorded content after" : "Recorded content before", + text: "", + }, + ]); + } + expect(toolCallDiff({ fileName: "a.ts", oldStr: "before", newStr: "" })).toEqual({ + patch: undefined, + content: [ + { label: "Recorded content before", text: "before" }, + { label: "Recorded content after", text: "" }, + ], + truncated: false, + }); + expect(toolCallDiff({ fileName: "a.ts", newStr: "after" }).content).toEqual([ + { label: "Recorded content after", text: "after" }, + ]); + }); + + it("removes transport truncation markers before converting file contents", () => { + const suffix = "\n… output truncated for transport"; + const diff = toolCallDiff({ + fileName: "a.ts", + diffStr: `first\nsecond${suffix}`, + changes: [{ operation: "add", path: "a.ts" }], + }); + expect(diff.truncated).toBe(true); + expect(diff.patch).not.toContain("output truncated"); + expect(getRenderablePatch(diff.patch)?.kind).toBe("files"); + expect(toolCallDiff({ fileName: "a.ts", newStr: `content${suffix}` })).toMatchObject({ + content: [{ label: "Recorded content after", text: "content" }], + truncated: true, + }); + }); + + it("preserves complete patches and unsupported provider output", () => { + for (const operation of ["add", "delete"]) { + const diffStr = [ + "diff --git a/a.ts b/a.ts", + `--- ${operation === "add" ? "/dev/null" : "a/a.ts"}`, + `+++ ${operation === "add" ? "b/a.ts" : "/dev/null"}`, + operation === "add" ? "@@ -0,0 +1 @@" : "@@ -1 +0,0 @@", + operation === "add" ? "+content" : "-content", + "", + ].join("\n"); + expect( + toolCallDiff({ fileName: "a.ts", diffStr, changes: [{ operation, path: "a.ts" }] }).patch, + ).toBe(diffStr); + } + for (const diffStr of [ + undefined, + "", + "provider output", + "--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-a\n+b\n", + ]) { + expect( + toolCallDiff({ fileName: "a.ts", ...(diffStr === undefined ? {} : { diffStr }) }).patch, + ).toBe(diffStr); + } + }); +}); diff --git a/apps/web/src/lib/toolCallDiff.ts b/apps/web/src/lib/toolCallDiff.ts new file mode 100644 index 0000000000000..2224702601d74 --- /dev/null +++ b/apps/web/src/lib/toolCallDiff.ts @@ -0,0 +1,77 @@ +import type { OrchestrationV2TurnItem } from "@t3tools/contracts"; +import { getRenderablePatch, resolveFileDiffPath } from "./diffRendering"; + +type FileChange = Extract; + +function toolCallPatch(item: Pick) { + let patch = item.diffStr; + if (!patch) return patch; + const change = item.changes?.[0]; + const rawFileOperation = change?.operation === "add" || change?.operation === "delete"; + if (patch.startsWith("diff --git ") || patch.startsWith("--- ")) { + if (!rawFileOperation) return patch; + const parsed = getRenderablePatch(patch, "tool-call-format"); + if ( + parsed?.kind === "files" && + parsed.files.every((file) => { + const path = resolveFileDiffPath(file).replaceAll("\\", "/"); + return ( + file.hunks.length > 0 && + item.changes?.some((recorded) => { + const recordedPath = recorded.path.replaceAll("\\", "/"); + return ( + (recorded.operation === "add" + ? file.deletionLines.length === 0 + : recorded.operation === "delete" + ? file.additionLines.length === 0 + : true) && + (recordedPath === path || recordedPath.endsWith(`/${path}`)) + ); + }) + ); + }) + ) + return patch; + } + // Codex can record added/deleted file contents or bare hunks instead of a complete patch. + if (rawFileOperation || !patch.trimStart().startsWith("@@ ")) { + if (!rawFileOperation) return patch; + const lines = patch.split("\n"); + const hasFinalNewline = patch.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = change.operation === "add"; + const range = `1,${lines.length}`; + patch = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const oldPath = change?.oldPath ?? item.fileName; + const newPath = change?.path ?? item.fileName; + const before = change?.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = change?.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n--- ${before}\n+++ ${after}\n${patch.trimStart()}`; +} + +function recordedText(value: string | undefined) { + const suffix = "\n… output truncated for transport"; + const truncated = value !== undefined && value.endsWith(suffix); + return { text: truncated ? value.slice(0, -suffix.length) : value, truncated }; +} + +export function toolCallDiff( + item: Pick, +) { + const diff = recordedText(item.diffStr); + const operation = item.changes?.[0]?.operation; + const emptyContent = diff.text === "" ? "" : undefined; + const before = recordedText(item.oldStr ?? (operation === "delete" ? emptyContent : undefined)); + const after = recordedText(item.newStr ?? (operation === "add" ? emptyContent : undefined)); + return { + patch: toolCallPatch({ ...item, ...(diff.text === undefined ? {} : { diffStr: diff.text }) }), + content: diff.text?.trim() + ? [] + : [ + { label: "Recorded content before", text: before.text }, + { label: "Recorded content after", text: after.text }, + ].filter((entry): entry is { label: string; text: string } => entry.text !== undefined), + truncated: diff.truncated || before.truncated || after.truncated, + }; +} diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.ts index 521a249b00048..69800be4b7574 100644 --- a/apps/web/src/pendingUserInput.test.ts +++ b/apps/web/src/pendingUserInput.test.ts @@ -27,7 +27,7 @@ describe("projectPendingUserInputAnswer", () => { it("sends thread chips as readable links with the actual thread ID", () => { const answer = `Compare ${formatInlineContextReference(threadContextReference(record))}`; expect(projectPendingUserInputAnswer(answer, [record])).toBe( - "Compare [Reference work](t3-thread://v1/reference-thread)", + "Compare [Reference work](t3-thread://v2/env-answer/reference-thread)", ); }); diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.ts index 55817c3378bda..f8f9d6d52b5ba 100644 --- a/apps/web/src/pendingUserInput.ts +++ b/apps/web/src/pendingUserInput.ts @@ -12,7 +12,7 @@ export function projectPendingUserInputAnswer( const recordsById = new Map(threadContexts.map((record) => [record.contextId, record])); return replaceComposerContextReferences(answer, (reference) => { const record = reference.kind === "thread" ? recordsById.get(reference.contextId) : undefined; - return record ? formatThreadLink(record.threadId, reference.label) : reference.source; + return record ? formatThreadLink(record, reference.label) : reference.source; }); } diff --git a/apps/web/src/rpc/requestLatencyState.ts b/apps/web/src/rpc/requestLatencyState.ts index 8d782fd2a5718..23ae32d3bd693 100644 --- a/apps/web/src/rpc/requestLatencyState.ts +++ b/apps/web/src/rpc/requestLatencyState.ts @@ -27,7 +27,8 @@ interface PendingRpcAckRequest { const pendingRpcAckRequests = new Map(); // Background reports nobody waits on. A busy host delays them first, and warning -// about a request the user never made does not say what is wrong. +// about a request the user never made does not say what is wrong. A sign-in wait +// lasts as long as the user takes on the forge. const untrackedRpcAckMethods = new Set([ WS_METHODS.serverGetUsageSummary, WS_METHODS.serverReportClientActivity, diff --git a/apps/web/src/shortcuts/chatRouteCommands.ts b/apps/web/src/shortcuts/chatRouteCommands.ts index 0e7bc0f5aa7e1..8f58d25834375 100644 --- a/apps/web/src/shortcuts/chatRouteCommands.ts +++ b/apps/web/src/shortcuts/chatRouteCommands.ts @@ -33,6 +33,7 @@ export function installChatRouteCommands(router: AnyRouter): () => void { [...appAtomRegistry.get(environmentPresentations.presentationsAtom)].map( ([environmentId, presentation]) => ({ ...presentation, environmentId }), ), + primaryEnvironmentId: () => appAtomRegistry.get(primaryEnvironmentIdAtom), registry: appAtomRegistry, handleNewThread, }); @@ -85,17 +86,17 @@ export function installChatRouteCommands(router: AnyRouter): () => void { "chat.newWithoutProject": (event) => { const { activeThread, activeDraftThread } = readThreadContext(); const environmentId = scratch.scratchEnvironmentId( - activeThread?.environmentId ?? - activeDraftThread?.environmentId ?? - appAtomRegistry.get(primaryEnvironmentIdAtom), + activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null, ); if (environmentId === null) return; claim(event); void scratch.startScratchThread(environmentId); }, "chat.new": (event) => { - // Coder: there is no legacy sidebar. - if (readProjectGroupCount() > 1) { + // The boring sidebar's folders already show the context, so it starts in + // the current project like the legacy sidebar did. + const { boringSidebarEnabled, legacySidebarEnabled } = getClientSettings(); + if (!boringSidebarEnabled && !legacySidebarEnabled && readProjectGroupCount() > 1) { claim(event); openCommandPalette({ open: "new-thread-in" }); return; diff --git a/apps/web/src/state/use-orchestration-command.ts b/apps/web/src/state/use-orchestration-command.ts index 1c801abc3c6b7..98f7efeecbfe6 100644 --- a/apps/web/src/state/use-orchestration-command.ts +++ b/apps/web/src/state/use-orchestration-command.ts @@ -14,8 +14,7 @@ import { AsyncResult } from "effect/reactivity"; import { readEnvironmentScope } from "./session"; import { useAtomCommand } from "./use-atom-command"; -export const ORCHESTRATION_OPERATE_DENIED_MESSAGE = - "This connection cannot change threads or projects."; +const ORCHESTRATION_OPERATE_DENIED_MESSAGE = "This connection cannot change threads or projects."; export function useOrchestrationCommand( command: AtomCommand, diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index 321bc0b48cc17..cb05acdc5e03d 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -518,10 +518,14 @@ export class GhosttyTerminalSurface { readonly canvas: HTMLCanvasElement; readonly input: HTMLTextAreaElement; readonly scrollbar: HTMLDivElement; + /** The drawn grid: the shared PTY grid, clamped per axis to the measured one. */ cols = 1; rows = 1; private readonly mount: HTMLElement; + private measuredCols = 1; + private measuredRows = 1; + private sharedGrid: { readonly cols: number; readonly rows: number } | null = null; private readonly context: CanvasRenderingContext2D; private readonly core: GhosttyTerminalCore; private readonly options: GhosttyTerminalSurfaceOptions; @@ -866,28 +870,59 @@ export class GhosttyTerminalSurface { } const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING); this.mountHeight = height; - // onResize is the only PTY channel; notify on first fit even when the grid matches its 1x1 sentinel. - if (grid.cols !== this.cols || grid.rows !== this.rows || !this.resizeNotified) { - this.cols = grid.cols; - this.rows = grid.rows; - this.core.resize(grid.cols, grid.rows, this.metrics.width, this.metrics.height); + // onResize is the only PTY resize channel, so the first successful fit must + // notify even when the measured grid equals the 1x1 construction sentinel. + if ( + grid.cols !== this.measuredCols || + grid.rows !== this.measuredRows || + !this.resizeNotified + ) { + this.measuredCols = grid.cols; + this.measuredRows = grid.rows; this.notifyResize(); - this.forceFullRender = true; - this.scrollbarDirty = true; - shouldRender = true; } + if (this.applyGrid()) shouldRender = true; // Repaint synchronously before paint so resize never stretches the old backing store. if (shouldRender || this.forceFullRender) this.renderFrame(); return true; } - // Reflow locally during drags; debounce PTY resizes so the shell does not reprint its prompt each step. + /** + * Other clients can share this PTY, so the server owns its grid. Drawing that grid + * keeps wrapping and cursor positions in step with the PTY. Each axis is clamped to + * this surface's own fit: the server's grid lags a local resize, and read-only + * observers never constrain it. + */ + setSharedGrid(grid: { readonly cols: number; readonly rows: number } | null): void { + if (this.disposed) return; + if (this.sharedGrid?.cols === grid?.cols && this.sharedGrid?.rows === grid?.rows) return; + this.sharedGrid = grid; + if (this.hasSize && this.applyGrid()) this.requestRender(); + } + + private applyGrid(): boolean { + const cols = Math.min(this.sharedGrid?.cols ?? this.measuredCols, this.measuredCols); + const rows = Math.min(this.sharedGrid?.rows ?? this.measuredRows, this.measuredRows); + if (cols === this.cols && rows === this.rows) return false; + this.cols = cols; + this.rows = rows; + this.core.resize(cols, rows, this.metrics.width, this.metrics.height); + this.forceFullRender = true; + this.scrollbarDirty = true; + return true; + } + + /** + * The local grid reflows immediately, but the PTY only hears about settled + * dimensions: notifying on every drag step makes the shell reprint its + * prompt mid-drag, which reads as jitter. + */ private notifyResize(): void { this.resizeNotified = true; if (this.resizeNotifyTimer !== null) window.clearTimeout(this.resizeNotifyTimer); this.resizeNotifyTimer = window.setTimeout(() => { this.resizeNotifyTimer = null; - if (!this.disposed) this.options.onResize(this.cols, this.rows); + if (!this.disposed) this.options.onResize(this.measuredCols, this.measuredRows); }, 150); } @@ -898,7 +933,7 @@ export class GhosttyTerminalSurface { if (this.resizeNotifyTimer === null) return; window.clearTimeout(this.resizeNotifyTimer); this.resizeNotifyTimer = null; - this.options.onResize(this.cols, this.rows); + this.options.onResize(this.measuredCols, this.measuredRows); }; focus(): void { @@ -1019,7 +1054,7 @@ export class GhosttyTerminalSurface { if (this.resizeNotifyTimer !== null) { window.clearTimeout(this.resizeNotifyTimer); this.resizeNotifyTimer = null; - this.options.onResize(this.cols, this.rows); + this.options.onResize(this.measuredCols, this.measuredRows); } this.cancelRender(); if (this.compositionSuppressionTimer !== null) { diff --git a/docs/internals/coder-only.md b/docs/internals/coder-only.md index 9d80b70770441..15a2fe5029fb4 100644 --- a/docs/internals/coder-only.md +++ b/docs/internals/coder-only.md @@ -509,6 +509,10 @@ listed here is drift to remove rather than fork behavior to keep. orchestration-v2 guest decider, commands, and projection columns stay, because the contract unions need them (`knip.jsonc` ignores their unused exports); with no service nothing creates a share, so the sidebar `"request"` status and its notification title never fire. + Guests' screenshots (#26323) are not carried either: `ChatMarkdown.tsx` has no + `HostImageUrlContext` or `hostImageUrl.ts` (workspace images load through the workspace asset + route), shared `markdownPipeline.ts` has no `chatMarkdownImageSources`, and + `SidebarThreadRow.tsx`'s `TOP_STATUS_ICONS` has no guest `request` entry. - Linked environments (#16653–#17130) are carried between Coder workspaces through the gateway hub instead of server-to-server HTTP `/mcp` and pairing, which would break `AGENTS.md` boundaries 2, 3, and 6. Upstream's `peer/PeerForwarding.ts` and `peer/RemoteDelegation.ts`, @@ -992,7 +996,7 @@ listed here is drift to remove rather than fork behavior to keep. splitting, but not the render scenarios project, `VITE_RELEASE_CHANNEL`, source maps, or the build manifest. - **App sidebar.** The layout, header, footer, and provider-update pill are upstream's. Coder - deltas: there is no legacy sidebar (or its Settings switch), usage page, desktop app-update + deltas: there is no usage page, desktop app-update pills, desktop window bridge (fullscreen insets and the open-settings menu action), or preview keybinding context (`readUsagePageOpen` is always false); the active workspace supplies keybindings and the pill's providers. Without upstream's "Update everything" (server self-update), `ProviderUpdatesAction.tsx`'s Update all @@ -1133,6 +1137,16 @@ listed here is drift to remove rather than fork behavior to keep. host secrets exist; upstream's host, token, account, and routing settings are not carried. The registry's `parseChangeRequestUrl` (core `shared/definition.ts`) rejects a URL carrying credentials, because links persist their URL verbatim. + - Upstream's forge app sign-in (#26245) is not carried: the server has no + `SourceControlSignIn` service or sign-in and app-access handlers, and source-control-core + drops the driver's `signIn`, the definition's `appSignIn` and `signIns` setting, and + `SourceControlHost.settings.update` (also absent from the test host), because GitLab uses the + workspace's `glab` login. Contracts keep upstream's sign-in schemas, the dormant `appSignIn` + field, and the `sourceControl.signIn*` and `sourceControl.appAccess` RPCs in upstream's + dormant `WsRpcGroup` only; `CoderWsRpcGroup` omits them. In the clients, web + `SourceControlAppAccessNotice.tsx`, `T3AppIcon.tsx`, `settings/SourceControlAppSignInSettings.tsx` + and `sourceControlAppAccessToast.ts` are cut, and client-runtime `state/sourceControl.ts` and + `sourceControlClients.ts` have no app-access or sign-in atoms and no `appSignInTargetForRemote`. - GitLab's definition (`source-control-gitlab/src/shared/definition.ts`) has three deltas: `isChangeRequestReference` accepts a merge request URL on any HTTP(S) host, because self-hosted hostnames need not contain "gitlab"; `authorProfileUrl` links comment authors @@ -1293,7 +1307,10 @@ listed here is drift to remove rather than fork behavior to keep. builds the multi-route driver, routes, and relay credentials the fork cuts. `connection/registry.ts` starts every registered workspace's supervisor desired (upstream starts only enabled ones), since the Coder config owns registration. Its entries carry no cached unsupported-host rejection, so web `state/server.ts`'s shortcut-keybinding - fallback presents each workspace's connection state as is. + fallback presents each workspace's connection state as is. It has no `assertKnownAddress` or + `register(..., { knownAddressOnly })`, since pairing links (#26178) are not carried, and + `connection/resolver.ts` keeps no remote HTTP prepare path, so #25754's authorized descriptor + fetch there is not carried. `state/shell.ts` treats every workspace as remote (no primary local target). - `lib/runtime.ts` has no primary-environment HTTP client, relay, DPoP, or tracer, and `branding.ts` fixes the "T3 Coder" name without a desktop bridge or hosted channel. diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index e41f42c8248a3..befaca4c077c8 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -390,12 +390,15 @@ and `creationSource: "mcp"`; provider output uses `creationSource: "provider"`. Actor and ingress are separate so agent-authored user-role messages remain distinguishable from human-authored messages. -Agents mention another thread as `[title](t3-thread://v1/)`. Thread -results carry this ready-made as `link`, so agents never format the id. The -link carries only the id. Clients first resolve it in the message's environment, -then use a unique match in another enabled environment. Ambiguous matches stay -unresolved. Web and desktop show the resolved thread’s current title. Mobile -relabels local matches; cross-environment links can retain the written label. +Agents mention another thread by the `link` its result carries, +`/>`, so they never format an id or +write a title, which goes stale when the user renames the thread. The +environment that owns the thread builds the link, so forwarded results and tasks +delegated to a linked environment name that environment. Clients open only that +environment's thread and show its current title; a link to a thread they do not +know renders as a label that opens nothing. Older `t3-thread://v1/` +links name no environment: clients resolve them in the message's environment, +then by a unique match in another enabled environment. List and read results report `snoozed` and `snoozedUntil`, and `t3_thread_list` filters on `snoozed`. The server's `isSnoozed` follows the diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 483fd3c4c8daf..f6c800e1e0477 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -120,6 +120,15 @@ its own choice. While this is on, the active list is ordered by when each thread last came back to you, so you cannot drag or move threads within it. Your saved order returns when you turn it off. +### Group threads by project (beta) + +Turn on **Settings → Labs → Boring sidebar (group by project)** on web and desktop to put active +threads in a folder for each project. Click a folder to open or close it. A closed folder shows how +many threads it holds, and a dot when one of them needs you. Use the pen button on a folder, or +right-click it, to start a thread in that project. Pinned threads stay above the folders, and +Snoozed and Settled stay below them. In this mode you cannot drag threads, and the Working section +is off. Each device keeps its own choice. + ## Settle finished work Choose **Settle thread** from its menu to move finished work out of the active list diff --git a/packages/client-runtime/src/markdownImages.ts b/packages/client-runtime/src/markdownImages.ts index 924220ec27ce4..94cba5c9f842b 100644 --- a/packages/client-runtime/src/markdownImages.ts +++ b/packages/client-runtime/src/markdownImages.ts @@ -1,16 +1,14 @@ import { isNetworkPath, isWindowsAbsolutePath, - stripSlashPrefixedWindowsDrive, workspaceRelativeFilePath, } from "@t3tools/shared/path"; import { + markdownDestinationHostPath, normalizeMarkdownLinkDestination, - safeDecodeURIComponent, splitMarkdownLinkSearchAndHash, } from "@t3tools/shared/markdownLinks"; -import { parseFileUrlHref } from "@t3tools/shared/fileLinks"; const DIRECT_IMAGE_SOURCE_PATTERN = /^(?:https?:|data:|blob:|\/\/)/i; const URI_SCHEME_PATTERN = /^[A-Za-z][A-Za-z0-9+.-]*:/; @@ -59,19 +57,9 @@ export function classifyMarkdownImageSource( return { _tag: "Direct", uri: source }; } - if (/^file:/i.test(source)) { - const target = parseFileUrlHref(source); - return target === null - ? { _tag: "Blocked" } - : hostFileSource( - stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)), - workspaceRoot, - ); - } - - const path = stripSlashPrefixedWindowsDrive( - safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path), - ); + const path = markdownDestinationHostPath(source); + if (path === null) return { _tag: "Blocked" }; + if (/^file:/i.test(source)) return hostFileSource(path, workspaceRoot); if (path.length === 0) return { _tag: "Blocked" }; if (path.startsWith("/") || isWindowsAbsolutePath(path)) { return hostFileSource(path, workspaceRoot); diff --git a/packages/client-runtime/src/state/projectGrouping.ts b/packages/client-runtime/src/state/projectGrouping.ts index 6866c02b08cfd..a23fd4a79e0bc 100644 --- a/packages/client-runtime/src/state/projectGrouping.ts +++ b/packages/client-runtime/src/state/projectGrouping.ts @@ -78,7 +78,7 @@ export function derivePhysicalProjectKey( return derivePhysicalProjectKeyFromPath(project.environmentId, project.workspaceRoot); } -export function deriveProjectGroupingOverrideKey( +function deriveProjectGroupingOverrideKey( project: Pick, ): string { return derivePhysicalProjectKey(project); diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts index 84a0a0697e468..fe7b59017722a 100644 --- a/packages/client-runtime/src/state/terminalSession.test.ts +++ b/packages/client-runtime/src/state/terminalSession.test.ts @@ -88,6 +88,30 @@ describe("terminal session reducers", () => { }); }); + it("follows the shared PTY grid from snapshots and activity without disturbing output", () => { + const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), { + type: "snapshot", + snapshot: { ...BASE_SNAPSHOT, cols: 130, rows: 15 }, + }); + const activity = { + type: "activity", + threadId: TARGET.threadId, + terminalId: TARGET.terminalId, + hasRunningSubprocess: false, + label: "Terminal 1", + } as const; + const narrowed = applyTerminalAttachStreamEvent(attached, { ...activity, cols: 54, rows: 15 }); + // Activity from a server without geometry, or a repeat, must not reset the renderer. + const unchanged = applyTerminalAttachStreamEvent( + applyTerminalAttachStreamEvent(narrowed, activity), + { ...activity, cols: 54, rows: 15 }, + ); + + expect(attached.grid).toEqual({ cols: 130, rows: 15 }); + expect(narrowed).toEqual({ ...attached, grid: { cols: 54, rows: 15 } }); + expect(unchanged).toBe(narrowed); + }); + it("preserves a BOM code point at a new output chunk boundary", () => { const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, { type: "snapshot", diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts index fcbd42cc5c6a5..1fe3b92f2efb7 100644 --- a/packages/client-runtime/src/state/terminalSession.ts +++ b/packages/client-runtime/src/state/terminalSession.ts @@ -24,9 +24,17 @@ export { } from "./terminalOutput.ts"; export { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts"; +/** The PTY grid every renderer of a shared terminal draws. */ +export interface TerminalGrid { + readonly cols: number; + readonly rows: number; +} + export interface TerminalSessionState { readonly summary: TerminalSummary | null; readonly output: TerminalOutputState; + /** Null when the server predates shared terminal geometry. */ + readonly grid: TerminalGrid | null; readonly status: TerminalSessionSnapshot["status"] | "closed"; readonly error: string | null; readonly hasRunningSubprocess: boolean; @@ -37,6 +45,7 @@ export interface TerminalSessionState { export interface TerminalBufferState { readonly output: TerminalOutputState; + readonly grid: TerminalGrid | null; readonly status: TerminalSessionSnapshot["status"] | "closed"; readonly error: string | null; readonly updatedAt: string | null; @@ -69,6 +78,7 @@ export function selectRunningSubprocessTerminalIds( export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({ output: EMPTY_TERMINAL_OUTPUT_STATE, + grid: null, status: "closed", error: null, updatedAt: null, @@ -79,6 +89,7 @@ export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({ export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze({ summary: null, output: EMPTY_TERMINAL_OUTPUT_STATE, + grid: null, status: "closed", error: null, hasRunningSubprocess: false, @@ -107,6 +118,7 @@ function terminalBufferStateFromSnapshot( ): TerminalBufferState { return { output: resetOutput(current.output, snapshot.history, maxBufferBytes), + grid: nextGrid(current.grid, snapshot), status: snapshot.status, error: null, updatedAt: snapshot.updatedAt, @@ -115,6 +127,16 @@ function terminalBufferStateFromSnapshot( }; } +function nextGrid( + current: TerminalGrid | null, + source: { readonly cols?: number | undefined; readonly rows?: number | undefined }, +): TerminalGrid | null { + if (source.cols === undefined || source.rows === undefined) return current; + return current?.cols === source.cols && current.rows === source.rows + ? current + : { cols: source.cols, rows: source.rows }; +} + function latestTimestamp(left: string | null, right: string | null): string | null { if (left === null) return right; if (right === null) return left; @@ -128,6 +150,7 @@ export function combineTerminalSessionState( return { summary, output: buffer.output, + grid: buffer.grid, status: buffer.version > 0 ? buffer.status : (summary?.status ?? buffer.status), error: buffer.error, hasRunningSubprocess: summary?.hasRunningSubprocess ?? false, @@ -218,8 +241,10 @@ function applyUpstreamTerminalAttachStreamEvent( error: event.message, version: current.version + 1, }; - case "activity": - return current; + case "activity": { + const grid = nextGrid(current.grid, event); + return grid === current.grid ? current : { ...current, grid }; + } } } diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts index d61213c243ea8..2b1b1162d6bc9 100644 --- a/packages/client-runtime/src/state/threadCommands.test.ts +++ b/packages/client-runtime/src/state/threadCommands.test.ts @@ -3,6 +3,7 @@ import { CommandId, RuntimeRequestId, EnvironmentId, + MessageId, RunId, ORCHESTRATION_V2_WS_METHODS, ProjectId, @@ -86,6 +87,7 @@ const SNAPSHOT: OrchestrationV2ShellSnapshot = { }; const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (options?: { + readonly loadEarlier?: () => Effect.Effect; readonly reconcilePendingWork?: (threadId: ThreadId) => Effect.Effect; }) { const requests = yield* Queue.unbounded<{ @@ -126,7 +128,7 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio ThreadHistoryController.ThreadHistoryController.of({ register: () => Effect.die("unused"), unregister: () => Effect.void, - loadEarlier: () => Effect.die("unused"), + loadEarlier: () => options?.loadEarlier?.() ?? Effect.die("unused"), reconcilePendingWork: (_environmentId, threadId) => options?.reconcilePendingWork?.(threadId) ?? Queue.offer(reconciled, threadId), }), @@ -142,6 +144,59 @@ const makeHarness = Effect.fn("TestThreadCommands.makeHarness")(function* (optio return { registry, commands, snapshotAtom, visibleAtom, requests, reconciled }; }); +describe("history loading", () => { + it.effect("sends a message on the thread while earlier history is loading", () => + Effect.gen(function* () { + const historyStarted = yield* Deferred.make(); + const historyReply = + yield* Deferred.make(); + const h = yield* makeHarness({ + loadEarlier: () => + Deferred.succeed(historyStarted, undefined).pipe( + Effect.andThen(Deferred.await(historyReply)), + ), + }); + yield* Effect.addFinalizer(() => Deferred.succeed(historyReply, { _tag: "loaded" })); + const history = h.commands.loadEarlierHistory.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: THREAD_ID }, + }); + yield* Deferred.await(historyStarted); + const send = h.commands.startTurn.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { + threadId: THREAD_ID, + message: { + messageId: MessageId.make("message"), + role: "user", + text: "Send while history loads", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + dispatchMode: "start", + }, + }); + // Dispatched after Send on another thread, so it arrives first only if Send is queued. + const controlThreadId = ThreadId.make("control-thread"); + const control = h.commands.interruptTurn.run(h.registry, { + environmentId: ENVIRONMENT_ID, + input: { threadId: controlThreadId, runId: RunId.make("control-run") }, + }); + const first = yield* Queue.take(h.requests); + yield* Deferred.succeed(first.reply, { sequence: 1 }); + yield* Deferred.succeed(historyReply, { _tag: "loaded" }); + const second = yield* Queue.take(h.requests); + yield* Deferred.succeed(second.reply, { sequence: 2 }); + const results = yield* Effect.promise(() => Promise.all([history, send, control])); + + expect(first.command).toMatchObject({ type: "message.dispatch", threadId: THREAD_ID }); + expect(second.command).toMatchObject({ type: "run.interrupt", threadId: controlThreadId }); + expect(results.map((value) => value._tag)).toEqual(["Success", "Success", "Success"]); + }), + ); +}); + describe("interrupt turn", () => { // A stale cached item has nothing left to interrupt, so the server can reject Stop. it.effect("reconciles pending work when the server rejects the interrupt", () => diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 0484146fad4ab..d3b44574b7b0a 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -343,7 +343,8 @@ export function createThreadEnvironmentAtoms( scheduler, concurrency: { mode: "serial", - key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId]), + key: ({ environmentId, input }) => + `history:${JSON.stringify([environmentId, input.threadId])}`, }, }), }; diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.ts index 99e9841faaadc..d5d7c5ac08956 100644 --- a/packages/client-runtime/src/userMessage.ts +++ b/packages/client-runtime/src/userMessage.ts @@ -9,13 +9,13 @@ import { /** The working row while T3 Code's own compaction runs. */ export const IDLE_COMPACTING_LABELS = { beforeCacheExpires: "Compacting before the cache expires…", - onReturn: "Compacting after being idle…", + onReturn: "Compacting…", } satisfies Record; /** Leads the finished compaction's token counts, in place of "Context compacted". */ export const IDLE_COMPACTION_TITLES = { beforeCacheExpires: "Context automatically compacted before cache expiry", - onReturn: "Context compacted after being idle", + onReturn: "Context compacted before sending", } satisfies Record; const LEGACY_AUTOMATION_PREFIX = /^\[Triggered by schedule task: [^\r\n]+\]\r?\n\r?\n/; diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index af9407760046e..3cd80feea6b73 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -35,6 +35,10 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope, [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope, + // Signing in replaces the server's GitHub credential, as saving a token in Settings does. + [WS_METHODS.sourceControlSignInStart]: AuthSettingsWriteScope, + [WS_METHODS.sourceControlSignInWait]: AuthSettingsWriteScope, + [WS_METHODS.sourceControlSignInCancel]: AuthSettingsWriteScope, [WS_METHODS.projectCloneStart]: AuthSourceControlWriteScope, [WS_METHODS.projectCloneCancel]: AuthSourceControlWriteScope, [WS_METHODS.projectCloneRetry]: AuthSourceControlWriteScope, diff --git a/packages/contracts/src/guestShare.ts b/packages/contracts/src/guestShare.ts index fa4b3a256f013..fd991fe1e4c3b 100644 --- a/packages/contracts/src/guestShare.ts +++ b/packages/contracts/src/guestShare.ts @@ -136,3 +136,8 @@ export const GUEST_COMMAND_OUTPUT_ROUTE = `${GUEST_ROUTE_PREFIX}/command-output` * Images load inline; other files download. */ export const GUEST_ATTACHMENT_ROUTE = `${GUEST_ROUTE_PREFIX}/attachment`; +/** + * An image file on the host that an agent message in the shared thread embeds: + * `?share=&path=`. + */ +export const GUEST_MEDIA_ROUTE = `${GUEST_ROUTE_PREFIX}/media`; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 5b4f8a20c1407..cde3c373d3a42 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -327,6 +327,12 @@ import { SourceControlRepositoryError, SourceControlRepositoryInfo, SourceControlRepositoryLookupInput, + SourceControlAppAccess, + SourceControlAppAccessInput, + SourceControlSignInError, + SourceControlSignInInput, + SourceControlSignInPrompt, + SourceControlSignInResult, } from "./sourceControl.ts"; import { VcsError } from "./vcs.ts"; // Coder @@ -544,6 +550,10 @@ export const WS_METHODS = { sourceControlLookupRepository: "sourceControl.lookupRepository", sourceControlCloneRepository: "sourceControl.cloneRepository", sourceControlPublishRepository: "sourceControl.publishRepository", + sourceControlSignInStart: "sourceControl.signInStart", + sourceControlSignInWait: "sourceControl.signInWait", + sourceControlSignInCancel: "sourceControl.signInCancel", + sourceControlAppAccess: "sourceControl.appAccess", projectCloneStart: "projectClone.start", projectCloneCancel: "projectClone.cancel", projectCloneRetry: "projectClone.retry", @@ -1035,6 +1045,33 @@ const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlClone error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]), }); +// Starts a device-flow sign-in the server finishes on its own, so a client can leave meanwhile. +const WsSourceControlSignInStartRpc = Rpc.make(WS_METHODS.sourceControlSignInStart, { + payload: SourceControlSignInInput, + success: SourceControlSignInPrompt, + error: Schema.Union([SourceControlSignInError, EnvironmentAuthorizationError]), +}); + +// Resolves when the sign-in `signInStart` began ends, however long the user takes. +const WsSourceControlSignInWaitRpc = Rpc.make(WS_METHODS.sourceControlSignInWait, { + payload: SourceControlSignInInput, + success: SourceControlSignInResult, + error: Schema.Union([SourceControlSignInError, EnvironmentAuthorizationError]), +}); + +// Ends the sign-in `signInStart` began, so approving the code afterwards signs nothing in. +const WsSourceControlSignInCancelRpc = Rpc.make(WS_METHODS.sourceControlSignInCancel, { + payload: SourceControlSignInInput, + success: Schema.Void, + error: Schema.Union([SourceControlSignInError, EnvironmentAuthorizationError]), +}); + +const WsSourceControlAppAccessRpc = Rpc.make(WS_METHODS.sourceControlAppAccess, { + payload: SourceControlAppAccessInput, + success: SourceControlAppAccess, + error: EnvironmentAuthorizationError, +}); + // Returns when the project exists and cloning starts; progress uses the subscription. const WsProjectCloneStartRpc = Rpc.make(WS_METHODS.projectCloneStart, { payload: ProjectCloneStartInput, @@ -1787,6 +1824,10 @@ export const WsRpcGroup = RpcGroup.make( WsSourceControlLookupRepositoryRpc, WsSourceControlCloneRepositoryRpc, WsSourceControlPublishRepositoryRpc, + WsSourceControlSignInStartRpc, + WsSourceControlSignInWaitRpc, + WsSourceControlSignInCancelRpc, + WsSourceControlAppAccessRpc, WsProjectCloneStartRpc, WsProjectCloneCancelRpc, WsProjectCloneRetryRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 6df344a366e59..f022a2fcee221 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -73,16 +73,6 @@ export const SidebarProjectGroupingMode = Schema.Literals([ ]); export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type; const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository"; -export const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1; -export const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15; -export const SidebarThreadPreviewCount = Schema.Int.check( - Schema.isBetween({ - minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT, - maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT, - }), -); -export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type; -const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6; export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1; export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90; export const SidebarAutoSettleAfterDays = Schema.Number.check( @@ -494,6 +484,9 @@ export const ClientSettingsSchema = Schema.Struct({ ), proactivePanelsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), showSkillsInSlashMenu: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + boringSidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + // Opt-in for the removed legacy sidebar. Still read so those users land in + // the boring sidebar; the boring sidebar toggle clears it. legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( @@ -509,9 +502,6 @@ export const ClientSettingsSchema = Schema.Struct({ sidebarThreadSortOrder: SidebarThreadSortOrder.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)), ), - sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe( - Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)), - ), timestampFormat: TimestampFormat.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)), ), @@ -1728,6 +1718,7 @@ export const ClientSettingsPatch = Schema.Struct({ followUpBehavior: Schema.optionalKey(Schema.Literals(["queue", "steer"])), proactivePanelsEnabled: Schema.optionalKey(Schema.Boolean), showSkillsInSlashMenu: Schema.optionalKey(Schema.Boolean), + boringSidebarEnabled: Schema.optionalKey(Schema.Boolean), legacySidebarEnabled: Schema.optionalKey(Schema.Boolean), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), @@ -1736,7 +1727,6 @@ export const ClientSettingsPatch = Schema.Struct({ ), sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder), sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder), - sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount), timestampFormat: Schema.optionalKey(TimestampFormat), snapShotEnabled: Schema.optionalKey(Schema.Boolean), snapShotIncludeAccessibility: Schema.optionalKey(Schema.Boolean), diff --git a/packages/contracts/src/sourceControl.ts b/packages/contracts/src/sourceControl.ts index e0713b2425a29..6ffb4b97066f2 100644 --- a/packages/contracts/src/sourceControl.ts +++ b/packages/contracts/src/sourceControl.ts @@ -155,6 +155,8 @@ export const SourceControlProviderDiscoveryItem = Schema.Struct({ kind: SourceControlProviderKind, ...SourceControlDiscoverySharedFields, auth: SourceControlProviderAuth, + /** The server is configured to sign in through the host's app; clients offer it only then. */ + appSignIn: Schema.optionalKey(Schema.Boolean), }); export type SourceControlProviderDiscoveryItem = typeof SourceControlProviderDiscoveryItem.Type; @@ -182,6 +184,63 @@ export class SourceControlProviderError extends Schema.TaggedError()( + "SourceControlSignInError", + { + provider: SourceControlProviderKind, + host: Schema.String, + reason: SourceControlSignInFailure, + detail: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) { + override get message(): string { + return this.detail; + } +} + export class SourceControlRepositoryError extends Schema.TaggedError()( "SourceControlRepositoryError", { diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index 022215010da5e..6fed995ee96e7 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -106,6 +106,9 @@ export const TerminalSessionSnapshot = Schema.Struct({ sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), // Coder: identifies the shell session whose sequences a replay-window resume refers to. attachEpoch: Schema.optional(Schema.String), + // The PTY grid every renderer of this terminal should draw; absent from older servers. + cols: Schema.optional(TerminalColsSchema), + rows: Schema.optional(TerminalRowsSchema), }); export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type; @@ -199,6 +202,9 @@ const TerminalActivityEvent = Schema.Struct({ type: Schema.Literal("activity"), hasRunningSubprocess: Schema.Boolean, label: Schema.String.check(Schema.isMaxLength(128)), + // Shared PTY grid changes ride on activity because older clients reject unknown event types. + cols: Schema.optional(TerminalColsSchema), + rows: Schema.optional(TerminalRowsSchema), }); export const TerminalEvent = Schema.Union([ diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 57346634a9166..fed56ed584d99 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -815,7 +815,24 @@ export function acpToolCallDiffPatch(content: unknown): string | undefined { }); for (const diff of diffs) { const patch = unknownRecord(diff.patch); - if (typeof patch?.text === "string") return patch.text; + if (typeof patch?.text === "string") { + const change = + Array.isArray(diff.changes) && diff.changes.length === 1 + ? unknownRecord(diff.changes[0]) + : undefined; + if ( + patch.format === "git_patch" && + patch.text.trimStart().startsWith("@@ ") && + typeof change?.path === "string" + ) { + const oldPath = typeof change.oldPath === "string" ? change.oldPath : change.path; + const before = change.operation === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = + change.operation === "delete" ? "/dev/null" : JSON.stringify(`b/${change.path}`); + return `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${change.path}`)}\n--- ${before}\n+++ ${after}\n${patch.text.trimStart()}`; + } + return patch.text; + } } const v1Patches = diffs.flatMap((diff) => { if (typeof diff.path !== "string" || typeof diff.newText !== "string") return []; diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index d32f74c40cdda..0cbb6c39fbfb2 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -17,7 +17,7 @@ Ordinary coding tasks need no T3 tools. - Given a thread id, \`t3_thread_read\` it before you answer about it. - Another machine: \`t3_environment_links\` lists linked ones. Pass its \`environmentId\` to a T3 tool to act there. Ids are then that machine's, so pass \`threadId\`. - A machine the user names that is not linked: tell them to link its workspace in T3 Coder's workspace Links settings. -- In your reply, a thread's first mention is its \`link\` verbatim. No \`link\`: \`[title](t3-thread://v1/)\`. Never a plain title or bare id. A thread on a linked machine: its title and machine, not its link. +- In your reply, mention a thread by its \`link\`, verbatim. Never a plain title or bare id. - A secret: call \`request_secret\` yourself. Pass its \`secretRef\` to a T3 tool, or use \`delivery: "file"\` for a shell command. Never ask in chat or invent one. When asked only to schedule, \`schedule_task\` without running its prompt. - T3 tools may load late. Try the name once before you call it absent.`, `### Visuals and preview diff --git a/packages/shared/src/composerPullRequestMatches.test.ts b/packages/shared/src/composerPullRequestMatches.test.ts index e87dc5d622f32..19e960721892c 100644 --- a/packages/shared/src/composerPullRequestMatches.test.ts +++ b/packages/shared/src/composerPullRequestMatches.test.ts @@ -5,6 +5,7 @@ import type { ThreadPullRequestLink } from "@t3tools/contracts"; import { composerPullRequestsFromLinks, filterComposerPullRequestMatches, + withLinkedComposerPullRequestsFirst, } from "./composerPullRequestMatches.ts"; const entry = (number: number, updatedAt: string) => ({ @@ -78,4 +79,30 @@ describe("linked pull requests", () => { }); expect(result).toEqual([entry(4, "2026-01-03")]); }); + + it("puts linked pull requests ahead of a text search, before and after it returns", () => { + const linked = composerPullRequestsFromLinks( + [ + link("owner/repo", 7, { + snapshot: { ...link("owner/repo", 7).snapshot!, title: "Fix login" }, + }), + link("owner/repo", 8), + ], + "p1", + ); + const searching = withLinkedComposerPullRequestsFirst({ + matches: [], + linked, + query: "fix", + limit: 10, + }); + expect(searching.map((match) => match.number)).toEqual([7]); + const searched = withLinkedComposerPullRequestsFirst({ + matches: [entry(9, "2026-01-05"), entry(8, "2026-01-03")], + linked, + query: "fix", + limit: 10, + }); + expect(searched).toEqual([linked[0], entry(8, "2026-01-03"), entry(9, "2026-01-05")]); + }); }); diff --git a/packages/shared/src/composerPullRequestMatches.ts b/packages/shared/src/composerPullRequestMatches.ts index 6a586a8a66ba3..4be2248a48a7e 100644 --- a/packages/shared/src/composerPullRequestMatches.ts +++ b/packages/shared/src/composerPullRequestMatches.ts @@ -73,3 +73,34 @@ export function filterComposerPullRequestMatches< ) .slice(0, input.limit); } + +/** Puts the thread's linked pull requests that match a text query ahead of the searched ones. */ +export function withLinkedComposerPullRequestsFirst< + Entry extends ComposerPullRequestMatch, + Linked extends ComposerPullRequestMatch & { + readonly title: string; + readonly headBranch: string; + }, +>(input: { + readonly matches: ReadonlyArray; + readonly linked: ReadonlyArray; + readonly query: string; + readonly limit: number; +}): ReadonlyArray { + const keyOf = (entry: ComposerPullRequestMatch) => + `${entry.repository.trim().toLowerCase()}#${entry.number}`; + const matchesByKey = new Map(input.matches.map((entry) => [keyOf(entry), entry])); + const words = input.query.toLowerCase().split(/\s+/u).filter(Boolean); + const linked = input.linked.flatMap((entry): Array => { + const match = matchesByKey.get(keyOf(entry)); + if (match !== undefined) return [match]; + const text = + `#${entry.number} ${entry.title} ${entry.repository} ${entry.headBranch}`.toLowerCase(); + return words.every((word) => text.includes(word)) ? [entry] : []; + }); + const linkedKeys = new Set(linked.map(keyOf)); + return [...linked, ...input.matches.filter((entry) => !linkedKeys.has(keyOf(entry)))].slice( + 0, + input.limit, + ); +} diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 0445fa42d8a0a..177e6fcbf5008 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -227,6 +227,22 @@ export function splitMarkdownLinkSearchAndHash(value: string): { }; } +/** + * The decoded path a markdown destination names on the host, before any workspace resolution, or + * null for a `file:` URL that does not parse. Clients and the guest media route both read it here. + */ +export function markdownDestinationHostPath(source: string): string | null { + if (/^file:/i.test(source)) { + const target = parseFileUrlHref(source); + return target === null + ? null + : stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(target.path)); + } + return stripSlashPrefixedWindowsDrive( + safeDecodeURIComponent(splitMarkdownLinkSearchAndHash(source).path), + ); +} + export function isMarkdownFileLinkLabel(label: string, href: string): boolean { const destination = parseMarkdownFileLink(href); if (!destination) return false; diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.ts index e23195f693afe..aa753e6303fc0 100644 --- a/packages/shared/src/markdownPipeline.test.ts +++ b/packages/shared/src/markdownPipeline.test.ts @@ -12,7 +12,7 @@ it("preserves in-app thread links through the shared Markdown sanitizer", () => .use(CHAT_MARKDOWN_REHYPE_PLUGINS); const tree = processor.runSync( processor.parse( - '[Open thread](t3-thread://v1/environment/thread)\n\nUnsafe', + '[Open thread](t3-thread://v1/thread)\n\n\n\nUnsafe', ), ); expect(tree.children[0]).toMatchObject({ @@ -20,11 +20,21 @@ it("preserves in-app thread links through the shared Markdown sanitizer", () => children: [ { tagName: "a", - properties: { href: "t3-thread://v1/environment/thread" }, + properties: { href: "t3-thread://v1/thread" }, children: [{ type: "text", value: "Open thread" }], }, ], }); + expect(tree.children[2]).toMatchObject({ + tagName: "p", + children: [ + { + tagName: "a", + properties: { href: "t3-thread://v2/environment/thread:a%3A1" }, + children: [{ type: "text", value: "t3-thread://v2/environment/thread:a%3A1" }], + }, + ], + }); expect(JSON.stringify(tree)).not.toContain("javascript:"); }); diff --git a/packages/shared/src/threadLinks.test.ts b/packages/shared/src/threadLinks.test.ts index a6c8eebc7e65d..82d981f59827c 100644 --- a/packages/shared/src/threadLinks.test.ts +++ b/packages/shared/src/threadLinks.test.ts @@ -1,53 +1,69 @@ import { describe, expect, it } from "vite-plus/test"; -import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import { formatThreadLink, + guessThreadLinkRef, parseThreadLinkHref, relabelThreadLinks, - resolveThreadLinkRef, + threadLinkCandidates, + threadLinkRefs, } from "./threadLinks.ts"; const ref = (environmentId: string, threadId = "chat-1") => ({ environmentId: EnvironmentId.make(environmentId), threadId: ThreadId.make(threadId), }); +const v1 = (threadId: string) => ({ environmentId: null, threadId: ThreadId.make(threadId) }); +const local = EnvironmentId.make("local"); +const titlesIn = + (titles: Record>) => + ({ environmentId, threadId }: ScopedThreadRef) => + titles[environmentId]?.[threadId]; describe("thread link destinations", () => { - it("prefers the local literal id, then the local decoded id, over remote matches", () => { - const source = ref("local", "provider%3A1"); - const decoded = ref("local", "provider:1"); - const remote = ref("remote", "provider%3A1"); - expect(resolveThreadLinkRef(source, [remote, decoded, source])).toEqual(source); - expect(resolveThreadLinkRef(source, [remote, decoded])).toEqual(decoded); + it("names a v1 link's thread in the message's environment, as written and then decoded", () => { + expect(threadLinkCandidates(v1("provider%3A1"), local)).toEqual([ + ref("local", "provider%3A1"), + ref("local", "provider:1"), + ]); }); - it("opens the unique matching chat in another environment", () => { + it("opens the unique matching chat in another environment for a v1 link", () => { const destination = ref("remote"); - expect(resolveThreadLinkRef(ref("local"), [ref("local", "other-chat"), destination])).toEqual( + expect(guessThreadLinkRef(v1("chat-1"), [ref("local", "other-chat"), destination])).toEqual( destination, ); }); + it("opens a v2 link only in its own environment", () => { + const there = ref("there", "a%3A1"); + expect(threadLinkCandidates(there, local)).toEqual([there, ref("there", "a:1")]); + expect(guessThreadLinkRef(there, [ref("elsewhere", "a%3A1"), ref("elsewhere", "a:1")])).toBe( + null, + ); + }); + it("leaves ambiguous or missing destinations unresolved", () => { - const source = ref("local", "provider%3A1"); + const link = v1("provider%3A1"); const literal = ref("remote", "provider%3A1"); const decoded = ref("remote", "provider:1"); expect( - resolveThreadLinkRef(source, [literal, ref("other-remote", literal.threadId), decoded]), - ).toBeNull(); - expect( - resolveThreadLinkRef(source, [decoded, ref("other-remote", decoded.threadId)]), + guessThreadLinkRef(link, [literal, ref("other-remote", literal.threadId), decoded]), ).toBeNull(); - expect(resolveThreadLinkRef(source, [ref("remote", "other-chat")])).toBeNull(); + expect(guessThreadLinkRef(link, [decoded, ref("other-remote", decoded.threadId)])).toBeNull(); + expect(guessThreadLinkRef(link, [ref("remote", "other-chat")])).toBeNull(); }); }); describe("thread links", () => { - it("takes the thread id verbatim, percent escapes included", () => { - expect(parseThreadLinkHref("t3-thread://v1/mcp:1234")).toBe("mcp:1234"); - expect(parseThreadLinkHref("t3-thread://v1/thread:delegated-task:mcp%3A1")).toBe( - "thread:delegated-task:mcp%3A1", + it("takes the ids verbatim, percent escapes included", () => { + expect(parseThreadLinkHref("t3-thread://v1/mcp:1234")).toEqual(v1("mcp:1234")); + expect(parseThreadLinkHref("t3-thread://v1/thread:delegated-task:mcp%3A1")).toEqual( + v1("thread:delegated-task:mcp%3A1"), + ); + expect(parseThreadLinkHref("t3-thread://v2/env-1/thread:a/b%3A1")).toEqual( + ref("env-1", "thread:a/b%3A1"), ); }); @@ -55,59 +71,90 @@ describe("thread links", () => { expect(parseThreadLinkHref("https://t3.codes")).toBeNull(); expect(parseThreadLinkHref("t3-thread://v1/")).toBeNull(); expect(parseThreadLinkHref("t3-thread://v1/ ")).toBeNull(); + expect(parseThreadLinkHref("t3-thread://v2/env-1")).toBeNull(); + expect(parseThreadLinkHref("t3-thread://v2/env-1/")).toBeNull(); + expect(parseThreadLinkHref("t3-thread://v2//chat-1")).toBeNull(); }); it("resolves a percent-encoded id when the id as written names no thread", () => { - const titles = new Map([ - ["thread:project:1", "Decoded"], - ["provider%3A1", "Literal escape"], - ]); + const title = titlesIn({ local: { "thread:project:1": "Decoded", "provider%3A1": "Literal" } }); expect( relabelThreadLinks( "[a](t3-thread://v1/thread%3Aproject%3A1) [b](t3-thread://v1/provider%3A1)", - (threadId) => titles.get(threadId), + local, + title, ), - ).toBe( - "[Decoded](t3-thread://v1/thread:project:1) [Literal escape](t3-thread://v1/provider%3A1)", + ).toBe("[Decoded](t3-thread://v1/thread:project:1) [Literal](t3-thread://v1/provider%3A1)"); + const untitled = titlesIn({ local: { "a%3A1": "", "a:1": "Other" } }); + expect(relabelThreadLinks("[Kept](t3-thread://v1/a%3A1)", local, untitled)).toBe( + "[Kept](t3-thread://v1/a%3A1)", ); - const untitled = new Map([ - ["a%3A1", ""], - ["a:1", "Other"], - ]); + }); + + it("titles a v2 link from its own environment and writes it with that title", () => { + const title = titlesIn({ local: { t1: "Here" }, there: { t1: "There" } }); + expect( + relabelThreadLinks( + " and [old](t3-thread://v2/local/t1)", + local, + title, + ), + ).toBe("[There](t3-thread://v2/there/t1) and [Here](t3-thread://v2/local/t1)"); + }); + + it("turns a v2 link it cannot resolve into plain text, never the raw link", () => { expect( - relabelThreadLinks("[Kept](t3-thread://v1/a%3A1)", (threadId) => untitled.get(threadId)), - ).toBe("[Kept](t3-thread://v1/a%3A1)"); + relabelThreadLinks( + ", , [Old title](t3-thread://v2/there/t1)", + local, + () => undefined, + ), + ).toBe("Thread on another machine, Thread no longer available, Old title"); + expect(relabelThreadLinks("[Old](t3-thread://v1/t1)", local, () => undefined)).toBe( + "[Old](t3-thread://v1/t1)", + ); }); it("leaves links inside code spans and fences as written", () => { const markdown = [ "Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.", "```md", - "[old](t3-thread://v1/t1)", + "", "```", - "After [old](t3-thread://v1/t1)", + "After ", ].join("\n"); - expect(relabelThreadLinks(markdown, () => "New")).toBe( + expect(relabelThreadLinks(markdown, local, () => "New")).toBe( [ "Live [New](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.", "```md", - "[old](t3-thread://v1/t1)", + "", "```", - "After [New](t3-thread://v1/t1)", + "After [New](t3-thread://v2/local/t1)", ].join("\n"), ); }); - it("writes the thread id verbatim so the link opens that exact thread", () => { - const link = formatThreadLink("thread:delegated-task:mcp%3A1", "Fix"); - expect(link).toBe("[Fix](t3-thread://v1/thread:delegated-task:mcp%3A1)"); - expect(parseThreadLinkHref(link.slice(link.indexOf("](") + 2, -1))).toBe( - "thread:delegated-task:mcp%3A1", + it("lists the threads a message's links can name, outside code", () => { + expect( + threadLinkRefs( + " [a](t3-thread://v1/t%3A2) ``", + local, + ), + ).toEqual([ref("there", "t1"), ref("local", "t%3A2"), ref("local", "t:2")]); + }); + + it("writes a titleless autolink that opens that exact thread", () => { + const link = formatThreadLink(ref("env-1", "thread:delegated-task:mcp%3A1")); + expect(link).toBe(""); + expect(parseThreadLinkHref(link.slice(1, -1))).toEqual( + ref("env-1", "thread:delegated-task:mcp%3A1"), ); }); it("formats a label that would otherwise break the Markdown link", () => { - expect(formatThreadLink("t1", "Fix [ci] \\ build")).toBe("[Fix ci build](t3-thread://v1/t1)"); - expect(formatThreadLink("t1", " ] ")).toBe("[t1](t3-thread://v1/t1)"); + expect(formatThreadLink(ref("e", "t1"), "Fix [ci] \\ build")).toBe( + "[Fix ci build](t3-thread://v2/e/t1)", + ); + expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe(""); }); }); diff --git a/packages/shared/src/threadLinks.ts b/packages/shared/src/threadLinks.ts index 20c64e1ec1a39..a71fe4489d65e 100644 --- a/packages/shared/src/threadLinks.ts +++ b/packages/shared/src/threadLinks.ts @@ -1,19 +1,36 @@ -import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; export const THREAD_LINK_PROTOCOL = "t3-thread"; -const THREAD_LINK_HREF_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`; +const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`; +const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`; // Code comes first in the alternation so a link written inside a code span or fence is skipped. const THREAD_LINK_OUTSIDE_CODE = - /(?(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?(`+)[^\n]*?\4)|\[[^\]\n]*\]\((?t3-thread:\/\/v1\/[^\s)]+)\)/g; + /(?(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?(`+)[^\n]*?\4)|\[(?