From ba4d01cf7f78b29f2fb3a5be019e7ea8562ee692 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 21:04:49 -0800 Subject: [PATCH 001/436] fix(shared): login-shell environment probe ignores DEBUG trap output (#32646) Co-authored-by: Claude Opus 5.5 --- packages/shared/src/shell.test.ts | 33 +++++++++++++++++++++++++++++++ packages/shared/src/shell.ts | 10 +++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index d4e831f2af4b..83561c8daced 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -118,6 +118,39 @@ describe("readEnvironmentFromLoginShell", () => { }, ); + it.runIf(NodeFS.existsSync("/bin/bash"))( + "ignores probe markers a bash DEBUG trap echoes into the terminal title", + () => { + const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-bash-env-")); + try { + const shellPath = `${NodePath.join(home, "bin")}:/usr/bin:/bin`; + const bashEnv = NodePath.join(home, "env.bash"); + NodeFS.writeFileSync( + bashEnv, + [ + `export PATH=${JSON.stringify(shellPath)}`, + `trap 'echo -ne "\\033]0;\${BASH_COMMAND}\\007"' DEBUG`, + ].join("\n"), + ); + + expect( + readEnvironmentFromLoginShell( + "/bin/bash", + ["XDG_DATA_HOME", "PATH"], + // Non-interactive bash reads only BASH_ENV, not the host's /etc startup files that -il runs. + (file, [, command = ""], options) => + NodeChildProcess.execFileSync(file, ["-c", command], { + ...options, + env: { HOME: home, PATH: "/usr/bin:/bin", TERM: "dumb", BASH_ENV: bashEnv }, + }), + ), + ).toEqual({ PATH: shellPath }); + } finally { + NodeFS.rmSync(home, { recursive: true, force: true }); + } + }, + ); + it("extracts multiple environment variables from a login shell command", () => { const execFile = vi.fn< ( diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 8a0e0be51922..2b4dd9b96493 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -208,6 +208,8 @@ function envCaptureEnd(name: string): string { return `__T3CODE_ENV_${name}_END__`; } +const DEBUG_TRAP_SHELLS = new Set(["bash", "zsh", "sh", "ksh", "ksh93"]); + export function buildEnvironmentCaptureCommand( shell: string, names: ReadonlyArray, @@ -215,7 +217,7 @@ export function buildEnvironmentCaptureCommand( const executableName = NodePath.basename(shell).toLowerCase(); const isNushell = executableName.startsWith("nu"); - return names + const capture = names .map((name) => { if (!SHELL_ENV_NAME_PATTERN.test(name)) { throw new Error(`Unsupported environment variable name: ${name}`); @@ -249,6 +251,12 @@ export function buildEnvironmentCaptureCommand( ].join("; "); }) .join("; "); + + // A DEBUG trap that echoes each command (e.g. into the terminal title) would print the markers. + // OpenBSD ksh (also its /bin/sh) exits on `trap - DEBUG`, so try it in a subshell first. + return DEBUG_TRAP_SHELLS.has(executableName) + ? `(trap - DEBUG) 2>/dev/null && trap - DEBUG; ${capture}` + : capture; } function buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray): string { From 0815d98cd7dc8589e99fedca9fb8426b8a05318e Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Tue, 10 Nov 2026 23:15:14 -0600 Subject: [PATCH 002/436] fix(web): make Q&A option outlines visible across themes (#34178) --- .../chat/ComposerPendingUserInputPanel.tsx | 4 +-- apps/web/src/components/ui/checkbox.tsx | 30 ++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index c25eacd50671..c752e78c1ba6 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -285,7 +285,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( <> {activeQuestion.multiSelect ? ( - + ) : ( )} @@ -340,7 +340,7 @@ function OptionRadio({ checked }: { checked: boolean }) { diff --git a/apps/web/src/components/ui/checkbox.tsx b/apps/web/src/components/ui/checkbox.tsx index c7eb2bcfdda6..7c822ae01b1f 100644 --- a/apps/web/src/components/ui/checkbox.tsx +++ b/apps/web/src/components/ui/checkbox.tsx @@ -8,10 +8,21 @@ const rootClassName = const indicatorClassName = "-inset-px absolute flex items-center justify-center rounded-[.25rem] text-primary-foreground data-unchecked:hidden data-checked:bg-primary data-indeterminate:text-foreground in-[[data-slot=checkbox]:focus-visible]:inset-shadow-[0_0_0_3px_var(--background)] in-[[data-slot=checkbox]:focus-visible]:outline-2 in-[[data-slot=checkbox]:focus-visible]:outline-solid in-[[data-slot=checkbox]:focus-visible]:-outline-offset-2 in-[[data-slot=checkbox]:focus-visible]:outline-inherit"; -function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) { +const variantClassNames = { + default: "", + contrast: "border-foreground/55", +}; + +type CheckboxVariant = keyof typeof variantClassNames; + +function Checkbox({ + className, + variant = "default", + ...props +}: CheckboxPrimitive.Root.Props & { variant?: CheckboxVariant }) { return ( @@ -60,10 +71,21 @@ function Checkbox({ className, ...props }: CheckboxPrimitive.Root.Props) { } // Checkbox's look without its hidden input, for a row that is itself the button. -function CheckboxMark({ checked }: { checked: boolean }) { +function CheckboxMark({ + checked, + variant = "default", +}: { + checked: boolean; + variant?: CheckboxVariant; +}) { const state = checked ? { "data-checked": "" } : { "data-unchecked": "" }; return ( - + Date: Tue, 10 Nov 2026 23:17:03 -0600 Subject: [PATCH 003/436] fix(web): hide empty replies when renders show the result (#34182) --- .../chat/MessagesTimeline.logic.test.ts | 68 +++++++++++++++++++ .../components/chat/MessagesTimeline.logic.ts | 12 ++++ .../components/chat/TimelineAssistantRows.tsx | 3 +- 3 files changed, 82 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index ba0f508ebeec..2cbbbe762928 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -55,6 +55,74 @@ describe("resolveAssistantMessageCopyState", () => { }); describe("deriveMessagesTimelineRows", () => { + it.each([ + ["html-render", "reply-run", true], + ["mcp-app", "reply-run", true], + ["html-render", "other-run", false], + ["html-render", null, false], + [null, null, false], + ] as const)("suppresses the empty fallback for %s in %s: %s", (kind, renderRun, expected) => { + const at = "2026-11-06T00:00:00Z"; + const runId = RunId.make("reply-run"); + const renderBase = { + id: "render", + createdAt: at, + runId: renderRun ? RunId.make(renderRun) : null, + }; + const embedded: TimelineEntry[] = + kind === "html-render" + ? [ + { + ...renderBase, + kind, + htmlRender: { attachmentId: "preview", title: "Preview", height: 420 }, + }, + ] + : kind === "mcp-app" + ? [ + { + ...renderBase, + kind, + sourceThreadId: ThreadId.make("thread"), + itemId: TurnItemId.make("app"), + revision: "1", + mcpApp: { + attachmentId: "app", + server: "weather", + tool: "weather", + resourceUri: "ui://weather", + }, + }, + ] + : []; + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + ...embedded, + { + kind: "message", + id: "reply", + createdAt: at, + message: { + id: MessageId.make("reply"), + role: "assistant", + runId, + text: "", + streaming: false, + createdAt: at, + updatedAt: at, + }, + }, + ], + latestRun: null, + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + const reply = rows.find((row) => row.kind === "message" && row.id === "reply"); + expect(reply).toMatchObject({ suppressEmptyResponse: expected }); + }); + it.each(["alone", "before tool", "before commentary and tool"])( "keeps an unfinished task update static %s", (placement) => { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 4536e9a25038..45bebaa805f6 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -594,6 +594,7 @@ type MessagesTimelineRowContent = message: ChatMessage; projectedItem?: OrchestrationV2ProjectedTurnItem; showAssistantMeta: boolean; + suppressEmptyResponse?: boolean; showAssistantCopyButton: boolean; assistantCopyStreaming: boolean; assistantTurnDiffSummary?: TurnDiffSummary | undefined; @@ -1520,6 +1521,12 @@ export function deriveMessagesTimelineRows(input: { revealedMessageId?: MessageId | null; }): MessagesTimelineRow[] { const timelineEntries = timelineRowEntries(input); + const embeddedResultRunIds = new Set(); + for (const entry of timelineEntries) { + if ((entry.kind === "html-render" || entry.kind === "mcp-app") && entry.runId !== null) { + embeddedResultRunIds.add(entry.runId); + } + } const isPendingApproval = (entry: WorkLogEntry) => { const item = entry.projectedItem?.item; return ( @@ -2164,6 +2171,10 @@ export function deriveMessagesTimelineRows(input: { ? {} : { projectedItem: timelineEntry.projectedItem }), showAssistantMeta, + suppressEmptyResponse: + timelineEntry.message.role === "assistant" && + timelineEntry.message.runId != null && + embeddedResultRunIds.has(timelineEntry.message.runId), showAssistantCopyButton: showAssistantMeta, assistantCopyStreaming: timelineEntry.message.streaming || assistantResponseStillInProgress, assistantTurnDiffSummary: @@ -2633,6 +2644,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.message === bm.message && a.projectedItem === bm.projectedItem && a.showAssistantMeta === bm.showAssistantMeta && + a.suppressEmptyResponse === bm.suppressEmptyResponse && a.showAssistantCopyButton === bm.showAssistantCopyButton && a.assistantCopyStreaming === bm.assistantCopyStreaming && a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary && diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 458d84b9e982..6756220a990c 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -32,7 +32,8 @@ export function AssistantTimelineRow({ row }: { row: Extract From 4363d0bf658f67089fcae185d2354e01a1a6706c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 21:22:21 -0800 Subject: [PATCH 004/436] fix(web): mouse tilt wheel no longer switches threads on Windows and Linux desktop (#32963) Co-authored-by: Claude Opus 5.5 --- .../HistorySwipeNavigation.browser.test.tsx | 13 +++++++++++++ apps/web/src/components/HistorySwipeNavigation.tsx | 8 ++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx index b2e6fcaaaf40..10bf817b7363 100644 --- a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -29,6 +29,7 @@ describe("HistorySwipeNavigation", () => { ["a swipe that started in a closed dialog keeps the thread", "closed-dialog", 0, -130, false], ] as const)("%s", async (_name, scroller, scrollLeft, deltaX, navigates) => { navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); await using screen = await render(); const panel = screen.container.appendChild(document.createElement("div")); const root = scroller.startsWith("shadow") ? panel.attachShadow({ mode: "open" }) : panel; @@ -58,4 +59,16 @@ describe("HistorySwipeNavigation", () => { expect(navigateHistory).toHaveBeenCalledTimes(navigates ? 1 : 0); }); + + it("a horizontal mouse wheel tick off macOS keeps the thread", async () => { + navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Win32"); + await using screen = await render(); + const content = screen.container.appendChild(document.createElement("div")); + content.style.cssText = "height: 20px; width: 100px"; + + swipe(content, -120); + + expect(navigateHistory).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index 767b4285c696..e1adc04491a9 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -1,7 +1,7 @@ import { ArrowLeftIcon, ArrowRightIcon } from "lucide-react"; import { useEffect, useState } from "react"; -import { cn } from "../lib/utils"; +import { cn, isMacPlatform } from "../lib/utils"; import { canNavigateHistory, navigateHistory, type HistoryDirection } from "../navigationHistory"; const SWIPE_TRIGGER_DISTANCE = 120; @@ -88,12 +88,16 @@ export function isMomentumTail(deltas: readonly number[]): boolean { ); } -/** Two-finger horizontal trackpad swipes go back and forward, like a browser. */ +/** + * Two-finger horizontal trackpad swipes go back and forward, like a browser. + * macOS only: on Windows and Linux a mouse tilt wheel is indistinguishable from a trackpad swipe. + */ export function HistorySwipeNavigation() { const [swipe, setSwipe] = useState(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window wheel and desktop gesture listeners track trackpad swipes useEffect(() => { + if (!isMacPlatform(navigator.platform)) return; let gesture: SwipeGesture | null = null; const hideIndicator = () => setSwipe((current) => (current === null ? null : { ...current, tracking: false })); From 32fdad5f49498c8ea72a2418da2dc69703dfd500 Mon Sep 17 00:00:00 2001 From: NoomStuff <128687290+NoomStuff@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:26:41 +0100 Subject: [PATCH 005/436] fix(web): timeline minimap preview no longer steals hover or jumps around (#32151) Co-authored-by: Julius Marminge Co-authored-by: Claude Opus 5.5 --- .../components/chat/MessagesTimeline.logic.ts | 12 ++---- .../src/components/chat/TimelineMinimap.tsx | 39 ++++--------------- 2 files changed, 10 insertions(+), 41 deletions(-) diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 45bebaa805f6..2fd1eced3a44 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -283,7 +283,9 @@ export function workEntryIsVisibleInGroup( } const TIMELINE_MINIMAP_ITEM_SPACING = 8; export const TIMELINE_MINIMAP_MIN_ITEMS = 2; -const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "calc(100vh - 18rem)"; +// Relative to the timeline, not the viewport, so an open terminal shrinks the rail and +// endpoint previews (centered on their strip) still fit above and below it. +const TIMELINE_MINIMAP_MAX_HEIGHT_CSS = "max(4rem, calc(100% - 14.75rem))"; const TIMELINE_MINIMAP_PERSISTENT_GUTTER = 48; export interface WorkGroupScrollAnchor { @@ -443,7 +445,6 @@ export function resolveTimelineMinimapHasPersistentGutter( const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 12; const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40; -const TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH = "22rem"; export function resolveTimelineMinimapHitStripWidth( viewportWidth: number, @@ -465,13 +466,6 @@ export function resolveTimelineMinimapNavigationInteractive(collapsedWidth: numb return collapsedWidth >= TIMELINE_MINIMAP_NAVIGATION_REACH; } -export function resolveTimelineMinimapInteractiveWidth( - collapsedWidth: number, - expanded: boolean, -): number | string { - return expanded ? TIMELINE_MINIMAP_EXPANDED_HIT_STRIP_WIDTH : collapsedWidth; -} - function computeElapsedMs(startIso: string, endIso: string): number | null { const start = Date.parse(startIso); const end = Date.parse(endIso); diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index 3aefd3c34e6a..3a32ec20400d 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -5,7 +5,6 @@ import { Button } from "../ui/button"; import { resolveTimelineMinimapHeightStyle, resolveTimelineMinimapIndexFromPointer, - resolveTimelineMinimapInteractiveWidth, resolveTimelineMinimapNavigationInteractive, resolveTimelineMinimapTopPercent, TIMELINE_MINIMAP_MIN_ITEMS, @@ -13,10 +12,6 @@ import { import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; -function timelineMinimapEventTargetsPreview(target: EventTarget): boolean { - return target instanceof Element && target.closest("[data-minimap-preview]") !== null; -} - // A release outside the window can skip `mouseup`, so the next button-free // `mousemove` also counts. function onMouseButtonsReleased(onRelease: () => void): () => void { @@ -74,14 +69,6 @@ export function TimelineMinimap({ resolvedActiveIndex === null ? 0 : resolveTimelineMinimapTopPercent(resolvedActiveIndex, items.length); - const activeTooltipTranslate = - resolvedActiveIndex === null - ? "-50%" - : resolvedActiveIndex === 0 - ? "0%" - : resolvedActiveIndex === items.length - 1 - ? "-100%" - : "-50%"; const resolvedCurrentIndex = currentIndex !== null && currentIndex >= 0 && currentIndex < items.length ? currentIndex : null; const previousItem = @@ -147,7 +134,7 @@ export function TimelineMinimap({ }} style={{ height: resolveTimelineMinimapHeightStyle(items.length), - width: resolveTimelineMinimapInteractiveWidth(hitStripWidth, activeItem !== null), + width: hitStripWidth, }} >
@@ -245,14 +224,10 @@ export function TimelineMinimap({ ); })} {activeItem ? ( + // Display-only: it overlaps the message column, and the strip keeps tracking beneath it. event.stopPropagation()} - style={{ - top: `${activeTopPercent}%`, - transform: `translateY(${activeTooltipTranslate})`, - }} + className="pointer-events-none absolute left-8 w-80 -translate-y-1/2" + style={{ top: `${activeTopPercent}%` }} > @@ -311,7 +286,7 @@ function TimelineMinimapNavigationButton({ className={cn( "absolute left-1 z-10 inline-flex -translate-x-1/2 opacity-0 transition-opacity duration-150 hover:opacity-100 focus-within:opacity-100", interactive ? "pointer-events-auto" : "pointer-events-none", - previous ? "bottom-[calc(100%+2px)]" : "top-[calc(100%+2px)]", + previous ? "bottom-[calc(100%+6px)]" : "top-[calc(100%+6px)]", )} /> } From c192c6786779ebd439e5a47bc181b076ba0bbee5 Mon Sep 17 00:00:00 2001 From: Tanav Poswal <63358333+tanav29@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:02:01 +0530 Subject: [PATCH 006/436] fix(server): auto thread sends queue while a turn is stopping (#34163) Co-authored-by: Julius Marminge --- .../ThreadManagementService.ts | 1 + .../src/orchestration-v2/ThreadStop.test.ts | 92 +++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 81d252389072..f67e9768667e 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -865,6 +865,7 @@ const make = Effect.gen(function* () { ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }), ...(input.freshContext ? { freshContext: true } : {}), dispatchMode, + ...(mode === "auto" ? { deliveryIntent: "auto" } : {}), createdBy: input.createdBy, creationSource: input.creationSource, }); diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index 6b3ea08a8644..a0e6d4bae4c8 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -796,6 +796,98 @@ it.effect("a message the user sends after Stop releases the held queue; an agent }).pipe(Effect.provide(layerTest)), ); +it.effect( + "an agent's auto send queues behind a run that is still stopping instead of steering it", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const threadId = ThreadId.make("thread:stop-mcp-send"); + yield* createWatchingThread(threadId, 6); + yield* send(threadId, "active", "start_immediately"); + const initial = yield* orchestrator.getThreadProjection(threadId); + const run = initial.runs[0]!; + const providerSessionId = ProviderSessionId.make("session:stop-mcp-send"); + const now = yield* DateTime.now; + yield* projections.apply({ + id: EventId.make("event:stop-mcp-send:session"), + type: "provider-session.updated", + threadId, + occurredAt: now, + payload: { + id: providerSessionId, + driver: adapter.driver, + providerInstanceId: instanceId, + status: "ready", + cwd: "/repo", + model: modelSelection.model, + capabilities: CodexProviderCapabilitiesV2, + createdAt: now, + updatedAt: now, + lastError: null, + }, + }); + yield* projections.apply({ + id: EventId.make("event:stop-mcp-send:provider-thread"), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { ...initial.providerThreads[0]!, providerSessionId }, + }); + yield* projections.apply({ + id: EventId.make("event:stop-mcp-send:running"), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "running", startedAt: now }, + }); + yield* projections.apply({ + id: EventId.make("event:stop-mcp-send:turn"), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderTurnId.make("provider-turn:stop-mcp-send"), + providerThreadId: run.providerThreadId!, + nodeId: run.rootNodeId!, + runAttemptId: run.activeAttemptId!, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + yield* send(threadId, "queued before the stop", "queue_after_active"); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-mcp-send"), + threadId, + }); + assert.deepEqual((yield* threadState(threadId)).runs, ["running", "queued:held"]); + + const result = yield* threads.sendToThread({ + projectId: ProjectId.make("project:thread-stop"), + commandId: CommandId.make("command:stop-mcp-send"), + threadId, + messageId: MessageId.make("message:stop-mcp-send"), + text: "Follow up after Stop", + attachments: [], + mode: "auto", + createdBy: "agent", + creationSource: "mcp", + }); + assert.equal(result.delivery, "queued"); + assert.deepEqual((yield* threadState(threadId)).runs, [ + "running", + "queued:held", + "queued:held", + ]); + }).pipe(Effect.provide(layerTest)), +); + it.effect( "thread.stop ends an idle thread's watches and accepts a thread with nothing to stop", () => From c03f84bcde5952a83242652308200a862411eed1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 21:32:03 -0800 Subject: [PATCH 007/436] fix(server): stream the usage-scan cache to disk instead of one string (#34030) --- apps/server/src/usage/UsageService.test.ts | 16 +++++---- apps/server/src/usage/UsageService.ts | 36 +++++++++++++++++++- apps/server/src/usage/usageScanCache.test.ts | 21 +++++------- apps/server/src/usage/usageScanCache.ts | 28 +++++++-------- packages/shared/src/atomicWrite.test.ts | 16 +++++++++ packages/shared/src/atomicWrite.ts | 29 ++++++++++++++-- 6 files changed, 108 insertions(+), 38 deletions(-) diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index a3775c6aebe1..a1de34fac38b 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2587,7 +2587,7 @@ describe("UsageService", () => { ); it.live.each([4, 5, 6, 7, 8, 10])( - "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts and the old file", + "upgrades a v%s cache: reparses live Codex usage, keeps deleted rollouts, removes the old file", (version) => Effect.gen(function* () { const { home, settings } = yield* setup; @@ -2636,7 +2636,7 @@ describe("UsageService", () => { yield* first.readSummary(WINDOW); yield* first.awaitPersisted; - const legacy = yield* Effect.promise(async () => { + yield* Effect.promise(async () => { const livePath = await NodeFSP.realpath(live); const document = decodeUnknownJsonString(await NodeFSP.readFile(cachePath, "utf8")) as { files: Record }>; @@ -2674,7 +2674,9 @@ describe("UsageService", () => { } } await NodeFSP.rm(deleted); - return text; + await NodeFSP.mkdir(`${cachePath}.stale`); + await NodeFSP.utimes(`${cachePath}.stale`, 0, 0); + await NodeFSP.mkdir(`${cachePath}.active`); }); const upgraded = yield* UsageService.make; @@ -2686,9 +2688,11 @@ describe("UsageService", () => { ); yield* upgraded.awaitPersisted; assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v11.json"); - assert.strictEqual( - yield* Effect.promise(() => NodeFSP.readFile(legacyPath, "utf8")), - legacy, + assert.deepStrictEqual( + (yield* Effect.promise(() => NodeFSP.readdir(stateDir))) + .filter((name) => name.startsWith("usage-scan-cache")) + .toSorted(), + [SCAN_CACHE_FILE_NAME, `${SCAN_CACHE_FILE_NAME}.active`], ); }).pipe( Effect.provide( diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index 6b6762c089ba..b834b078058a 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -71,6 +71,7 @@ const MTIME_SLACK_MS = 36 * 60 * 60 * 1000; const MAX_HOURLY_WINDOW_MS = 24 * 60 * 60 * 1000; const CACHE_RETENTION_DAYS = 92; +const STALE_TEMP_DIRECTORY_MS = 60 * 60 * 1000; const TRANSCRIPT_READ_CONCURRENCY = 4; @@ -172,7 +173,7 @@ export const make = Effect.gen(function* () { const ratesCachePath = path.join(config.stateDir, "usage-model-rates.json"); const scanCachePath = path.join(config.stateDir, SCAN_CACHE_FILE_NAME); - const writeCacheFile = (filePath: string, contents: string) => + const writeCacheFile = (filePath: string, contents: string | Iterable) => writeFileStringAtomically({ filePath, contents }).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), @@ -407,6 +408,32 @@ export const make = Effect.gen(function* () { // Serialize writes so concurrently finished window scans cannot overwrite newer snapshots. const persistLock = yield* Semaphore.make(1); + // The saved cache supersedes older versions. Temp folders an aborted write left behind are + // removed once idle for an hour, so a write in progress from another server survives. + let supersededFilesRemoved = false; + const removeSupersededCacheFiles = Effect.gen(function* () { + for (const fileName of LEGACY_SCAN_CACHE_FILE_NAMES) { + yield* fileSystem.remove(path.join(config.stateDir, fileName)).pipe(Effect.ignore); + } + const tempPrefixes = [SCAN_CACHE_FILE_NAME, ...LEGACY_SCAN_CACHE_FILE_NAMES].map( + (fileName) => `${fileName}.`, + ); + const staleBeforeMs = (yield* Clock.currentTimeMillis) - STALE_TEMP_DIRECTORY_MS; + for (const name of yield* fileSystem.readDirectory(config.stateDir)) { + if (!tempPrefixes.some((prefix) => name.startsWith(prefix))) continue; + const tempPath = path.join(config.stateDir, name); + yield* fileSystem.stat(tempPath).pipe( + Effect.flatMap((info) => { + const mtimeMs = Option.getOrUndefined(info.mtime)?.getTime(); + return info.type === "Directory" && mtimeMs !== undefined && mtimeMs <= staleBeforeMs + ? fileSystem.remove(tempPath, { recursive: true }) + : Effect.void; + }), + Effect.ignore, + ); + } + }).pipe(Effect.ignore); + // Clear dirty before encoding to retain concurrent changes; restore it on failure for retry. const persistCaches = Effect.gen(function* () { if (cacheDirty) { @@ -415,6 +442,13 @@ export const make = Effect.gen(function* () { writeScanCache(fileCache, { sources: Object.fromEntries(sourceCache) }), ).pipe( Effect.flatMap((contents) => writeCacheFile(scanCachePath, contents)), + Effect.andThen( + Effect.suspend(() => { + if (supersededFilesRemoved) return Effect.void; + supersededFilesRemoved = true; + return removeSupersededCacheFiles; + }), + ), Effect.catchCause(() => Effect.sync(() => { cacheDirty = true; diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index fa659c4a443b..d0e5eaceec26 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -11,6 +11,8 @@ import type { UsageRecord } from "@t3tools/provider-core/server/usage"; import { TEST_FORMAT_MAP } from "./usageTestFormats.ts"; import { initialCodexScanState, parseCodexLine } from "../provider/Drivers/codexUsage.ts"; +const parse = (parts: Iterable) => JSON.parse([...parts].join("")); + function record(overrides: Partial = {}): UsageRecord { return { provider: "claude", @@ -152,10 +154,7 @@ describe("scan cache round trip", () => { record({ model: "", dedupeKey: "msg_tail:" }), ], }); - const restored = decodeScanCache( - JSON.parse(makeScanCacheWriter()(cached, {})), - TEST_FORMAT_MAP, - ); + const restored = decodeScanCache(parse(makeScanCacheWriter()(cached, {})), TEST_FORMAT_MAP); expect(restored.size).toBe(4); expect(restored).toEqual(original); @@ -196,7 +195,7 @@ describe("scan cache round trip", () => { malformedRecords: 0, }; original.set("/clean-codex.jsonl", cleanCodex); - const encoded = JSON.parse(makeScanCacheWriter()(original, {})); + const encoded = parse(makeScanCacheWriter()(original, {})); const entry = encoded.files["/gone.jsonl"]!; const legacy = { ...encoded, @@ -251,7 +250,7 @@ describe("scan cache round trip", () => { it("re-parses a Claude transcript cached before advisor usage was counted", () => { const original = cacheWith([["/claude.jsonl", 100, [record()]]]); - const v9 = { ...JSON.parse(makeScanCacheWriter()(original, {})), version: 9 }; + const v9 = { ...parse(makeScanCacheWriter()(original, {})), version: 9 }; const restored = decodeScanCache(JSON.parse(JSON.stringify(v9)), TEST_FORMAT_MAP); expect(restored.get("/claude.jsonl")).toEqual({ @@ -269,7 +268,7 @@ describe("scan cache round trip", () => { ]); cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, malformedRecords: 2 }); const sources = { "claude\u0000/projects": { dir: "/projects", volumeId: "1:2" } }; - expect(decodeScanCache(JSON.parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache); + expect(decodeScanCache(parse(write(cache, { sources })), TEST_FORMAT_MAP)).toEqual(cache); cache.set("/b.jsonl", { ...cache.get("/b.jsonl")!, @@ -277,7 +276,7 @@ describe("scan cache round trip", () => { malformedRecords: 4, records: [record({ sessionId: "session-c", model: "claude-opus-5-5", dedupeKey: "msg_3:" })], }); - const document = JSON.parse(write(cache, { sources })); + const document = parse(write(cache, { sources })); expect(decodeScanCache(document, TEST_FORMAT_MAP)).toEqual(cache); expect(document.sources).toEqual(sources); }); @@ -291,9 +290,7 @@ describe("scan cache round trip", () => { }); it("skips malformed file entries but keeps good ones", () => { - const encoded = JSON.parse( - makeScanCacheWriter()(cacheWith([["/good.jsonl", 100, [record()]]]), {}), - ); + const encoded = parse(makeScanCacheWriter()(cacheWith([["/good.jsonl", 100, [record()]]]), {})); const withJunk = { ...encoded, files: { ...encoded.files, "/bad.jsonl": { s: "nope", m: 1, p: "claude", r: [] } }, @@ -304,7 +301,7 @@ describe("scan cache round trip", () => { }); it("drops the whole entry when any row is corrupt, forcing a cold re-parse", () => { - const encoded = JSON.parse( + const encoded = parse( makeScanCacheWriter()( cacheWith([["/a.jsonl", 100, [record(), record({ dedupeKey: "msg_2:" })]]]), {}, diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index c9032d64c05b..c2cdc1cbf5ab 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -15,7 +15,7 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** * An older server sharing that directory cannot read a newer cache and would * replace it, dropping saved usage for deleted transcripts. Separate files keep - * both. + * the newer one; older files are removed once it is saved. */ export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v11.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ @@ -134,32 +134,28 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile }; } -/** Memoizes immutable entries by identity; growing intern tables preserve indexes, retaining unused strings until restart. */ +/** Yields the document in pieces so large caches never become one string; growing intern tables preserve indexes, retaining unused strings until restart. */ export function makeScanCacheWriter(): ( cache: ScanCache, extra: Readonly>, -) => string { +) => Iterable { const tables = makeInternTables(); - const fragments = new WeakMap(); - return (cache, extra) => { - const files: string[] = []; - for (const [path, entry] of cache) { - let fragment = fragments.get(entry); - if (fragment === undefined) { - fragment = JSON.stringify(serializeFile(entry, tables)); - fragments.set(entry, fragment); - } - files.push(`${JSON.stringify(path)}:${fragment}`); + function* encode(entries: readonly (readonly [string, CachedFile])[], extra: object) { + yield '{"files":{'; + for (const [index, [path, entry]] of entries.entries()) { + yield `${index === 0 ? "" : ","}${JSON.stringify(path)}:${JSON.stringify(serializeFile(entry, tables))}`; } // Encoded after the files, which may have added to the intern tables. - const head = JSON.stringify({ + const tail = JSON.stringify({ ...extra, version: USAGE_SCAN_CACHE_VERSION, models: tables.models, sessions: tables.sessions, }); - return `${head.slice(0, -1)},"files":{${files.join(",")}}}`; - }; + yield `},${tail.slice(1)}`; + } + // Snapshot now: the encoding runs later, while the file is written. + return (cache, extra) => encode([...cache], extra); } function isRecordArray(value: unknown): value is readonly unknown[] { diff --git a/packages/shared/src/atomicWrite.test.ts b/packages/shared/src/atomicWrite.test.ts index 3b0a99ec0d2d..6aec907c049a 100644 --- a/packages/shared/src/atomicWrite.test.ts +++ b/packages/shared/src/atomicWrite.test.ts @@ -44,6 +44,22 @@ it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => { }), ); + it.effect("streams iterable contents across write batches", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const filePath = path.join(root, "cache.json"); + yield* fs.writeFileString(filePath, "a much longer previous document"); + const chunks = ["é".repeat(700_000), "🙂".repeat(400_000), "end"]; + + yield* writeFileStringAtomically({ filePath, contents: chunks.values() }); + + assert.strictEqual(yield* fs.readFileString(filePath), chunks.join("")); + assert.deepStrictEqual(yield* fs.readDirectory(root), ["cache.json"]); + }), + ); + it.effect("keeps a symlinked file linked and rewrites its destination", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/packages/shared/src/atomicWrite.ts b/packages/shared/src/atomicWrite.ts index e48755047398..39904817fb67 100644 --- a/packages/shared/src/atomicWrite.ts +++ b/packages/shared/src/atomicWrite.ts @@ -16,11 +16,12 @@ export const isWindowsRenameLock = (error: PlatformError.PlatformError) => { // Bound denial delays to about two seconds because settings saves hold their write lock. const LOCKED_RENAME_RETRIES = 20; const LOCKED_RENAME_RETRY_DELAY = "100 millis"; +const CHUNK_WRITE_LENGTH = 1 << 20; -/** Resolves symlink targets before renaming so writes preserve the link. */ +/** Resolves symlink targets before renaming so writes preserve the link. Iterable contents stream in bounded batches. */ export const writeFileStringAtomically = (input: { readonly filePath: string; - readonly contents: string; + readonly contents: string | Iterable; }) => Effect.scoped( Effect.gen(function* () { @@ -41,7 +42,29 @@ export const writeFileStringAtomically = (input: { ); const tempPath = path.join(tempDirectory, "contents.tmp"); - yield* fs.writeFileString(tempPath, input.contents); + const contents = input.contents; + if (typeof contents === "string") { + yield* fs.writeFileString(tempPath, contents); + } else { + // Closed before the rename, which Windows refuses for open files. + yield* Effect.scoped( + Effect.gen(function* () { + const file = yield* fs.open(tempPath, { flag: "w" }); + const encoder = new TextEncoder(); + let batch: string[] = []; + let batchLength = 0; + for (const chunk of contents) { + batch.push(chunk); + batchLength += chunk.length; + if (batchLength < CHUNK_WRITE_LENGTH) continue; + yield* file.writeAll(encoder.encode(batch.join(""))); + batch = []; + batchLength = 0; + } + if (batchLength > 0) yield* file.writeAll(encoder.encode(batch.join(""))); + }), + ); + } if (platform !== "win32") return yield* fs.rename(tempPath, targetPath); // Stop retrying if another save changes the target; read-only targets also return permanent EPERM. From 5b11efe5df2f44741d2a89733ee49b00b753e5d1 Mon Sep 17 00:00:00 2001 From: Federico Infelici <49081659+fedeinfe@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:35:32 +0100 Subject: [PATCH 008/436] fix(clients): images the agent opens stay visible in the chat (#30473) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../src/features/threads/ThreadFeed.tsx | 14 +++ apps/mobile/src/lib/threadActivity.ts | 44 ++++++++- .../Adapters/CodexAdapterV2.test.ts | 68 +++++++++++++ .../Adapters/CodexAdapterV2.ts | 21 ++++ .../chat/MessagesTimeline.logic.test.ts | 99 +++++++++++++++++++ .../components/chat/MessagesTimeline.logic.ts | 57 +++++++++-- .../src/components/chat/MessagesTimeline.tsx | 5 +- .../components/chat/TimelineWorkEntryRow.tsx | 32 ++++++ .../src/work-log/presentation.ts | 7 ++ 9 files changed, 332 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index e7f4bfbc3d02..277fd104805a 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -286,6 +286,7 @@ const WIDE_MARKDOWN_BLOCK_OPTIONS = { const TURN_FOLD_HEIGHT = 42; const FEED_PADDING_TOP = 12; +const VIEWED_IMAGE_GAP = 8; const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5; const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5; // Virtualization remounts old rows; only newly created content should replay an entrance. @@ -1722,6 +1723,19 @@ function renderFeedEntry( ); } + if (entry.type === "viewed-images") { + const thumbnailWidth = Math.floor((props.contentWidth - VIEWED_IMAGE_GAP) / 2); + return ( + + {entry.paths.map((path) => ( + + {props.renderViewedImage({ href: path, alt: null, title: null })} + + ))} + + ); + } + if (entry.type === "mcp-app") { return ( ; + } | { readonly type: "run-fold"; readonly deferredWorkItemIds?: ReadonlyArray; @@ -1252,7 +1261,10 @@ const supersededReasoningGroups = new WeakMap(); function settleSupersededReasoning( - entry: Exclude, + entry: Exclude< + ThreadFeedEntry, + { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" } + >, tail: boolean, ) { if (entry.type !== "activity-group") return entry; @@ -1527,7 +1539,10 @@ export function deriveThreadFeedPresentation( const lastEntryByRun = new Map(); const retainedFeed: Array< - Exclude + Exclude< + ThreadFeedEntry, + { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" } + > > = []; const retainedFeedIndices: number[] = []; const { toolCallVisibility, revealedMessageId } = display; @@ -1540,7 +1555,12 @@ export function deriveThreadFeedPresentation( : null; for (let index = start; index < feed.length; index += 1) { let entry = feed[index]!; - if (entry.type === "run-fold" || entry.type === "work-toggle" || entry.type === "thinking") + if ( + entry.type === "run-fold" || + entry.type === "work-toggle" || + entry.type === "thinking" || + entry.type === "viewed-images" + ) continue; const runId = feedEntryRunId(entry); if (runId !== null) { @@ -1819,7 +1839,10 @@ function thinkingRow(createdAt: string, runId: RunId | null, label: string | nul function appendPresentedFeedEntry( result: ThreadFeedEntry[], - entry: Exclude, + entry: Exclude< + ThreadFeedEntry, + { readonly type: "run-fold" | "work-toggle" | "thinking" | "viewed-images" } + >, expandedWorkGroupIds: ReadonlySet, activeRunId: RunId | null, isWorking: boolean, @@ -1890,16 +1913,27 @@ function appendActivityGroupRows( let groupableRun: ThreadFeedActivity[] = []; const flushGroupableRun = (isTrailingRun: boolean) => { if (groupableRun.length === 0) return; + const groupId = `work-group:${groupAnchorIdByActivityId.get(groupableRun[0]!.id) ?? groupableRun[0]!.id}`; appendToolGroupRows( result, entry, groupableRun, - `work-group:${groupAnchorIdByActivityId.get(groupableRun[0]!.id) ?? groupableRun[0]!.id}`, + groupId, expandedWorkGroupIds, activeRunId, isWorking, activeTail && isTrailingRun, ); + const paths = workEntriesViewedImagePaths(groupableRun.map((activity) => activity.workEntry)); + if (paths.length > 0) { + result.push({ + type: "viewed-images", + id: `${groupId}:viewed-images`, + createdAt: groupableRun[0]!.createdAt, + runId: groupableRun[0]!.runId, + paths, + }); + } groupableRun = []; }; for (const activity of activities) { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index e8e4bf37d479..f8c63587fec6 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1375,6 +1375,74 @@ describe("CodexAdapterV2 post-settle continuation", () => { }; }); + it.effect("keeps native image views available to the clients", () => + Effect.gen(function* () { + const nativeThreadId = "image-view-thread"; + const nativeTurnId = "image-view-turn"; + const imagePath = "file:///workspace/reference.png"; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "image-view", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Show the reference." }), + ...(["started", "completed"] as const).map((phase) => ({ + type: "emit_inbound" as const, + label: `image ${phase}`, + frame: { + method: `item/${phase}`, + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + item: { type: "imageView", id: "image-view", path: imagePath }, + ...(phase === "started" ? { startedAtMs: 1 } : { completedAtMs: 2 }), + }, + }, + })), + { + type: "emit_inbound", + label: "turn completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("image-view-attempt"), + text: "Show the reference.", + }), + ); + yield* harness.firstTerminal; + const images = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "dynamic_tool" + ? [event.turnItem] + : [], + ); + assert.lengthOf(images, 1); + assert.equal(images[0]?.viewedImagePath, imagePath); + assert.equal(images[0]?.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each(["before", "after"] as const)( "rejects a previous run's native turn when it completes %s the new start response", (completionOrder) => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 66bc21d6030f..6953636a8dcf 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -5357,6 +5357,27 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return; } + if (payload.item.type === "imageView") { + const artifacts = yield* buildDynamicToolArtifacts(context, { + type: "dynamicToolCall", + id: payload.item.id, + tool: "view_image", + arguments: { path: payload.item.path }, + status: "completed", + }); + yield* emitProviderEvent({ + type: "node.updated", + driver: CODEX_PROVIDER, + node: artifacts.node, + }); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: { ...artifacts.turnItem, viewedImagePath: payload.item.path }, + }); + return; + } + if (payload.item.type !== "agentMessage") { return; } diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 2cbbbe762928..5d242f1efc20 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -2210,6 +2210,105 @@ describe("deriveMessagesTimelineRows", () => { ]); }); + it("shows images the agent viewed outside their collapsed tool group", () => { + const threadId = ThreadId.make("viewed-images-thread"); + const runId = RunId.make("viewed-images-run"); + const at = (second: number) => + DateTime.makeUnsafe(new Date(Date.UTC(2026, 10, 4, 12, 0, second)).toISOString()); + const base = (id: string, ordinal: number) => ({ + id: TurnItemId.make(id), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed" as const, + title: null, + startedAt: at(ordinal), + completedAt: at(ordinal), + updatedAt: at(ordinal), + }); + const read = (id: string, ordinal: number, filePath: string) => ({ + ...base(id, ordinal), + type: "dynamic_tool" as const, + toolName: "Read", + // The Claude adapter tags reads of image files. + ...(filePath.endsWith(".png") ? { viewedImagePath: filePath } : {}), + input: { file_path: filePath }, + }); + const items = (settled: boolean) => + [ + { + ...base("prompt", 0), + type: "user_message" as const, + messageId: MessageId.make("prompt"), + text: "Show me the mockups", + attachments: [], + inputIntent: "turn_start" as const, + createdBy: "user" as const, + creationSource: "web" as const, + }, + read("read-sidebar", 1, "/repo/docs/sidebar.png"), + read("read-notes", 2, "/repo/docs/notes.md"), + read("read-sidebar-again", 3, "/repo/docs/sidebar.png"), + read("read-topbar", 4, "/repo/docs/topbar.png"), + settled + ? { + ...base("answer", 5), + type: "assistant_message" as const, + messageId: MessageId.make("answer"), + text: "Here are both layouts", + streaming: false, + } + : { + ...base("ask-again", 5), + status: "waiting" as const, + completedAt: null, + type: "user_input_request" as const, + requestId: RuntimeRequestId.make("layout-question"), + questions: [], + }, + ].map((item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: item.id, + item, + })); + const viewedImages = (settled: boolean, expandedRunIds?: ReadonlySet) => { + const rows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items(settled), + optimisticMessages: [], + }), + latestRun: { + runId, + status: settled ? "completed" : "running", + startedAt: DateTime.formatIso(at(0)), + completedAt: settled ? DateTime.formatIso(at(5)) : null, + }, + runningRunId: settled ? null : runId, + isWorking: !settled, + activeTurnStartedAt: settled ? null : DateTime.formatIso(at(0)), + ...(expandedRunIds === undefined ? {} : { expandedRunIds }), + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + return rows.flatMap((row, index) => + row.kind === "viewed-images" ? [{ after: rows[index - 1]?.kind, paths: row.paths }] : [], + ); + }; + const paths = ["/repo/docs/sidebar.png", "/repo/docs/topbar.png"]; + + expect(viewedImages(false)).toEqual([{ after: "work-live", paths }]); + // A settled turn's fold keeps hiding its work, images included, until it is opened. + expect(viewedImages(true)).toEqual([]); + expect(viewedImages(true, new Set([runId]))).toEqual([{ after: "work-toggle", paths }]); + }); + it("keeps imported V1 turns folded once the thread's first V2 run starts", () => { const at = (second: number) => `2026-01-01T00:00:${String(second).padStart(2, "0")}Z`; const message = ( diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 2fd1eced3a44..94fbe68e2952 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -27,6 +27,7 @@ import { toolGroupAction, toolGroupSummaryKind, contextCompactionTokenCounts, + workEntriesViewedImagePaths, type ToolGroupSummaryKind, liveThoughtLine, workEntryHiddenByToolCallVisibility, @@ -549,6 +550,13 @@ type MessagesTimelineRowContent = toolIcon?: WorkLogEntry["toolIcon"]; hasFailure: boolean; } + | { + /** Images the agent opened in the tool group above, kept visible while the group is collapsed. */ + kind: "viewed-images"; + id: string; + createdAt: string; + paths: ReadonlyArray; + } | { kind: "turn-fold"; deferredWorkItemIds?: ReadonlyArray; @@ -662,6 +670,17 @@ function expandedWorkGroupRow( }; } +function viewedImagesRows( + groupId: string, + createdAt: string, + groupedEntries: ReadonlyArray, +): Array> { + const paths = workEntriesViewedImagePaths(groupedEntries); + return paths.length === 0 + ? [] + : [{ kind: "viewed-images", id: `${groupId}:viewed-images`, createdAt, paths }]; +} + export function resolveAssistantMessageCopyState({ text, showCopyButton, @@ -1792,9 +1811,17 @@ export function deriveMessagesTimelineRows(input: { if (activeWorkRow === null) return; nextRows.push(activeWorkRow); hasActivityRow ||= activeWorkRow.active; - if (!activeWorkRow.expanded) return; + if (activeWorkRow.expanded) { + nextRows.push( + expandedWorkGroupRow( + activeWorkRow.groupId, + activeWorkRow.createdAt, + activeWorkRow.groupedEntries, + ), + ); + } nextRows.push( - expandedWorkGroupRow( + ...viewedImagesRows( activeWorkRow.groupId, activeWorkRow.createdAt, activeWorkRow.groupedEntries, @@ -2058,6 +2085,13 @@ export function deriveMessagesTimelineRows(input: { ); } } + nextRows.push( + ...viewedImagesRows( + workGroupId(timelineEntry.id), + timelineEntry.createdAt, + visibleGroupedEntries, + ), + ); } index = cursor - 1; continue; @@ -2241,6 +2275,7 @@ export function deriveMessagesTimelineRows(input: { if (failedGroupAnchor) { const groupId = workGroupId(failedGroupAnchor.id); const expanded = input.expandedWorkGroupIds?.has(groupId) ?? false; + const groupedEntries = visibleActiveToolEntries.map((entry) => entry.entry); nextRows.push({ kind: "thinking", id: LIVE_ACTIVITY_ROW_ID, @@ -2249,14 +2284,9 @@ export function deriveMessagesTimelineRows(input: { expanded, }); if (expanded) { - nextRows.push( - expandedWorkGroupRow( - groupId, - failedGroupAnchor.createdAt, - visibleActiveToolEntries.map((entry) => entry.entry), - ), - ); + nextRows.push(expandedWorkGroupRow(groupId, failedGroupAnchor.createdAt, groupedEntries)); } + nextRows.push(...viewedImagesRows(groupId, failedGroupAnchor.createdAt, groupedEntries)); } else { nextRows.push({ kind: "thinking", @@ -2573,6 +2603,15 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; + case "viewed-images": { + const bv = b as typeof a; + return ( + a.createdAt === bv.createdAt && + a.paths.length === bv.paths.length && + a.paths.every((path, index) => path === bv.paths[index]) + ); + } + case "html-render": { // Tool updates rebuild entries; preserve frames for unchanged pages. const bh = b as typeof a; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 3e13b788b17a..61d5c4d97e45 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -117,6 +117,7 @@ import { LiveWorkEntryTimelineRow, WorkGroupToggleTimelineRow, } from "./TimelineWorkGroupRows"; +import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; import { UserMessageRow } from "./TimelineUserMessageRow"; import { AssistantTimelineRow, @@ -1453,7 +1454,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time row.kind === "event" || row.kind === "attempt-fold" || row.kind === "html-render" || - row.kind === "mcp-app" + row.kind === "mcp-app" || + row.kind === "viewed-images" ? "pb-2" : "pb-4", (row.kind === "message" && row.message.role === "assistant") || @@ -1502,6 +1504,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "assistant-meta" ? : null} {row.kind === "proposed-plan" ? : null} {row.kind === "html-render" ? : null} + {row.kind === "viewed-images" ? : null} {row.kind === "mcp-app" ? : null} {row.kind === "working" ? : null} {row.kind === "worktree-setup" ? : null} diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx index 95661d16b930..5f63142a8e29 100644 --- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx +++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx @@ -51,6 +51,7 @@ import { TimelineRowCtx, TimelineRowActivityCtx, WorkGroupViewCtx, + type TimelineRow, type TimelineWorkEntry, } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, TimelineRowTimestamp } from "./TimelineRowParts"; @@ -171,6 +172,37 @@ export const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: WorkEn ); }); +export function ViewedImagesTimelineRow({ + row, +}: { + row: Extract; +}) { + const { threadRef, workspaceRoot, onImageExpand } = use(TimelineRowCtx); + if (!threadRef) return null; + return ( +
+ {row.paths.map((path) => { + const image = resolveViewedImageAsset(path, { + threadId: threadRef.threadId, + workspaceRoot, + }); + return image ? ( + + ) : null; + })} +
+ ); +} + function WorkEntryLogRow(props: WorkEntryRowProps) { const { workEntry, workspaceRoot, displayLabel } = props; const ctx = use(TimelineRowCtx); diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts index fd0dca831e06..e2097ed4a46c 100644 --- a/packages/client-runtime/src/work-log/presentation.ts +++ b/packages/client-runtime/src/work-log/presentation.ts @@ -414,6 +414,13 @@ export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): strin : null; } +/** Distinct images the agent opened across a tool group, in viewing order. */ +export function workEntriesViewedImagePaths( + entries: ReadonlyArray, +): string[] { + return [...new Set(entries.flatMap((entry) => workEntryViewedImagePath(entry) ?? []))]; +} + export interface ViewedImageAsset { readonly resource: Extract; readonly alt: string; From 31bf2f7f3404200503300064fec9c6676c55691a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 21:38:54 -0800 Subject: [PATCH 009/436] fix(client-runtime): pasted repository page URLs clone the repository into its own folder (#32681) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/CommandPalette.tsx | 3 +- docs/user/source-control.md | 4 +- .../src/operations/projects.test.ts | 27 +++++++++++++ .../client-runtime/src/operations/projects.ts | 3 +- .../src/shared/definition.test.ts | 11 +++++ .../src/shared/definition.ts | 4 ++ .../src/shared/definition.ts | 40 +++++++++++++++++++ .../src/shared/definition.test.ts | 16 ++++++++ .../src/shared/definition.ts | 9 +++++ .../src/shared/definition.ts | 6 +++ .../src/shared/definition.test.ts | 8 ++++ .../src/shared/definition.ts | 4 ++ .../src/shared/definition.ts | 4 ++ 13 files changed, 135 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index a6dd4fe1d40c..fd912fda2cc7 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2006,7 +2006,7 @@ function OpenCommandPaletteDialog(props: { function getDefaultCloneDestination( environmentId: EnvironmentId, remoteUrl: string, - repository: string, + repository?: string, ): string { const environment = environments.find((candidate) => candidate.environmentId === environmentId); return getCloneDestinationPath( @@ -2061,7 +2061,6 @@ function OpenCommandPaletteDialog(props: { const destinationPath = getDefaultCloneDestination( addProjectCloneFlow.environmentId, remoteUrl, - rawRepository, ); setAddProjectCloneFlow({ step: "confirm", diff --git a/docs/user/source-control.md b/docs/user/source-control.md index e9edbb449dd8..8bbeb7e988cb 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -155,7 +155,9 @@ publish it. If Git has no name or email on that machine, the project is created first commit. Use **Add Project** in the command palette (`Cmd/Ctrl+K`) to clone a repository. Choose a hosting -provider or paste a Git URL, then choose where to save it. The project opens right away while the +provider or paste a Git URL, then choose where to save it. A branch or file page copied from GitHub, +GitLab, GitCafe, Codeberg or Bitbucket also works: T3 Code clones that repository's default branch. +On other hosts, paste the repository's clone URL. The project opens right away while the clone runs in the background: you can write your first prompt, and sending waits until the files are in place. A toast tracks progress and lets you cancel; if the clone fails, retry it from the toast or from the banner above the composer. When the host refuses the machine's SSH key, T3 Code diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts index 5b55a40f4ebb..698754f069cc 100644 --- a/packages/client-runtime/src/operations/projects.test.ts +++ b/packages/client-runtime/src/operations/projects.test.ts @@ -63,6 +63,33 @@ describe("add project shared logic", () => { ); expect(normalizePastedCloneUrl("group/subgroup/project")).toBe("group/subgroup/project"); expect(normalizePastedCloneUrl("/srv/git/repo.git")).toBe("/srv/git/repo.git"); + for (const gitlabProject of [ + "https://gitlab.com/acme/tools/src/branch/worker.git", + "https://scm.example.test/acme/tools/src/branch/worker.git", + "https://scm.example.test/acme/tools/src/branch/worker", + "https://scm.example.test/team/repo/src/branch/main/-/README.md", + "https://forgejo.example.test/a/b/src/branch/mount/team/repo.git", + ]) { + expect(normalizePastedCloneUrl(gitlabProject)).toBe(gitlabProject); + } + }); + + it("clones the repository when given a page URL copied from the browser", () => { + for (const [pageUrl, pageRoute, repository] of [ + ["https://github.com/pingdotgg/t3code/tree/main", "/tree/", "t3code"], + ["https://gitlab.com/gitlab-org/gitlab-runner/-/tree/main", "/-/", "gitlab-runner"], + ["https://git.cafe/pingdotgg/t3code/tree/main", "/tree/", "t3code"], + ["https://gitlab.example.test/g/p/-/blob/main/src/branch/x", "/-/", "p"], + ["https://code.company.test/g/p/-/tree/main", "/-/", "p"], + ["https://github.com/pingdotgg/t3code/tree/release.git", "/tree/", "t3code"], + ] as const) { + const cloneUrl = normalizePastedCloneUrl(pageUrl); + expect(cloneUrl).not.toContain(pageRoute); + expect(getCloneDirectoryName(cloneUrl)).toBe(repository); + } + expect( + normalizePastedCloneUrl("https://alice:example@bitbucket.org/workspace/repo/src/master/"), + ).toBe("https://alice:example@bitbucket.org/workspace/repo"); }); it("uses HTTPS for repositories selected through a provider", () => { diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index aab4f0f28429..f0d7e489423f 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -128,7 +128,8 @@ export function githubIncompleteOwnerRepositoryMessage( export function normalizePastedCloneUrl(input: string): string { const trimmed = input.trim(); - return REPOSITORY_SHORTHAND.test(trimmed) ? (defaultHostCloneUrl(trimmed) ?? trimmed) : trimmed; + if (REPOSITORY_SHORTHAND.test(trimmed)) return defaultHostCloneUrl(trimmed) ?? trimmed; + return sourceControlClients.repositoryUrlFromPage(trimmed) ?? trimmed; } export function getDefaultCloneUrl( diff --git a/packages/source-control-bitbucket/src/shared/definition.test.ts b/packages/source-control-bitbucket/src/shared/definition.test.ts index f10b9c7e6bdf..da844c2b2a2a 100644 --- a/packages/source-control-bitbucket/src/shared/definition.test.ts +++ b/packages/source-control-bitbucket/src/shared/definition.test.ts @@ -51,6 +51,17 @@ describe("Bitbucket change request URLs", () => { }); }); +describe("Bitbucket repository pages", () => { + it("reads the repository from a source view on Bitbucket hosts only", () => { + const repositoryUrl = (url: string) => definition.repositoryUrlFromPage?.(new URL(url)); + expect(repositoryUrl("https://bitbucket.org/workspace/repo/src/main/")).toBe( + "https://bitbucket.org/workspace/repo", + ); + expect(repositoryUrl("https://bitbucket.org/workspace/repo")).toBeNull(); + expect(repositoryUrl("https://scm.example.test/workspace/repo/src/main/")).toBeNull(); + }); +}); + describe("Bitbucket remotes", () => { const recognize = (url: string) => recognizeRemoteWith(definition, url); diff --git a/packages/source-control-bitbucket/src/shared/definition.ts b/packages/source-control-bitbucket/src/shared/definition.ts index 2f643751c599..edb1b103081c 100644 --- a/packages/source-control-bitbucket/src/shared/definition.ts +++ b/packages/source-control-bitbucket/src/shared/definition.ts @@ -14,6 +14,7 @@ import { isChangeRequestOnProjectHost, parseChangeRequestPath, parseCommitPath, + repositoryUrlFromPagePath, projectChangeRequestHost, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; @@ -23,6 +24,7 @@ const repositoryName = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/; const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull-requests\/(\d+)(?:\/|$)/u; const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/commits\/([0-9a-f]+)\/?$/iu; +const REPOSITORY_PAGE_PATH = /^\/([^/]+\/[^/]+)\/src\/[^/]/u; const KIND = SourceControlProviderKind.make("bitbucket"); @@ -96,6 +98,8 @@ export const definition = defineSourceControl({ commitUrl: (input) => buildCommitUrl(input, "commits"), parseCommitUrl: (url) => isBitbucketHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null, + repositoryUrlFromPage: (url) => + isBitbucketHost(url.hostname) ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) : null, changeRequestUrlFromReferenceAutolink: () => null, // No endpoint reopens a declined pull request, and nothing documented moves one in or out of // draft, so neither is offered rather than failing when pressed. diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index 8f71e1cc7346..a94ed6708e2d 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -258,6 +258,12 @@ export interface SourceControlDefinition { readonly parseCommitUrl?: (url: URL, known: boolean) => CommitLink | null; /** Null when the URL is not one of this host's change requests. */ readonly parseChangeRequestUrl: (url: URL) => ParsedChangeRequestUrl | null; + /** + * The repository URL when `url` is a page inside one of this host's repositories. `known` is set + * when the caller already knows this host serves the URL's repository. Off a known host, return + * `url.href` when the path may already be a clone URL, so no rewrite happens. + */ + readonly repositoryUrlFromPage?: (url: URL, known: boolean) => string | null; /** * The change request URL a `reference` autolink might name, such as a GitHub `#123` written * through the issue route. Only a candidate: the caller must read it as a change request @@ -410,6 +416,18 @@ export function parseChangeRequestPath(url: URL, route: RegExp): ParsedChangeReq : null; } +/** Reads a repository page from `url` with `route`, whose first group is the repository path. */ +export function repositoryUrlFromPagePath(url: URL, route: RegExp): string | null { + const repository = route.exec(url.pathname)?.[1]; + if (!repository) return null; + // Keeps the credentials and port a private clone relies on. + const repositoryUrl = new URL(url); + repositoryUrl.pathname = `/${repository}`; + repositoryUrl.search = ""; + repositoryUrl.hash = ""; + return repositoryUrl.href; +} + export function changeRequestUrlBelow(webUrl: string, route: string): string { return `${webUrl.replace(/\/+$/u, "")}/${route}`; } @@ -615,6 +633,8 @@ export interface SourceControlDefinitionRegistry { readonly hostLabelForChangeRequestUrl: (url: string) => string; readonly isSameChangeRequest: (left: string, right: string) => boolean; readonly changeRequestUrlFromReferenceAutolink: (url: string) => string | null; + /** The repository a page URL copied from a browser is in, such as a branch or file view. */ + readonly repositoryUrlFromPage: (url: string) => string | null; /** * The host a remote is on, from the first definition in recognition order that claims it, or an * unknown host. Null when the remote names no host. @@ -683,6 +703,8 @@ export function makeSourceControlDefinitionRegistry( } return undefined; }; + const remoteOwner = (remote: GitRemoteHost) => + recognitionOrder.find((definition) => definition.recognizeRemote(remote) !== null); const parseChangeRequestUrl = (value: string): ParsedChangeRequest | null => { const url = httpUrl(value); if (url === null) return null; @@ -744,6 +766,24 @@ export function makeSourceControlDefinitionRegistry( } return null; }, + repositoryUrlFromPage: (value) => { + const url = httpUrl(value); + if (url === null) return null; + // A recognized host's paths are its own, so another host's any-host route never rewrites them. + const remote = parseGitRemoteHost(value); + const owner = remote === null ? undefined : remoteOwner(remote); + if (owner) return owner.repositoryUrlFromPage?.(url, true) ?? null; + // Elsewhere a path ending in `.git` is already a clone URL, whatever routes it contains. + if (url.pathname.replace(/\/$/u, "").endsWith(".git")) return null; + // On an unrecognized host, only rewrite when every route that matches agrees. A route that + // answers with the page itself says it may already be the clone URL. + const [repositoryUrl, ...others] = new Set( + claimOrder.flatMap((definition) => definition.repositoryUrlFromPage?.(url, false) ?? []), + ); + return repositoryUrl !== undefined && repositoryUrl !== url.href && others.length === 0 + ? repositoryUrl + : null; + }, recognizeRemote: (remoteUrl) => { const remote = parseGitRemoteHost(remoteUrl); if (remote === null) return null; diff --git a/packages/source-control-forgejo/src/shared/definition.test.ts b/packages/source-control-forgejo/src/shared/definition.test.ts index 139d21c37f5c..ccf88aa461de 100644 --- a/packages/source-control-forgejo/src/shared/definition.test.ts +++ b/packages/source-control-forgejo/src/shared/definition.test.ts @@ -104,6 +104,22 @@ describe("Forgejo change request URLs", () => { }); }); +describe("Forgejo repository pages", () => { + it("reads the repository from branch, tag and commit views", () => { + const repositoryUrl = (url: string) => definition.repositoryUrlFromPage?.(new URL(url), true); + expect(repositoryUrl("https://codeberg.org/forgejo/forgejo/src/branch/forgejo/README.md")).toBe( + "https://codeberg.org/forgejo/forgejo", + ); + expect(repositoryUrl("http://git.example.test:3000/git/team/repo/src/tag/v1.0")).toBe( + "http://git.example.test:3000/git/team/repo", + ); + expect(repositoryUrl("https://codeberg.org/forgejo/forgejo/src/commit/abc123")).toBe( + "https://codeberg.org/forgejo/forgejo", + ); + expect(repositoryUrl("https://codeberg.org/forgejo/forgejo")).toBeNull(); + }); +}); + describe("Forgejo remotes", () => { it("recognises Codeberg and Forgejo or Gitea hosts, keeping an HTTP remote's origin", () => { for (const host of ["codeberg.org", "forgejo.example.test", "gitea.example.test"]) { diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.ts index f78805fee1c6..65360496f28d 100644 --- a/packages/source-control-forgejo/src/shared/definition.ts +++ b/packages/source-control-forgejo/src/shared/definition.ts @@ -10,6 +10,7 @@ import { isChangeRequestOnProjectHost, parseChangeRequestPath, parseCommitPath, + repositoryUrlFromPagePath, projectChangeRequestHost, remoteWebOrigin, } from "@t3tools/source-control-core/shared/definition"; @@ -22,6 +23,7 @@ const CHANGE_REQUEST_REFERENCE = // Forgejo and Gitea run on any hostname, possibly mounted below a path. const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/pulls\/(\d+)(?:\/|$)/u; const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/commit\/([0-9a-f]+)\/?$/iu; +const REPOSITORY_PAGE_PATH = /^\/([^/]+(?:\/[^/]+)+?)\/src\/(?:branch|tag|commit)\/[^/]/u; const KIND = SourceControlProviderKind.make("forgejo"); @@ -87,6 +89,13 @@ export const definition = defineSourceControl({ changeRequestUrlFromReferenceAutolink: () => null, commitUrl: (input) => buildCommitUrl(input, "commit"), parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), + repositoryUrlFromPage: (url, known) => { + // A mount path may itself contain `src/branch/`, so a `.git` path is always the clone URL. + if (url.pathname.replace(/\/$/u, "").endsWith(".git")) return null; + const repositoryUrl = repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH); + // Elsewhere the same path is a GitLab project nested under groups named `src` and `branch`. + return repositoryUrl === null || known ? repositoryUrl : url.href; + }, changeRequestActions: new Set(["merge", "close", "reopen", "update-branch"] as const), // Neither `fj` nor `tea` checks out by number. checkoutCommand: ({ number, repositoryUrl }) => diff --git a/packages/source-control-gitcafe/src/shared/definition.ts b/packages/source-control-gitcafe/src/shared/definition.ts index 3749063ce7c1..2abc258fbf95 100644 --- a/packages/source-control-gitcafe/src/shared/definition.ts +++ b/packages/source-control-gitcafe/src/shared/definition.ts @@ -14,6 +14,7 @@ import { parseChangeRequestPath, parseCommitPath, projectChangeRequestHost, + repositoryUrlFromPagePath, } from "@t3tools/source-control-core/shared/definition"; import { icon } from "./icon.ts"; @@ -23,6 +24,7 @@ const GITCAFE_HOSTS = new Set(["git.cafe", "staging.git.cafe"]); /** GitCafe serves pull requests at `/pull/` and redirects the older `/pulls/` there. */ const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pulls?\/(\d+)(?:\/|$)/u; const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/commit\/([0-9a-f]+)\/?$/iu; +const REPOSITORY_PAGE_PATH = /^\/([^/]+\/[^/]+)\/(?:tree|blob)\/[^/]/u; function parseChangeRequestUrl(url: URL) { return GITCAFE_HOSTS.has(url.hostname.toLowerCase()) @@ -72,6 +74,10 @@ export const definition = defineSourceControl({ commitUrl: (input) => buildCommitUrl(input, "commit"), parseCommitUrl: (url) => GITCAFE_HOSTS.has(url.hostname.toLowerCase()) ? parseCommitPath(url, COMMIT_PATH) : null, + repositoryUrlFromPage: (url) => + GITCAFE_HOSTS.has(url.hostname.toLowerCase()) + ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) + : null, changeRequestUrlFromReferenceAutolink: () => null, changeRequestActions: new Set([ "ready", diff --git a/packages/source-control-github/src/shared/definition.test.ts b/packages/source-control-github/src/shared/definition.test.ts index 924ab3171685..17ac17ad437b 100644 --- a/packages/source-control-github/src/shared/definition.test.ts +++ b/packages/source-control-github/src/shared/definition.test.ts @@ -96,6 +96,14 @@ describe("GitHub change request URLs", () => { }); }); +describe("GitHub repository pages", () => { + it("leaves the tree route on other hosts to them", () => { + expect( + definition.repositoryUrlFromPage?.(new URL("https://scm.example.test/o/r/tree/main")), + ).toBeNull(); + }); +}); + describe("GitHub remotes", () => { const recognize = (url: string) => recognizeRemoteWith(definition, url); diff --git a/packages/source-control-github/src/shared/definition.ts b/packages/source-control-github/src/shared/definition.ts index 3c33cfb3a3f6..b08547ae12c1 100644 --- a/packages/source-control-github/src/shared/definition.ts +++ b/packages/source-control-github/src/shared/definition.ts @@ -8,6 +8,7 @@ import { isChangeRequestOnProjectHost, parseChangeRequestPath, parseCommitPath, + repositoryUrlFromPagePath, projectChangeRequestHost, remoteWebOrigin, type SourceControlAppSignIn, @@ -26,6 +27,7 @@ const CHANGE_REQUEST_REFERENCE = const CHANGE_REQUEST_PATH = /^\/([^/]+\/[^/]+)\/pull\/(\d+)(?:\/|$)/u; const COMMIT_PATH = /^\/([^/]+\/[^/]+)\/(?:commit|pull\/\d+\/commits)\/([0-9a-f]+)\/?$/iu; const ISSUE_PATH = /^\/([^/]+\/[^/]+)\/issues\/(\d+)(?:\/|$)/u; +const REPOSITORY_PAGE_PATH = /^\/([^/]+\/[^/]+)\/(?:tree|blob)\/[^/]/u; const KIND = SourceControlProviderKind.make("github"); @@ -98,6 +100,8 @@ export const definition = defineSourceControl({ parseCommitUrl: (url, known) => known || isGitHubHost(url.hostname) ? parseCommitPath(url, COMMIT_PATH) : null, parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH), + repositoryUrlFromPage: (url) => + isGitHubHost(url.hostname) ? repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH) : null, // GitHub writes every bare reference through `/issues/`, including pull requests. changeRequestUrlFromReferenceAutolink: (url) => { const match = isGitHubHost(url.hostname) ? ISSUE_PATH.exec(url.pathname) : null; diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.ts index 16d5bb8cf0ef..96d6f7be7200 100644 --- a/packages/source-control-gitlab/src/shared/definition.ts +++ b/packages/source-control-gitlab/src/shared/definition.ts @@ -7,6 +7,7 @@ import { isChangeRequestOnProjectHost, parseChangeRequestPath, parseCommitPath, + repositoryUrlFromPagePath, projectChangeRequestHost, remoteWebOrigin, } from "@t3tools/source-control-core/shared/definition"; @@ -20,6 +21,8 @@ const CHANGE_REQUEST_REFERENCE = // Self-managed GitLab runs on any hostname and nests projects in groups. const CHANGE_REQUEST_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/merge_requests\/(\d+)(?:\/|$)/u; const COMMIT_PATH = /^\/([^/]+(?:\/[^/]+)+)\/-\/commit\/([0-9a-f]+)\/?$/iu; +// Every GitLab page inside a project sits below its first `/-/`. +const REPOSITORY_PAGE_PATH = /^\/([^/]+(?:\/[^/]+)+?)\/-\//u; const KIND = SourceControlProviderKind.make("gitlab"); @@ -47,6 +50,7 @@ export const definition = defineSourceControl({ parseChangeRequestUrl: (url) => parseChangeRequestPath(url, CHANGE_REQUEST_PATH), commitUrl: (input) => buildCommitUrl(input, "-/commit"), parseCommitUrl: (url) => parseCommitPath(url, COMMIT_PATH), + repositoryUrlFromPage: (url) => repositoryUrlFromPagePath(url, REPOSITORY_PAGE_PATH), // `!12` already links the merge request itself; `#12` is always an issue. changeRequestUrlFromReferenceAutolink: (url) => CHANGE_REQUEST_PATH.test(url.pathname) ? url.toString() : null, From 11611419f39eb2bdc222989e842f3da4033b99b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 21:39:00 -0800 Subject: [PATCH 010/436] fix(web): trackpad flicks over the right panel tabs no longer navigate back (#33396) Co-authored-by: Claude Opus 5.5 --- .../RightPanelTabs.browser.test.tsx | 135 ++++++++++++++++++ apps/web/src/components/RightPanelTabs.tsx | 7 +- 2 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 apps/web/src/components/RightPanelTabs.browser.test.tsx diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx new file mode 100644 index 000000000000..eea63a9c85a6 --- /dev/null +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -0,0 +1,135 @@ +import "~/index.css"; + +import { describe, expect, it, vi } from "vite-plus/test"; + +import type { RightPanelSurface } from "~/rightPanelStore"; +import { render, stubGlobal } from "../../test/render"; +import { HistorySwipeNavigation } from "./HistorySwipeNavigation"; +import { RightPanelTabs } from "./RightPanelTabs"; + +const navigateHistory = vi.hoisted(() => vi.fn()); +vi.mock("../navigationHistory", () => ({ canNavigateHistory: () => true, navigateHistory })); + +// Chromium starts a gesture scroll, and Electron reports its begin, only for a +// wheel event the page did not preventDefault; it then scrolls the latched scroller. +function trackpad() { + const begin = new Set<() => void>(); + const end = new Set<() => void>(); + const subscribe = (listeners: Set<() => void>) => (listener: () => void) => { + listeners.add(listener); + return () => listeners.delete(listener); + }; + let scrolling = false; + return { + bridge: { onTrackpadScrollBegin: subscribe(begin), onTrackpadScrollEnd: subscribe(end) }, + scroll(target: Element, deltas: readonly number[]) { + let scroller: Element | null = target; + while ( + scroller && + (scroller.scrollWidth <= scroller.clientWidth || + !/auto|scroll/.test(getComputedStyle(scroller).overflowX)) + ) { + scroller = scroller.parentElement; + } + for (const deltaX of deltas) { + const event = new WheelEvent("wheel", { + deltaX, + bubbles: true, + cancelable: true, + composed: true, + }); + target.dispatchEvent(event); + if (event.defaultPrevented) continue; + if (scroller) scroller.scrollLeft += deltaX; + if (scrolling) continue; + scrolling = true; + for (const listener of begin) listener(); + } + if (scrolling) for (const listener of end) listener(); + scrolling = false; + }, + }; +} + +const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ({ + id: `terminal:${index}`, + kind: "terminal", + resourceId: `${index}`, + terminalIds: [`${index}`], + activeTerminalId: `${index}`, +})); + +describe("RightPanelTabs", () => { + it("a flick that scrolls the tab strip to its left edge keeps the thread, a swipe from the edge goes back", async () => { + navigateHistory.mockReset(); + const { bridge, scroll } = trackpad(); + using _bridge = stubGlobal("desktopBridge", bridge); + const panel = document.createElement("div"); + panel.style.cssText = "width: 320px; height: 200px; display: flex"; + const noop = () => {}; + await using screen = await render( + <> + + ({ + terminalFocus: false, + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: true, + isDesktop: false, + })} + surfaces={surfaces} + environmentId={null} + activeSurfaceId={null} + pendingSurfaceIds={new Set()} + previewSessions={{}} + desktopByTabId={{}} + terminalLabelsById={new Map(surfaces.map((surface) => [surface.id, "Terminal"]))} + onActivate={noop} + onCloseSurface={noop} + onCloseOtherSurfaces={noop} + onCloseSurfacesToRight={noop} + onCloseAllSurfaces={noop} + onCopyFilePath={noop} + onAddBrowser={noop} + onAddBrowserInProfile={noop} + onAddTerminal={noop} + onAddDiff={noop} + onAddFiles={noop} + onAddPullRequest={noop} + onAddPullRequests={noop} + onAddDevice={noop} + browserAvailable={false} + terminalAvailable + diffAvailable={false} + filesAvailable={false} + pullRequestAvailable={false} + pullRequestsAvailable={false} + deviceAvailable={false} + > + {null} + + , + { container: panel }, + ); + const viewport = screen.container.querySelector( + '[data-right-panel-tab-list] [data-slot="scroll-area-viewport"]', + )!; + expect(viewport.scrollWidth - viewport.clientWidth).toBeGreaterThan(120); + viewport.scrollLeft = 120; + + const momentum = Array.from({ length: 24 }, (_, index) => -60 * 0.85 ** index); + scroll(viewport.querySelector("[data-active-tab]")!, [-10, -20, -30, ...momentum]); + + expect(viewport.scrollLeft).toBe(0); + expect(navigateHistory).not.toHaveBeenCalled(); + + viewport.scrollLeft = 0; + scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); + + expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back"); + }); +}); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index d3c650e8a4c5..f3066201f71e 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1291,12 +1291,13 @@ export function RightPanelTabs(props: RightPanelTabsProps) { if (!viewport) return; const update = () => updateTabScrollState(viewport); + // Only a vertical mouse wheel is translated. Horizontal input scrolls natively, since + // consuming it keeps Chromium from starting the gesture scroll that swipe navigation tracks. const handleWheel = (event: WheelEvent) => { - if (event.ctrlKey) return; - let delta = Math.abs(event.deltaX) > Math.abs(event.deltaY) ? event.deltaX : event.deltaY; + if (event.ctrlKey || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return; + let delta = event.deltaY; if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) delta *= 16; if (event.deltaMode === WheelEvent.DOM_DELTA_PAGE) delta *= viewport.clientWidth; - if (delta === 0) return; const previousScrollLeft = viewport.scrollLeft; viewport.scrollLeft += delta; From a0efdaeb89a75050612a82436432de4ebf526206 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 21:45:24 -0800 Subject: [PATCH 011/436] fix: new threads move from draft to Working in one step (#33783) Co-authored-by: Claude Opus 5.5 --- .../src/features/home/HomeRouteScreen.tsx | 7 +- .../threads/ThreadNavigationSidebar.tsx | 9 ++- .../state/composer-attachment-uploads.test.ts | 1 + .../src/state/pending-new-tasks-model.test.ts | 63 ++++++++++++++++- .../src/state/pending-new-tasks-model.ts | 40 ++++++++++- .../src/state/pending-thread-creation.test.ts | 31 +++++++++ .../src/state/pending-thread-creation.ts | 29 ++++++++ .../threadOutboxDelivery.permissions.test.ts | 1 + .../src/state/threadOutboxDelivery.test.ts | 1 + apps/mobile/src/state/threadOutboxDelivery.ts | 17 +++++ .../mobile/src/state/use-pending-new-tasks.ts | 67 ++++++++++++++++++- apps/mobile/src/state/use-thread-outbox.ts | 5 ++ apps/web/src/components/Sidebar.tsx | 19 +++++- .../components/sidebar/SidebarThreadRow.tsx | 12 +++- apps/web/src/composerDraftStore.ts | 11 +++ .../client-runtime/src/state/threadInbox.ts | 19 ++++++ 16 files changed, 315 insertions(+), 17 deletions(-) diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index f1b163461b6c..a2db3d14d45f 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -16,7 +16,7 @@ import { import { useProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; -import { usePendingNewTasks } from "../../state/use-pending-new-tasks"; +import { useLaunchingThreads, usePendingNewTasks } from "../../state/use-pending-new-tasks"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { @@ -46,9 +46,8 @@ export function HomeRouteScreen() { const projects = useProjects(); // Stop rebuilding the streaming thread list while Thread covers Home. const visible = useHomeRouteVisible(); - const threads = useAtomValueWhileVisible( - environmentThreadShells.navigationThreadShellsAtom, - visible, + const threads = useLaunchingThreads( + useAtomValueWhileVisible(environmentThreadShells.navigationThreadShellsAtom, visible), ); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); const { savedConnectionsById } = useSavedRemoteConnections(); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 3d0253e2d3a2..6d724ac3b016 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -32,7 +32,11 @@ import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-pref import { useThreadListNow } from "./use-thread-list-now"; import { usePendingThreadOrder } from "../../state/thread-order"; import { threadListEnvironmentsAtom } from "../../state/presentation"; -import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks"; +import { + useLaunchingThreads, + usePendingNewTasks, + type PendingNewTask, +} from "../../state/use-pending-new-tasks"; import { useQueuedThreadKeys } from "../../state/use-thread-outbox"; import { useWorkspaceState } from "../../state/workspace"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; @@ -136,6 +140,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { regenerateThreadTitle, } = useThreadListActions(); const pendingTasks = usePendingNewTasks(); + const launchingThreads = useLaunchingThreads(threads); const activeNewTask = useActiveNewTask(); const queuedThreadKeys = useQueuedThreadKeys(); const selectDetail = useSelectWorkspaceDetail(); @@ -264,7 +269,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { contentOnlyThreadKeys, olderSettledShelf, } = useThreadListV2({ - threads, + threads: launchingThreads, pendingTasks, environmentId: options.selectedEnvironmentId, projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs, diff --git a/apps/mobile/src/state/composer-attachment-uploads.test.ts b/apps/mobile/src/state/composer-attachment-uploads.test.ts index 1809acc559be..4a9c0d427276 100644 --- a/apps/mobile/src/state/composer-attachment-uploads.test.ts +++ b/apps/mobile/src/state/composer-attachment-uploads.test.ts @@ -170,6 +170,7 @@ vi.mock("./use-thread-outbox", async () => { dispatchingQueuedMessageIdAtom: Atom.make>({}).pipe(Atom.keepAlive), useThreadOutboxMessages: () => appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom), + retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), threadOutboxShellStatusesAtom: Atom.make(new Map()), }; }); diff --git a/apps/mobile/src/state/pending-new-tasks-model.test.ts b/apps/mobile/src/state/pending-new-tasks-model.test.ts index 6c039d7254c0..9e523972a63c 100644 --- a/apps/mobile/src/state/pending-new-tasks-model.test.ts +++ b/apps/mobile/src/state/pending-new-tasks-model.test.ts @@ -1,11 +1,20 @@ -import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { + CommandId, + EnvironmentId, + MessageId, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { + buildPendingNewTasks, type PendingDraftProjectDefaults, pendingDraftBranchNeedsRefs, resolvePendingDraftBranch, } from "./pending-new-tasks-model"; +import type { QueuedThreadMessage } from "./thread-outbox-model"; import type { ComposerDraft, ComposerDraftWorkspaceSelection } from "./use-composer-drafts"; const projectCwd = "/repo"; @@ -82,3 +91,55 @@ describe("resolvePendingDraftBranch", () => { expect(resolve({ draft: chosen, branches, projectCwd })).toBe("release"); }); }); + +function queuedCreation(environmentId: string): QueuedThreadMessage { + return { + environmentId: EnvironmentId.make(environmentId), + threadId: ThreadId.make(`thread-${environmentId}`), + messageId: MessageId.make(`message-${environmentId}`), + commandId: CommandId.make(`command-${environmentId}`), + text: "Test", + attachments: [], + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }, + creation: { + projectId: ProjectId.make("project-1"), + workspaceMode: "local", + branch: null, + worktreePath: null, + }, + createdAt: "2026-11-10T01:10:00.000Z", + }; +} + +describe("buildPendingNewTasks", () => { + it("lists only creations the outbox is not sending yet", () => { + const sending = EnvironmentId.make("sending"); + const syncing = EnvironmentId.make("syncing"); + const readOnly = EnvironmentId.make("read-only"); + const retrying = EnvironmentId.make("retrying"); + const { modelSelection: _model, ...modelless } = queuedCreation("sending"); + const tasks = buildPendingNewTasks({ + queuedMessages: [ + ...["sending", "syncing", "read-only", "retrying", "offline"].map(queuedCreation), + { ...modelless, messageId: MessageId.make("message-modelless") }, + ], + drafts: {}, + sendGate: { + connectedEnvironmentIds: new Set([sending, syncing, readOnly, retrying]), + operableEnvironmentIds: new Set([sending, syncing, retrying]), + shellStatuses: new Map([ + [sending, "live"], + [syncing, "synchronizing"], + [readOnly, "live"], + [retrying, "live"], + ]), + retryingMessageIds: { [MessageId.make("message-retrying")]: true }, + }, + }); + + expect(tasks).toHaveLength(5); + expect(new Set(tasks.map((task) => task.environmentId))).toEqual( + new Set(["syncing", "read-only", "retrying", "offline", "sending"]), + ); + }); +}); diff --git a/apps/mobile/src/state/pending-new-tasks-model.ts b/apps/mobile/src/state/pending-new-tasks-model.ts index ce8923ce62ee..d923009452c7 100644 --- a/apps/mobile/src/state/pending-new-tasks-model.ts +++ b/apps/mobile/src/state/pending-new-tasks-model.ts @@ -1,7 +1,13 @@ -import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId, MessageId, ProjectId } from "@t3tools/contracts"; import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn"; -import type { QueuedThreadCreation, QueuedThreadMessage } from "./thread-outbox-model"; +import { + isQueuedThreadCreationSendable, + resolveThreadOutboxDeliveryAction, + type QueuedThreadCreation, + type QueuedThreadMessage, +} from "./thread-outbox-model"; import { isNewTaskDraftKey } from "./new-task-draft-key"; import type { ComposerDraft } from "./use-composer-drafts"; import { resolveNewTaskDraftWorkspace } from "../features/threads/new-task-context-presentation"; @@ -85,13 +91,41 @@ export function resolvePendingDraftBranch(input: { }).branch; } +export interface ThreadOutboxSendGate { + readonly connectedEnvironmentIds: ReadonlySet; + readonly operableEnvironmentIds: ReadonlySet; + readonly shellStatuses: ReadonlyMap; + readonly retryingMessageIds: Readonly>>; +} + +/** The outbox drain's gate for a creation: sendable, connected, shell live, operate granted, not backing off. */ +export function isQueuedCreationSending( + message: QueuedThreadMessage, + gate: ThreadOutboxSendGate, +): boolean { + const environmentId = message.environmentId; + return ( + isQueuedThreadCreationSendable(message) && + gate.retryingMessageIds[message.messageId] !== true && + gate.operableEnvironmentIds.has(environmentId) && + resolveThreadOutboxDeliveryAction({ + isCreation: true, + threadExists: false, + shellStatus: gate.shellStatuses.get(environmentId) ?? "empty", + environmentConnected: gate.connectedEnvironmentIds.has(environmentId), + }) === "send" + ); +} + export function buildPendingNewTasks(input: { readonly queuedMessages: ReadonlyArray; readonly drafts: Readonly>; + readonly sendGate: ThreadOutboxSendGate; }): ReadonlyArray { const tasks: PendingNewTask[] = []; for (const message of input.queuedMessages) { - if (!message.creation) { + // Listing a creation already being sent would flash an "Unsent" row. + if (!message.creation || isQueuedCreationSending(message, input.sendGate)) { continue; } tasks.push({ diff --git a/apps/mobile/src/state/pending-thread-creation.test.ts b/apps/mobile/src/state/pending-thread-creation.test.ts index dd1515be1d22..5c76c09bd5ba 100644 --- a/apps/mobile/src/state/pending-thread-creation.test.ts +++ b/apps/mobile/src/state/pending-thread-creation.test.ts @@ -4,13 +4,17 @@ import { MessageId, ProjectId, ProviderInstanceId, + RunId, ThreadId, } from "@t3tools/contracts"; +import { isThreadWorking } from "@t3tools/client-runtime/state/thread-inbox"; import { describe, expect, it } from "vite-plus/test"; import { + pendingThreadCreationShell, resolvePendingThreadCreation, selectThreadCreationDetail, + withLaunchingThreads, type PendingThreadCreation, } from "./pending-thread-creation"; import type { QueuedThreadMessage } from "./thread-outbox-model"; @@ -186,3 +190,30 @@ describe("selectThreadCreationDetail", () => { ).toEqual({ pendingCreation: null, detailRef: threadRef }); }); }); + +describe("withLaunchingThreads", () => { + it("reads as working from Send until the thread's first run arrives", () => { + const launch = (threads: Parameters[0]["threads"]) => + withLaunchingThreads({ threads, launches: [creation], hiddenThreadKeys: new Set() }); + // Before the shell arrives, and after the server commits the thread without its run. + const created = { ...pendingThreadCreationShell(creation)!, title: "Server title" }; + for (const threads of [launch([]), launch([created])]) { + expect(threads).toHaveLength(1); + expect(isThreadWorking(threads[0]!)).toBe(true); + } + expect(launch([created])[0]!.title).toBe("Server title"); + + const started = { + ...created, + latestRun: { + runId: RunId.make("run-1"), + status: "completed" as const, + requestedAt: null, + startedAt: null, + completedAt: null, + assistantMessageId: null, + }, + }; + expect(launch([started])[0]).toBe(started); + }); +}); diff --git a/apps/mobile/src/state/pending-thread-creation.ts b/apps/mobile/src/state/pending-thread-creation.ts index 22684ba0c264..78c682ec7a2d 100644 --- a/apps/mobile/src/state/pending-thread-creation.ts +++ b/apps/mobile/src/state/pending-thread-creation.ts @@ -4,6 +4,8 @@ import { } from "@t3tools/client-runtime/state/shell"; import type { LocalThreadMessage } from "../lib/threadActivity"; import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE } from "@t3tools/contracts"; +import { threadKey } from "@t3tools/client-runtime/state/entities"; +import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { Atom } from "effect/reactivity"; import * as DateTime from "effect/DateTime"; @@ -133,6 +135,33 @@ export function pendingThreadCreationMessage(message: QueuedThreadMessage): Loca }; } +/** Launches show as preparing from Send, before the server's shell exists, until their first run. */ +export function withLaunchingThreads(input: { + readonly threads: ReadonlyArray; + readonly launches: ReadonlyArray; + readonly hiddenThreadKeys: ReadonlySet; +}): ReadonlyArray { + if (input.launches.length === 0) return input.threads; + const launchByKey = new Map(); + for (const message of input.launches) { + if (!message.creation || input.hiddenThreadKeys.has(threadKey(message))) continue; + launchByKey.set(scopedThreadKey(message.environmentId, message.threadId), message); + } + if (launchByKey.size === 0) return input.threads; + const threads = input.threads.map((thread) => { + const key = scopedThreadKey(thread.environmentId, thread.id); + const launch = launchByKey.get(key); + if (!launch) return thread; + launchByKey.delete(key); + return asLaunchingThread(thread); + }); + for (const launch of launchByKey.values()) { + const shell = pendingThreadCreationShell(launch); + if (shell) threads.push(asLaunchingThread(shell)); + } + return threads; +} + export function pendingThreadCreationShell( message: QueuedThreadMessage, ): EnvironmentThreadShell | null { diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts index 3222101bf927..8014e579197f 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts @@ -136,6 +136,7 @@ vi.mock("./use-thread-outbox", async () => { return { editingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), + retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), threadOutboxShellStatusesAtom: Atom.make(new Map([["secondary", "live"]])), }; }); diff --git a/apps/mobile/src/state/threadOutboxDelivery.test.ts b/apps/mobile/src/state/threadOutboxDelivery.test.ts index 3f9797cc91f9..f7d67f434939 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.test.ts @@ -120,6 +120,7 @@ vi.mock("./use-thread-outbox", async () => { return { editingQueuedMessageIdsAtom: Atom.make>({}).pipe(Atom.keepAlive), dispatchingQueuedMessageIdAtom: Atom.make(null).pipe(Atom.keepAlive), + retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive), threadOutboxShellStatusesAtom: Atom.make(new Map()), }; }); diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index 9b2da676eee4..19cd4ec3339e 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -87,6 +87,7 @@ import { import { dispatchingQueuedMessageIdAtom, editingQueuedMessageIdsAtom, + retryingQueuedMessageIdsAtom, threadOutboxShellStatusesAtom, } from "./use-thread-outbox"; import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error"; @@ -155,7 +156,20 @@ function logThreadOutboxUploadFailure(queuedMessage: QueuedThreadMessage, error: } } +function setQueuedMessageRetrying(queuedMessageId: MessageId, retrying: boolean): void { + const { [queuedMessageId]: current, ...others } = appAtomRegistry.get( + retryingQueuedMessageIdsAtom, + ); + if ((current === true) === retrying) return; + appAtomRegistry.set( + retryingQueuedMessageIdsAtom, + retrying ? { ...others, [queuedMessageId]: true } : others, + ); +} + function beginDispatchingQueuedMessage(queuedMessageId: MessageId): void { + // An attempt in flight is sending, even while its retry count is kept. + setQueuedMessageRetrying(queuedMessageId, false); appAtomRegistry.set(dispatchingQueuedMessageIdAtom, queuedMessageId); } @@ -701,6 +715,7 @@ export function createThreadOutboxDelivery(): { notBefore: Date.now() + delayMs, timer: setTimeout(drain, delayMs), }); + setQueuedMessageRetrying(messageId, true); }; const clearRetry = (messageId: MessageId): void => { @@ -708,6 +723,7 @@ export function createThreadOutboxDelivery(): { if (retry === undefined) return; clearTimeout(retry.timer); retries.delete(messageId); + setQueuedMessageRetrying(messageId, false); }; // A delivery that throws backs off like any failure. Releasing the slot @@ -1412,6 +1428,7 @@ export function createThreadOutboxDelivery(): { stopCollectingOutcomes(); for (const retry of retries.values()) clearTimeout(retry.timer); retries.clear(); + appAtomRegistry.set(retryingQueuedMessageIdsAtom, {}); for (const blocked of blockedRecoveries.values()) blocked.unsubscribe(); blockedRecoveries.clear(); for (const release of familyMounts.values()) release(); diff --git a/apps/mobile/src/state/use-pending-new-tasks.ts b/apps/mobile/src/state/use-pending-new-tasks.ts index 0d5e3f602e52..58fbf0508817 100644 --- a/apps/mobile/src/state/use-pending-new-tasks.ts +++ b/apps/mobile/src/state/use-pending-new-tasks.ts @@ -1,10 +1,26 @@ import { useAtomValue } from "@effect/atom-react"; +import { AuthOrchestrationOperateScope } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; +import { useMemo } from "react"; import { threadKey } from "@t3tools/client-runtime/state/entities"; -import { buildPendingNewTasks, type PendingNewTask } from "./pending-new-tasks-model"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { + buildPendingNewTasks, + isQueuedCreationSending, + type PendingNewTask, + type ThreadOutboxSendGate, +} from "./pending-new-tasks-model"; +import { pendingThreadCreationOutcomesAtom, withLaunchingThreads } from "./pending-thread-creation"; import { flattenQueuedThreadMessages } from "./thread-outbox-model"; import { environmentThreadShells } from "./threads"; import { newTaskComposerDraftsAtom } from "./use-composer-drafts"; -import { useThreadOutboxMessages } from "./use-thread-outbox"; +import { + retryingQueuedMessageIdsAtom, + threadOutboxShellStatusesAtom, + useThreadOutboxMessages, +} from "./use-thread-outbox"; +import { environmentSession, sessionHasScope } from "./session"; +import { workspaceConnections } from "./workspace"; export type { PendingDraftTask, @@ -12,13 +28,58 @@ export type { PendingQueuedTask, } from "./pending-new-tasks-model"; +const threadOutboxSendGateAtom = Atom.make((get): ThreadOutboxSendGate => { + const connected = get(workspaceConnections.environmentsAtom).flatMap((environment) => + environment.connectionState === "connected" ? [environment.environmentId] : [], + ); + return { + connectedEnvironmentIds: new Set(connected), + operableEnvironmentIds: new Set( + connected.filter((environmentId) => + sessionHasScope( + get(environmentSession.sessionStateAtom(environmentId)), + AuthOrchestrationOperateScope, + ), + ), + ), + shellStatuses: get(threadOutboxShellStatusesAtom), + retryingMessageIds: get(retryingQueuedMessageIdsAtom), + }; +}).pipe(Atom.withLabel("mobile:pending-new-tasks:send-gate")); + export function usePendingNewTasks(): ReadonlyArray { const queuedMessagesByThreadKey = useThreadOutboxMessages(); const drafts = useAtomValue(newTaskComposerDraftsAtom); const hiddenKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + const sendGate = useAtomValue(threadOutboxSendGateAtom); // A delivered creation can stay queued after its thread is live and hidden. const queuedMessages = flattenQueuedThreadMessages(queuedMessagesByThreadKey).filter( (message) => !hiddenKeys.has(threadKey(message)), ); - return buildPendingNewTasks({ queuedMessages, drafts }); + return buildPendingNewTasks({ + queuedMessages, + drafts, + sendGate, + }); +} + +/** The list's threads, with creations the outbox is sending placed as working. */ +export function useLaunchingThreads( + threads: ReadonlyArray, +): ReadonlyArray { + const queuedMessagesByThreadKey = useThreadOutboxMessages(); + const outcomes = useAtomValue(pendingThreadCreationOutcomesAtom); + const hiddenThreadKeys = useAtomValue(environmentThreadShells.hiddenThreadKeysAtom); + const sendGate = useAtomValue(threadOutboxSendGateAtom); + return useMemo(() => { + const launches = [ + ...flattenQueuedThreadMessages(queuedMessagesByThreadKey).filter((message) => + isQueuedCreationSending(message, sendGate), + ), + ...Object.values(outcomes).flatMap((outcome) => + outcome.kind === "delivered" ? [outcome.message] : [], + ), + ]; + return withLaunchingThreads({ threads, launches, hiddenThreadKeys }); + }, [threads, queuedMessagesByThreadKey, outcomes, hiddenThreadKeys, sendGate]); } diff --git a/apps/mobile/src/state/use-thread-outbox.ts b/apps/mobile/src/state/use-thread-outbox.ts index caffa99f8cfa..bc1f3ea149e1 100644 --- a/apps/mobile/src/state/use-thread-outbox.ts +++ b/apps/mobile/src/state/use-thread-outbox.ts @@ -31,6 +31,11 @@ export const dispatchingQueuedMessageIdAtom = Atom.make(null). Atom.withLabel("mobile:thread-outbox:dispatching-message-id"), ); +/** Messages waiting out a retry backoff, which can repeat for as long as the failure lasts. */ +export const retryingQueuedMessageIdsAtom = Atom.make>>>( + {}, +).pipe(Atom.keepAlive, Atom.withLabel("mobile:thread-outbox:retrying-message-ids")); + export function holdEditingQueuedMessage(messageId: MessageId): void { const current = appAtomRegistry.get(editingQueuedMessageIdsAtom); if (current[messageId]) { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 661b50a00b24..fb9e5d1da230 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -30,6 +30,7 @@ import { threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; import { + asLaunchingThread, createInboxReturnTracker, isThreadWorking, } from "@t3tools/client-runtime/state/thread-inbox"; @@ -248,7 +249,12 @@ import { SidebarContent, SidebarGroup, useSidebar } from "./ui/sidebar"; import { SidebarChromeFooter, SidebarChromeHeader } from "./sidebar/SidebarChrome"; import { SidebarHeaderIconButton, SidebarThreadHeader } from "./sidebar/SidebarThreadHeader"; import { TooltipProvider } from "./ui/tooltip"; -import { composerDraftHasUserContent, DraftId, useComposerDraftStore } from "../composerDraftStore"; +import { + composerDraftHasUserContent, + DraftId, + useComposerDraftStore, + usePromotingDraftThreadKeys, +} from "../composerDraftStore"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { SidebarSearchResultRow, @@ -1095,6 +1101,15 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), ); const threads = useQuietThreadShells(); + const promotingDraftThreadKeys = usePromotingDraftThreadKeys(); + const listedThreads = + promotingDraftThreadKeys.length === 0 + ? threads + : threads.map((thread) => + promotingDraftThreadKeys.includes(threadShellKey(thread)) + ? asLaunchingThread(thread) + : thread, + ); const routeRowThreadKey = routeThreadRef === null ? null @@ -1326,7 +1341,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve serverConfigs, connectedEnvironmentIds, optimisticDrop, - threads, + threads: listedThreads, delegatedUnderParent, routeRowThreadKey, folderGroups: boringSidebarEnabled diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 3a50e76d06bd..05e898420047 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1,4 +1,5 @@ import { useAtomMount } from "@effect/atom-react"; +import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; @@ -477,9 +478,16 @@ export function SortableThreadRow( }; // The sidebar arranges rows from quiet shells, which hold still while a // thread streams; reading the live shell here re-renders only this row. + const liveThread = useThreadShell( + scopeThreadRef(rowProps.thread.environmentId, rowProps.thread.id), + ); + // A runtime on the arranged copy but not the run-less live shell is the list's launch overlay. const thread = - useThreadShell(scopeThreadRef(rowProps.thread.environmentId, rowProps.thread.id)) ?? - rowProps.thread; + liveThread === null + ? rowProps.thread + : rowProps.thread.runtime !== null + ? asLaunchingThread(liveThread) + : liveThread; // Keyed by variant so a card/slim switch remounts the row. return ; } diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 04715866949a..dde304da3d03 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -4439,6 +4439,17 @@ export function useComposerDraftModelState( ); } +/** Threads a sent draft is launching into: from their shell's arrival until the server owns the send. */ +export function usePromotingDraftThreadKeys(): ReadonlyArray { + return useComposerDraftStore( + useShallow((state) => + Object.values(state.draftThreadsByThreadKey).flatMap((draft) => + draft.promotedTo ? [scopedThreadKey(draft.promotedTo)] : [], + ), + ), + ); +} + export function markPromotedDraftThreadByRef(threadRef: ScopedThreadRef): void { const draftStore = useComposerDraftStore.getState(); for (const [draftId, draftThread] of Object.entries(draftStore.draftThreadsByThreadKey)) { diff --git a/packages/client-runtime/src/state/threadInbox.ts b/packages/client-runtime/src/state/threadInbox.ts index 2669416db42f..d3de3b0bc4c2 100644 --- a/packages/client-runtime/src/state/threadInbox.ts +++ b/packages/client-runtime/src/state/threadInbox.ts @@ -30,6 +30,25 @@ export function isThreadWorking(thread: WorkingThreadInput): boolean { return !(thread.interactionMode === "plan" && thread.hasActionableProposedPlan && runSettled); } +/** + * A thread its own client is launching reads as preparing until its first run lands. + * The server commits the thread before its run, so the list would otherwise place it twice. + */ +export function asLaunchingThread(thread: T): T { + if (thread.latestRun !== null || thread.runtime !== null) return thread; + return { + ...thread, + runtime: { + status: "preparing", + activeRunId: null, + providerInstanceId: thread.providerInstanceId, + providerName: null, + lastError: null, + updatedAt: thread.updatedAt, + }, + }; +} + type InboxThreadInput = Pick< EnvironmentThreadShell, "id" | "environmentId" | "createdAt" | "unsettledAt" | "latestRun" From c82e1ba515c88922306a92a42c5ff1b0f686205f Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Wed, 11 Nov 2026 06:51:09 +0100 Subject: [PATCH 012/436] fix(gitlab): review comments can cover a range of lines (#30535) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../src/server/GitLabPullRequestCli.test.ts | 47 ++++- .../src/server/GitLabPullRequestCli.ts | 166 +++++++++++++++--- .../src/server/GitLabPullRequestProvider.ts | 1 + 3 files changed, 189 insertions(+), 25 deletions(-) diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index f7e2422a6bc9..8c481399d78e 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -1383,6 +1383,21 @@ layer("GitLabPullRequestCli.layer", (it) => { ), ), ); + // Line 12 is added after a removed line, so GitLab's old counter there is 11, not 0. + mockedExecute.mockReturnValueOnce( + Effect.succeed( + output( + JSON.stringify([ + { + old_path: "src/a.ts", + new_path: "src/b.ts", + renamed_file: true, + diff: "@@ -8,4 +9,4 @@\n a\n b\n-c\n+d\n+e\n f\n-g\n", + }, + ]), + ), + ), + ); mockedExecute.mockReturnValue(Effect.succeed(output("{}"))); const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; @@ -1399,12 +1414,26 @@ layer("GitLabPullRequestCli.layer", (it) => { position: { kind: "deleted", oldLine: 4 }, body: "why remove?", }, + { + path: "src/b.ts", + oldPath: "src/a.ts", + startPosition: { kind: "context", oldLine: 9, newLine: 10, side: "right" }, + position: { kind: "added", newLine: 12 }, + body: "this block", + }, + { + path: "src/b.ts", + startPosition: { kind: "added", newLine: 12 }, + position: { kind: "added", newLine: 12 }, + body: "one line", + }, ], }); expect(argsOfCall(0)[1]).toContain("merge_requests/7"); - expect(argsOfCall(1)[1]).toContain("/discussions"); - expect(JSON.parse(callAt(1).stdin ?? "")).toEqual({ + expect(argsOfCall(1)[1]).toContain("merge_requests/7/diffs"); + expect(argsOfCall(2)[1]).toContain("/discussions"); + expect(JSON.parse(callAt(2).stdin ?? "")).toEqual({ body: "why remove?", position: { base_sha: "base", @@ -1416,8 +1445,18 @@ layer("GitLabPullRequestCli.layer", (it) => { old_line: 4, }, }); - expect(argsOfCall(2)[1]).toContain("/notes"); - expect(argsOfCall(3)[1]).toContain("/approve"); + // sha1("src/b.ts") + const fileHash = "e55a8d6c5dd26e72538fd71fb7695dd829c8dab5"; + expect(JSON.parse(callAt(3).stdin ?? "").position).toMatchObject({ + new_line: 12, + line_range: { + start: { line_code: `${fileHash}_9_10`, type: null, old_line: 9, new_line: 10 }, + end: { line_code: `${fileHash}_11_12`, type: "new", new_line: 12 }, + }, + }); + expect(JSON.parse(callAt(4).stdin ?? "").position).not.toHaveProperty("line_range"); + expect(argsOfCall(5)[1]).toContain("/notes"); + expect(argsOfCall(6)[1]).toContain("/approve"); }), ); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index b178218cf16f..c0bb3d5a8e1e 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -1,6 +1,7 @@ import { removeAgentCredits } from "@t3tools/source-control-core/server/mergeMessage"; import { isCommitSha } from "@t3tools/source-control-core/server/pullRequestUtils"; import * as Context from "effect/Context"; +import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -8,6 +9,7 @@ import * as Option from "effect/Option"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { resolvePullRequestAuthorFilter, VcsProcessExitError } from "@t3tools/contracts"; +import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import type { PullRequestAction, PullRequestActor, @@ -662,6 +664,90 @@ function gitLabReviewPositionLines( } } +function gitLabDiffHeader(oldPath: string, newPath: string): string { + return `diff --git ${quoteGitPatchPath(`a/${oldPath}`)} ${quoteGitPatchPath(`b/${newPath}`)}\n`; +} + +/** + * The old and new line counters GitLab's diff parser holds at a changed line. An added line + * keeps the old counter where it stands, and a removed line the new one, so neither side of a + * changed line's `line_code` is known without walking its hunk. + */ +function gitLabLineCounters( + patch: string, + header: string, + position: PullRequestReviewPosition, +): { readonly old: number; readonly new: number } | undefined { + if (position.kind === "context") return { old: position.oldLine, new: position.newLine }; + const start = `\n${patch}`.indexOf(`\n${header}`); + if (start === -1) return undefined; + const end = patch.indexOf("\ndiff --git ", start + header.length - 1); + const section = patch.slice(start, end === -1 ? undefined : end); + const firstHunk = section.indexOf("\n@@ "); + if (firstHunk === -1) return undefined; + let oldLine = 0; + let newLine = 0; + for (const line of section.slice(firstHunk + 1).split("\n")) { + const hunk = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(line); + if (hunk) { + oldLine = Number(hunk[1]); + newLine = Number(hunk[2]); + } else if (line.startsWith("+")) { + if (position.kind === "added" && newLine === position.newLine) { + return { old: oldLine, new: newLine }; + } + newLine += 1; + } else if (line.startsWith("-")) { + if (position.kind === "deleted" && oldLine === position.oldLine) { + return { old: oldLine, new: newLine }; + } + oldLine += 1; + } else if (line.startsWith(" ")) { + oldLine += 1; + newLine += 1; + } + } + return undefined; +} + +/** + * One end of a ranged comment. GitLab labels the range from `old_line`/`new_line` and `type`, + * the way its own UI sends them (`type` is null on a context line), and finds the lines to + * highlight by `line_code`, which needs both counters from the diff. + */ +function gitLabLineRangeEnd( + fileHash: string, + position: PullRequestReviewPosition, + counters: { readonly old: number; readonly new: number } | undefined, +) { + const lines = gitLabReviewPositionLines(position); + const oldLine = counters?.old ?? ("old_line" in lines ? lines.old_line : 0); + const newLine = counters?.new ?? ("new_line" in lines ? lines.new_line : 0); + return { + line_code: `${fileHash}_${oldLine}_${newLine}`, + type: position.kind === "added" ? "new" : position.kind === "deleted" ? "old" : null, + ...lines, + }; +} + +const gitLabLineRange = Effect.fn("GitLabPullRequestCli.lineRange")(function* ( + patch: string, + comment: PullRequestReviewCommentDraft, +) { + const start = comment.startPosition; + if (start === undefined) return {}; + const digest = yield* Digest.Digest; + const fileHash = yield* digest.digestHex(Digest.sha1, new TextEncoder().encode(comment.path)); + const header = gitLabDiffHeader(comment.oldPath ?? comment.path, comment.path); + const first = gitLabLineRangeEnd(fileHash, start, gitLabLineCounters(patch, header, start)); + const last = gitLabLineRangeEnd( + fileHash, + comment.position, + gitLabLineCounters(patch, header, comment.position), + ); + return first.line_code === last.line_code ? {} : { line_range: { start: first, end: last } }; +}, Effect.provide(Digest.layerWebCrypto)); + function stateParam(state: PullRequestListState): string { return state === "open" ? "opened" : state; } @@ -1128,6 +1214,28 @@ export const make = Effect.gen(function* () { }), ); + /** Reads diff pages only until every header is found, for the files ranged comments sit on. */ + const patchCovering = ( + input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly repository: string; + readonly number: number; + }, + headers: ReadonlyArray, + page: number, + collected: string, + ): Effect.Effect => + headers.every((header) => `\n${collected}`.includes(`\n${header}`)) + ? Effect.succeed(collected) + : diffPage({ ...input, page }).pipe( + Effect.flatMap((slice) => + slice.nextCursor === null + ? Effect.succeed(collected + slice.patch) + : patchCovering(input, headers, page + 1, collected + slice.patch), + ), + ); + const notesPage = (input: { readonly cwd: string; readonly host?: string | undefined; @@ -2575,30 +2683,46 @@ export const make = Effect.gen(function* () { } if (input.comments.length > 0) { const refs = yield* getDiffRefs(input); + const rangedFileHeaders = input.comments.flatMap((comment) => + comment.startPosition !== undefined && + (comment.startPosition.kind !== "context" || comment.position.kind !== "context") + ? [gitLabDiffHeader(comment.oldPath ?? comment.path, comment.path)] + : [], + ); + // Line codes only steer GitLab's highlight of a range, so an unreadable diff falls back + // to codes without the other side's counter rather than blocking the review. + const patch = yield* patchCovering(input, rangedFileHeaders, 1, "").pipe( + Effect.orElseSucceed(() => ""), + ); yield* Effect.forEach( input.comments, (comment) => - api({ - cwd: input.cwd, - host: input.host, - path: `${mergeRequest}/discussions`, - method: "POST", - stdin: JSON.stringify({ - body: comment.body, - position: { - base_sha: refs.baseSha, - head_sha: refs.headSha, - start_sha: refs.startSha, - position_type: "text", - // Both paths are sent because GitLab resolves a position against both - // sides of the diff. They differ only for a renamed file, which is why the - // draft carries the name the file had before the change. - old_path: comment.oldPath ?? comment.path, - new_path: comment.path, - ...gitLabReviewPositionLines(comment.position), - }, - }), - }), + gitLabLineRange(patch, comment).pipe( + Effect.flatMap((lineRange) => + api({ + cwd: input.cwd, + host: input.host, + path: `${mergeRequest}/discussions`, + method: "POST", + stdin: JSON.stringify({ + body: comment.body, + position: { + base_sha: refs.baseSha, + head_sha: refs.headSha, + start_sha: refs.startSha, + position_type: "text", + // Both paths are sent because GitLab resolves a position against both + // sides of the diff. They differ only for a renamed file, which is why the + // draft carries the name the file had before the change. + old_path: comment.oldPath ?? comment.path, + new_path: comment.path, + ...gitLabReviewPositionLines(comment.position), + ...lineRange, + }, + }), + }), + ), + ), { discard: true }, ); } diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index 7a79f437ad68..b4a6cfff6e9c 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -38,6 +38,7 @@ const CAPABILITIES: PullRequestCapabilities = { viewedFiles: "environment", review: { inlineComment: true, + rangeComment: true, reply: true, resolve: true, verdicts: ["comment", "approve", "request-changes"], From 42185a6206245c1cde5368e8ce368b384e7a400a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:11:31 -0800 Subject: [PATCH 013/436] test(web): right panel tab swipe test runs as macOS on any CI host (#34191) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/RightPanelTabs.browser.test.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index eea63a9c85a6..4a7617bb1abd 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -64,6 +64,7 @@ describe("RightPanelTabs", () => { navigateHistory.mockReset(); const { bridge, scroll } = trackpad(); using _bridge = stubGlobal("desktopBridge", bridge); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); const panel = document.createElement("div"); panel.style.cssText = "width: 320px; height: 200px; display: flex"; const noop = () => {}; From 1c17285e58350e6df91b0de805dc4030ced9c6c6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:14:46 -0800 Subject: [PATCH 014/436] fix(shared): cite assistant messages with IDs over 512 characters (#28084) Co-authored-by: Claude Opus 5.5 --- packages/contracts/src/assistantCitations.ts | 8 +++++--- packages/shared/src/assistantCitations.test.ts | 7 ++++--- packages/shared/src/assistantCitations.ts | 11 +++++++++-- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/contracts/src/assistantCitations.ts b/packages/contracts/src/assistantCitations.ts index 71934d1684ab..96572a4bfa65 100644 --- a/packages/contracts/src/assistantCitations.ts +++ b/packages/contracts/src/assistantCitations.ts @@ -4,13 +4,15 @@ import { EnvironmentId, MessageId, NonNegativeInt, ThreadId } from "./baseSchema export const ASSISTANT_CITATION_MAX_TEXT_LENGTH = 8_000; export const ASSISTANT_CITATION_MAX_COMMENT_LENGTH = 8_000; export const ASSISTANT_CITATION_CONTEXT_LENGTH = 32; +// Provider message IDs nest and re-encode their thread and turn IDs, so they outgrow a few hundred characters. +export const ASSISTANT_CITATION_MAX_ID_LENGTH = 4_096; /** Positions are UTF-16 offsets, not Markdown offsets. */ export const AssistantCitation = Schema.Struct({ version: Schema.Literal(1), - environmentId: EnvironmentId.check(Schema.isMaxLength(512)), - threadId: ThreadId.check(Schema.isMaxLength(512)), - messageId: MessageId.check(Schema.isMaxLength(512)), + environmentId: EnvironmentId.check(Schema.isMaxLength(ASSISTANT_CITATION_MAX_ID_LENGTH)), + threadId: ThreadId.check(Schema.isMaxLength(ASSISTANT_CITATION_MAX_ID_LENGTH)), + messageId: MessageId.check(Schema.isMaxLength(ASSISTANT_CITATION_MAX_ID_LENGTH)), text: Schema.String.check( Schema.isNonEmpty(), Schema.isMaxLength(ASSISTANT_CITATION_MAX_TEXT_LENGTH), diff --git a/packages/shared/src/assistantCitations.test.ts b/packages/shared/src/assistantCitations.test.ts index 7300de72e9d1..7dbaaf9d8bde 100644 --- a/packages/shared/src/assistantCitations.test.ts +++ b/packages/shared/src/assistantCitations.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test"; import { ASSISTANT_CITATION_CONTEXT_LENGTH, ASSISTANT_CITATION_MAX_COMMENT_LENGTH, + ASSISTANT_CITATION_MAX_ID_LENGTH, ASSISTANT_CITATION_MAX_TEXT_LENGTH, EnvironmentId, MessageId, @@ -126,9 +127,9 @@ describe("assistant citation references", () => { it("accepts complete 8k CJK quotes and comments with maximum-sized source selectors", () => { const largeCitation: AssistantCitation = { ...citation, - environmentId: EnvironmentId.make("環".repeat(512)), - threadId: ThreadId.make("線".repeat(512)), - messageId: MessageId.make("文".repeat(512)), + environmentId: EnvironmentId.make("環".repeat(ASSISTANT_CITATION_MAX_ID_LENGTH)), + threadId: ThreadId.make("線".repeat(ASSISTANT_CITATION_MAX_ID_LENGTH)), + messageId: MessageId.make("文".repeat(ASSISTANT_CITATION_MAX_ID_LENGTH)), text: "引".repeat(ASSISTANT_CITATION_MAX_TEXT_LENGTH), comment: "注".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH), start: Number.MAX_SAFE_INTEGER - ASSISTANT_CITATION_MAX_TEXT_LENGTH, diff --git a/packages/shared/src/assistantCitations.ts b/packages/shared/src/assistantCitations.ts index 64bb2b3904ba..bb072e462a45 100644 --- a/packages/shared/src/assistantCitations.ts +++ b/packages/shared/src/assistantCitations.ts @@ -1,5 +1,7 @@ import { + ASSISTANT_CITATION_CONTEXT_LENGTH, ASSISTANT_CITATION_MAX_COMMENT_LENGTH, + ASSISTANT_CITATION_MAX_ID_LENGTH, ASSISTANT_CITATION_MAX_TEXT_LENGTH, AssistantCitation, } from "@t3tools/contracts"; @@ -8,9 +10,14 @@ import * as Schema from "effect/Schema"; const CITATION_PROTOCOL = "t3-citation:"; const CITATION_HREF_PREFIX = `${CITATION_PROTOCOL}//v1/`; -// Percent encoding needs up to nine characters per UTF-16 code unit; 16k covers selectors. +// Percent encoding needs up to nine characters per UTF-16 code unit; 1k covers keys and offsets. const MAX_CITATION_HREF_LENGTH = - 9 * (ASSISTANT_CITATION_MAX_TEXT_LENGTH + ASSISTANT_CITATION_MAX_COMMENT_LENGTH) + 16_000; + 9 * + (ASSISTANT_CITATION_MAX_TEXT_LENGTH + + ASSISTANT_CITATION_MAX_COMMENT_LENGTH + + 3 * ASSISTANT_CITATION_MAX_ID_LENGTH + + 2 * ASSISTANT_CITATION_CONTEXT_LENGTH) + + 1_000; const CITATION_LINK = new RegExp( String.raw`\[Assistant quote\]\((${CITATION_HREF_PREFIX}[^\s)]{1,${MAX_CITATION_HREF_LENGTH - CITATION_HREF_PREFIX.length}})\)`, "g", From 034f3ba918c986da6abe9cdb4dc9715b7150dc1a Mon Sep 17 00:00:00 2001 From: Bin Jamshid Date: Wed, 11 Nov 2026 10:14:50 +0400 Subject: [PATCH 015/436] fix(server): updates copy the database while the server still runs when it cannot be cloned (#33058) Co-authored-by: Ajraba04 <143622128+Ajraba04@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/serviceLauncher.test.ts | 122 +++++++++++++++++++++++- apps/server/src/serviceLauncher.ts | 97 ++++++++++++++++++- 2 files changed, 216 insertions(+), 3 deletions(-) diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 274b86573ed3..0006d371cf2c 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -2,6 +2,7 @@ import type * as NodeChildProcess from "node:child_process"; // @effect-diagnostics-next-line nodeBuiltinImport:off - the free-space probe is a plain Promise callback. import * as NodeFS from "node:fs"; +import * as NodeSqlite from "node:sqlite"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -464,6 +465,125 @@ if (context.update?.status === "pending") { }), ); + it.effect.each(["wal", "delete"] as const)( + "backs up a %s-mode database (online when WAL) and restores its final state", + (journalMode) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-online-" }); + const statePath = path.join(root, "runtime", "service-state.json"); + const databasePath = path.join(root, "userdata", "state.sqlite"); + const observationsPath = path.join(root, "observations.json"); + yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true }); + // SQLite keeps -wal beside the symlink's target, so the backup must restore it there. + yield* fs.symlink("actual.sqlite", databasePath); + const seed = new NodeSqlite.DatabaseSync(databasePath); + seed.exec(` + PRAGMA journal_mode = ${journalMode}; + CREATE TABLE events (id INTEGER PRIMARY KEY, payload TEXT NOT NULL); + WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 500) + INSERT INTO events (payload) SELECT 'before the update ' || i FROM n; + `); + seed.close(); + + const encoded = JSON.stringify({ root, databasePath, observationsPath, journalMode }); + const childSource = ` +import { readdirSync, writeFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +const paths = ${encoded}; +const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT); +if (context.update?.status === "pending") { + writeFileSync(paths.observationsPath + ".trial", JSON.stringify( + readdirSync(paths.root + "/runtime/db-backup/" + context.update.id).sort(), + )); + const trial = new DatabaseSync(context.update.dbPath); + trial.exec("PRAGMA journal_mode = " + paths.journalMode + "; INSERT INTO events (payload) VALUES ('trial');"); + trial.close(); + process.exit(1); +} else if (context.update === undefined) { + const db = new DatabaseSync(paths.databasePath); + db.exec("PRAGMA busy_timeout = 5000;"); + db.exec("PRAGMA journal_mode = " + paths.journalMode + ";"); + const insert = db.prepare("INSERT INTO events (payload) VALUES (?)"); + const writer = setInterval(() => insert.run("written while serving"), 1); + process.once("SIGTERM", () => { + clearInterval(writer); + insert.run("last write before stopping"); + const backupRoot = paths.root + "/runtime/db-backup"; + writeFileSync(paths.observationsPath, JSON.stringify({ + backupsAtStop: readdirSync(backupRoot).map((entry) => readdirSync(backupRoot + "/" + entry)), + rows: db.prepare("SELECT count(*) AS n FROM events").get().n, + })); + db.close(); + process.exit(0); + }); + process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }); +} else { + process.exit(0); +} +`; + for (const version of ["1.0.0", "1.1.0"]) { + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", version), + childSource, + ); + } + yield* Effect.promise(() => + writeServiceState(statePath, { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.0.0", + }), + ); + + const launcher = new Launcher( + root, + yield* Effect.promise(() => readServiceState(statePath)), + { + backupSpaceProbe: { canClone: async () => false }, + }, + ); + yield* Effect.promise(() => + launcher.run().then( + () => Promise.reject(new Error("launcher unexpectedly completed")), + () => Promise.resolve(), + ), + ); + + const state = yield* Effect.promise(() => readServiceState(statePath)); + assert.equal(state.update?.status, "rolled-back"); + const observed = JSON.parse(yield* fs.readFileString(observationsPath)); + // A WAL database's main file is copied before the server is asked to stop; others fall back offline. + assert.deepEqual(observed.backupsAtStop, journalMode === "wal" ? [["database"]] : []); + assert.isAbove(observed.rows, 501); + // Only the online copy holds no -shm: the offline fallback copies the one the server left. + assert.deepEqual( + JSON.parse(yield* fs.readFileString(`${observationsPath}.trial`)), + journalMode === "wal" ? ["database", "database-wal"] : ["database"], + ); + const restored = new NodeSqlite.DatabaseSync(databasePath); + try { + assert.equal(restored.prepare("PRAGMA integrity_check").get()?.integrity_check, "ok"); + assert.equal( + restored.prepare("SELECT count(*) AS n FROM events").get()?.n, + observed.rows, + ); + assert.equal( + restored + .prepare( + "SELECT count(*) AS n FROM events WHERE payload = 'last write before stopping'", + ) + .get()?.n, + 1, + ); + } finally { + restored.close(); + } + }), + ); + const requestRejectedUpdate = (backupSpaceProbe: Partial) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -670,7 +790,7 @@ setInterval(() => {}, 1_000); assert.include((yield* check(0.5 * 1024 ** 3, true)) ?? "", "1.0 GB needed, 0.5 GB free"); const blocker = yield* check(8 * 1024 ** 3, false); assert.include(blocker ?? "", "Not enough free disk space"); - assert.include(blocker ?? "", "10.5 GB needed, 8.0 GB free"); + assert.include(blocker ?? "", "10.8 GB needed, 8.0 GB free"); assert.include(blocker ?? "", "The server was not stopped"); }), ); diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index ee05c6329784..b46083cccbcd 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -162,6 +162,8 @@ const GIB = 1024 ** 3; // Cloned backups still need headroom for trial writes and migrations to diverge. const CLONED_BACKUP_MIN_HEADROOM_BYTES = GIB; const CLONED_BACKUP_HEADROOM_FRACTION = 0.1; +// While the online backup holds its snapshot, the live WAL and its copy can each reach the server's 128 MiB gate. +const ONLINE_BACKUP_WAL_HEADROOM_BYTES = 2 * 128 * 1024 ** 2; async function statDatabaseFiles(dbPath: string): Promise> { const stats: Array = []; @@ -242,7 +244,7 @@ export async function databaseBackupBlocker( await removeAbandonedBackupCopies(backupRoot); const [files, free] = await Promise.all([statDatabaseFiles(dbPath), readFreeBytes(backupRoot)]); const size = files.reduce((total, file) => total + file.size, 0); - const fullCopyBytes = size * 1.05; + const fullCopyBytes = size * 1.05 + ONLINE_BACKUP_WAL_HEADROOM_BYTES; if (free >= fullCopyBytes) return undefined; const clonedBytes = Math.max( CLONED_BACKUP_MIN_HEADROOM_BYTES, @@ -254,6 +256,83 @@ export async function databaseBackupBlocker( return `Not enough free disk space to back up the database before updating: ${gb(needed)} GB needed, ${gb(free)} GB free. Free up disk space and try again. The server was not stopped.`; } +// A child-process copy: closing any descriptor this process opens on the database drops the snapshot's POSIX locks. +async function copyWithoutOpening(source: string, destination: string): Promise { + // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. + if (process.platform === "win32") return NodeFSP.copyFile(source, destination); + if (!(await runCp([source, destination]))) throw new Error(`cp ${source} failed.`); +} + +// Copies the main file while the server runs; an open read transaction stops SQLite resetting the WAL, +// which `finish` copies after the stop and which overrides any page the copy caught mid-checkpoint. +// `-shm` is left out: its backfill count would make SQLite trust those pages. Past the WAL size gate, +// a write-heavy server's new writes wait, uncommitted, until the server stops. +async function startOnlineDatabaseBackup( + baseDir: string, + pending: PendingServiceUpdate, + probe: Partial = {}, +): Promise<(() => Promise) | undefined> { + const backupDir = databaseBackupDir(baseDir, pending.id); + if (await pathExists(backupDir)) return undefined; + const { canClone } = { ...filesystemBackupSpaceProbe, ...probe }; + if (await canClone(pending.dbPath, NodePath.dirname(backupDir)).catch(() => true)) + return undefined; + const NodeSqlite = await import("node:sqlite").catch(() => undefined); + if (NodeSqlite === undefined) return undefined; + + const stagingDir = `${backupDir}.staging`; + const discardStaging = () => + NodeFSP.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined); + const fallBack = async (cause: unknown) => { + await discardStaging(); + process.stderr.write( + `[service-launcher] Copying the database while the server runs failed; backing it up offline: ${cause instanceof Error ? cause.message : String(cause)}\n`, + ); + return undefined; + }; + let snapshot: InstanceType | undefined; + // SQLite keeps -wal beside the resolved file, not beside a symlink to it. + let dbPath = pending.dbPath; + const release = () => { + try { + snapshot?.close(); + } catch {} + snapshot = undefined; + }; + try { + await discardStaging(); + await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 }); + dbPath = await NodeFSP.realpath(pending.dbPath); + snapshot = new NodeSqlite.DatabaseSync(dbPath, { readOnly: true }); + const mode = String(snapshot.prepare("PRAGMA journal_mode").get()?.journal_mode); + if (mode.toLowerCase() !== "wal") throw new Error(`journal_mode is ${mode}, not wal.`); + snapshot.exec("BEGIN"); + snapshot.prepare("SELECT count(*) FROM sqlite_schema").get(); + const mainCopy = databaseBackupFile(stagingDir, ""); + await copyWithoutOpening(dbPath, mainCopy); + await syncFile(mainCopy); + } catch (cause) { + release(); + return fallBack(cause); + } + return async () => { + try { + const wal = `${dbPath}-wal`; + if (!(await pathExists(wal))) + throw new Error("the WAL disappeared while the snapshot was open."); + const walCopy = databaseBackupFile(stagingDir, "-wal"); + await copyWithoutOpening(wal, walCopy); + await syncFile(walCopy); + release(); + await NodeFSP.rename(stagingDir, backupDir); + await syncDirectory(NodePath.dirname(backupDir)); + } catch (cause) { + release(); + await fallBack(cause); + } + }; +} + // Preserve completed backups; restarted trials may already have changed the live database. async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate): Promise { const backupDir = databaseBackupDir(baseDir, pending.id); @@ -330,8 +409,13 @@ async function restoreDatabaseBackup( await markDatabaseRestorePending(backupDir); const directories = new Set([NodePath.dirname(pending.dbPath)]); + // SQLite keeps -wal and -shm beside the resolved database file, not beside a symlink to it. + const mainTarget = await restoreTarget(pending.dbPath); for (const suffix of DB_FILE_SUFFIXES) { - const livePath = `${pending.dbPath}${suffix}`; + const livePath = suffix === "" ? pending.dbPath : `${mainTarget}${suffix}`; + if (livePath !== `${pending.dbPath}${suffix}`) { + await NodeFSP.rm(`${pending.dbPath}${suffix}`, { force: true }); + } const source = databaseBackupFile(backupDir, suffix); if (await pathExists(source)) { // Restore into the symlink target; cloning would replace the link. @@ -708,8 +792,17 @@ export class Launcher { return; } this.#timer = undefined; + // Anything thrown outside its own fallback still leaves the offline backup to run. + const finishOnlineBackup = await startOnlineDatabaseBackup( + this.#baseDir, + pending, + this.#backupSpaceProbe, + ).catch(() => undefined); this.#child = null; await terminateChild(child.process); + await finishOnlineBackup?.(); + // A stop during a minutes-long copy should not start a trial; restart resumes the pending update. + if (this.#stopRequested) return; await this.#startTrial(pending); } From a03d9bce026ef11930b35e9855adc1cdb5ea6eb7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:18:35 -0800 Subject: [PATCH 016/436] fix(mobile): file links in question cards open the file viewer (#29151) Co-authored-by: Claude Opus 5.5 --- .../threads/PendingUserInputCard.test.tsx | 142 ++++++++++++++++++ .../features/threads/PendingUserInputCard.tsx | 37 ++++- .../features/threads/ThreadDetailScreen.tsx | 2 + apps/mobile/vite.config.ts | 1 + 4 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 apps/mobile/src/features/threads/PendingUserInputCard.test.tsx diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.test.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.test.tsx new file mode 100644 index 000000000000..8dcfb787478e --- /dev/null +++ b/apps/mobile/src/features/threads/PendingUserInputCard.test.tsx @@ -0,0 +1,142 @@ +import type { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts"; +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +import type { PendingUserInput } from "../../lib/threadActivity"; + +const harness = vi.hoisted(() => ({ + navigate: [] as Array<[string, object | undefined]>, + openedUrls: [] as string[], +})); + +type Children = { children?: ReactNode }; + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, + View: ({ children }: Children) =>
{children}
, + ScrollView: ({ children }: Children) =>
{children}
, + Pressable: ({ children, onPress }: Children & { onPress?: () => void }) => ( +
{children}
+ ), +})); +vi.mock("react-native-reanimated", () => { + const animation = { duration: () => ({ easing: () => ({}) }) }; + return { + default: { View: ({ children }: Children) =>
{children}
}, + Easing: { out: () => () => 0, cubic: () => 0 }, + FadeInUp: animation, + FadeOutDown: animation, + useAnimatedStyle: () => ({}), + useSharedValue: (value: number) => ({ value, set: () => {} }), + }; +}); +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); +vi.mock("../../components/ui/AppText", () => ({ + AppText: ({ children }: Children) => {children}, +})); +vi.mock("../../components/ui/ControlPill", () => ({ ControlPill: () => null })); +vi.mock("../../components/ui/Button", () => ({ Button: () => null })); +vi.mock("./QuestionAttachments", () => ({ QuestionAttachments: () => null })); +vi.mock("../files/FileMarkdownPreview", () => ({ + useMarkdownPreviewStyles: () => ({ nativeTextStyle: {} }), +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ + SelectableMarkdownText: (props: { markdown: string; onLinkPress?: (href: string) => void }) => ( +

+ {[...props.markdown.matchAll(/\[([^\]]+)\]\(([^)]+)\)/g)].map(([, label, href]) => ( + + ))} +

+ ), +})); +vi.mock("../../state/entities", () => ({ + useLiveThreadLinkLabels: (markdown: string) => markdown, +})); +vi.mock("../../native/useOpenPullRequest", () => ({ + useOpenPullRequest: () => async (url: string) => { + harness.openedUrls.push(url); + return true; + }, +})); +vi.mock("@react-navigation/native", () => ({ + useNavigation: () => ({ + navigate: (name: string, params?: object) => harness.navigate.push([name, params]), + }), +})); + +import { PendingUserInputCard } from "./PendingUserInputCard"; + +function setup(questionMarkdown: string) { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + harness.navigate = []; + harness.openedUrls = []; + + const pendingUserInput = { + requestId: "request-1" as RuntimeRequestId, + responseCapability: "resumable", + questions: [ + { + id: "question-1", + header: "Review", + question: questionMarkdown, + options: [], + allowCustomAnswer: false, + }, + ], + } as unknown as PendingUserInput; + const container = document.createElement("div"); + const root = createRoot(container); + act(() => + root.render( + {} } as never} + cardCoverage={{ value: 0, set: () => {} } as never} + collapsed={false} + onToggleCollapsed={() => {}} + drafts={{}} + answers={null} + respondingUserInputId={null} + onSelectOption={() => {}} + onChangeCustomAnswer={() => {}} + onSubmit={async () => {}} + onDismiss={async () => {}} + />, + ), + ); + return { + async pressLink(label: string) { + const link = [...container.querySelectorAll("button")].find( + (button) => button.textContent === label, + ); + if (!link) throw new Error(`No link labelled ${label}`); + await act(async () => link.click()); + }, + [Symbol.dispose]() { + act(() => root.unmount()); + }, + }; +} + +it("opens a workspace file link in a question in the thread's file viewer", async () => { + using screen = setup("Should I update [probe.md](docs/probe.md:12)?"); + + await screen.pressLink("probe.md"); + + expect(harness.openedUrls).toEqual([]); + expect(harness.navigate).toEqual([ + [ + "ThreadFile", + { environmentId: "env-1", threadId: "thread-1", path: ["docs", "probe.md"], line: "12" }, + ], + ]); +}); diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index 3a2127ea2931..70e5ac5c9b07 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -1,12 +1,13 @@ import { Button } from "../../components/ui/Button"; import { QuestionAttachments } from "./QuestionAttachments"; -import type { EnvironmentId, RuntimeRequestId } from "@t3tools/contracts"; +import type { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts"; import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests"; import { markdownProseDirection, textDirection, type TextDirection, } from "@t3tools/shared/textDirection"; +import { useNavigation } from "@react-navigation/native"; import { useRef } from "react"; import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native"; import Animated, { @@ -20,9 +21,15 @@ import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { ControlPill } from "../../components/ui/ControlPill"; import { cn } from "../../lib/cn"; +import { resolveMarkdownLinkPresentation } from "../../lib/markdownLinks"; import { SelectableMarkdownText } from "../../native/SelectableMarkdownText"; import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview"; +import { + fileRoutePathSegments, + resolveFileLinkPath, + resolveWorkspaceRelativeFilePath, +} from "../files/filePath"; import { useLiveThreadLinkLabels } from "../../state/entities"; import { isPendingUserInputOptionSelected, @@ -32,6 +39,8 @@ import type { PendingUserInput } from "../../lib/threadActivity"; export interface PendingUserInputCardProps { readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly workspaceRoot: string | null; readonly canOperateThread: boolean; readonly pendingUserInput: PendingUserInput; readonly maxHeight: DerivedValue; @@ -69,11 +78,31 @@ function proseDirectionStyle(text: string, setDirection: TextDirection | undefin function QuestionText(props: { readonly markdown: string; readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly workspaceRoot: string | null; readonly setDirection: TextDirection | undefined; }) { const styles = useMarkdownPreviewStyles(); const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId); - const openLink = useOpenPullRequest(); + const navigation = useNavigation(); + const openPullRequest = useOpenPullRequest(); + const openLink = (href: string) => { + const link = resolveMarkdownLinkPresentation(href); + if (link.kind !== "file") { + void openPullRequest(href); + return; + } + const path = resolveFileLinkPath(props.workspaceRoot, link.path); + if (path === null) return; + navigation.navigate("ThreadFile", { + environmentId: String(props.environmentId), + threadId: String(props.threadId), + path: fileRoutePathSegments( + resolveWorkspaceRelativeFilePath(props.workspaceRoot, path) ?? path, + ), + ...(link.line ? { line: String(link.line) } : {}), + }); + }; return ( void openLink(href)} + onLinkPress={openLink} /> ); } @@ -239,6 +268,8 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index d9bb48682f89..72361dd24204 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1765,6 +1765,8 @@ function ThreadDetailBody( {props.activePendingUserInput ? ( Date: Tue, 10 Nov 2026 22:45:26 -0800 Subject: [PATCH 017/436] fix(server): cloning into a stranded clone project's empty folder reuses that project (#33439) --- .../features/projects/AddProjectScreen.tsx | 4 +- .../src/project/ProjectCloneTracker.test.ts | 30 ++++++++++ .../server/src/project/ProjectCloneTracker.ts | 60 +++++++++++++------ apps/server/src/ws.ts | 13 ++-- .../components/AddProjectToMachineDialog.tsx | 5 +- ...ommandPalette.composition.browser.test.tsx | 3 +- apps/web/src/components/CommandPalette.tsx | 8 ++- .../promptLinks/NewThreadLinkView.tsx | 10 ++-- apps/web/src/lib/addProjectToMachine.ts | 35 +++++++---- 9 files changed, 119 insertions(+), 49 deletions(-) diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 93680aa38159..c41e1e20ba67 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -1424,12 +1424,11 @@ export function AddProjectDestinationScreen(props: { const originRoute = getActiveRoute(navigation); setIsSubmitting(true); - const projectId = ProjectId.make(uuidv4()); const title = inferProjectTitleFromPath(resolved.path); const startResult = await startProjectClone({ environmentId: environment.environmentId, input: { - projectId, + projectId: ProjectId.make(uuidv4()), title, createdAt: new Date().toISOString(), remoteUrl, @@ -1440,6 +1439,7 @@ export function AddProjectDestinationScreen(props: { setError(errorMessage(Cause.squash(startResult.cause))); } else { void suggestAppAccessForRemote(checkAppAccess, environment.environmentId, remoteUrl); + const { projectId } = startResult.value; // Wait for the create event; the client store otherwise falls back to the project picker and loses clone controls. const project = await waitForProject( { environmentId: environment.environmentId, projectId }, diff --git a/apps/server/src/project/ProjectCloneTracker.test.ts b/apps/server/src/project/ProjectCloneTracker.test.ts index ed775e55a985..0d0a614e467a 100644 --- a/apps/server/src/project/ProjectCloneTracker.test.ts +++ b/apps/server/src/project/ProjectCloneTracker.test.ts @@ -16,6 +16,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts"; import * as ProjectCloneTracker from "./ProjectCloneTracker.ts"; +import { ProjectConflictError } from "./ProjectService.ts"; import { parseGitCloneProgressLine } from "./gitCloneProgress.ts"; const projectId = ProjectId.make("project-1"); @@ -282,6 +283,35 @@ describe("ProjectCloneTracker", () => { }).pipe(Effect.provide(harness.layer)); }); + it.effect("clones for the project that already owns the empty destination", () => { + const owner = ProjectId.make("project-stranded"); + const harness = makeHarness(); + const hooks: ProjectCloneTracker.ProjectCloneHooks = { + ...harness.hooks, + createProject: (input) => + Effect.fail( + new ProjectConflictError({ + projectId: input.projectId, + workspaceRoot: input.workspaceRoot, + conflictingProjectId: owner, + }), + ), + }; + return Effect.gen(function* () { + const tracker = yield* ProjectCloneTracker.ProjectCloneTracker; + const result = yield* tracker.start(startInput, hooks); + expect(result.projectId).toBe(owner); + yield* Effect.yieldNow; + expect(yield* tracker.get(owner)).toMatchObject({ + projectId: owner, + destinationPath: "/workspace/t3code", + phase: "done", + }); + expect(harness.cloned).toEqual([owner]); + expect(yield* tracker.get(projectId)).toBeNull(); + }).pipe(Effect.provide(harness.layer)); + }); + it.effect("does not create a project when the clone cannot be prepared", () => { const harness = makeHarness(); const layer = ProjectCloneTracker.layer.pipe( diff --git a/apps/server/src/project/ProjectCloneTracker.ts b/apps/server/src/project/ProjectCloneTracker.ts index 0a512bde2aa9..0a24f11ffd89 100644 --- a/apps/server/src/project/ProjectCloneTracker.ts +++ b/apps/server/src/project/ProjectCloneTracker.ts @@ -31,6 +31,7 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SourceControlRepositoryService from "../sourceControl/SourceControlRepositoryService.ts"; +import type { ProjectConflictError } from "./ProjectService.ts"; export class ProjectCloneTracker extends Context.Service< ProjectCloneTracker, @@ -53,12 +54,13 @@ export class ProjectCloneTracker extends Context.Service< >()("t3/project/ProjectCloneTracker") {} export interface ProjectCloneHooks { + /** Fails with `ProjectConflictError` when another project already owns the destination. */ readonly createProject: (input: { readonly projectId: ProjectId; readonly title: string; readonly workspaceRoot: string; readonly createdAt: string; - }) => Effect.Effect; + }) => Effect.Effect; readonly onCloned: (input: { readonly projectId: ProjectId; readonly workspaceRoot: string; @@ -266,6 +268,16 @@ export const make = Effect.gen(function* () { }); }); + const moveClaim = (from: ProjectId, to: ProjectId) => + Ref.modify(clones, (current) => { + const claim = current.get(from); + if (!claim || current.has(to)) return [false, current] as const; + const next = new Map(current); + next.delete(from); + next.set(to, { ...claim, snapshot: { ...claim.snapshot, projectId: to } }); + return [true, next] as const; + }); + const start: ProjectCloneTracker["Service"]["start"] = Effect.fn("ProjectCloneTracker.start")( function* (input, hooks) { const prepared = yield* repositories.prepareClone(input); @@ -306,30 +318,44 @@ export const make = Effect.gen(function* () { }); return [true, next] as const; }); - if (!claimed) { - return yield* new SourceControlRepositoryError({ - operation: "cloneRepository", - provider: input.provider ?? SourceControlProviderKind.make("unknown"), - detail: "A clone into this destination is already in progress.", - }); - } + const alreadyInProgress = new SourceControlRepositoryError({ + operation: "cloneRepository", + provider: input.provider ?? SourceControlProviderKind.make("unknown"), + detail: "A clone into this destination is already in progress.", + }); + if (!claimed) return yield* alreadyInProgress; // Finish or release the claim despite disconnects; a claim without a fiber cannot be cancelled or retried. - yield* Effect.uninterruptible( + const projectId = yield* Effect.uninterruptible( Effect.gen(function* () { yield* clearRetention(input.projectId); // Register before creation so racing thread.create and project.delete see the clone. - yield* hooks.createProject({ - projectId: input.projectId, - title: input.title, - workspaceRoot: prepared.destinationPath, - createdAt: input.createdAt, - }); + const projectId = yield* hooks + .createProject({ + projectId: input.projectId, + title: input.title, + workspaceRoot: prepared.destinationPath, + createdAt: input.createdAt, + }) + .pipe( + Effect.as(input.projectId), + // A failed clone's project still owns its empty folder after a restart + // forgets the clone; clone for that project instead. + Effect.catchTags({ + ProjectConflictError: (conflict) => + moveClaim(input.projectId, conflict.conflictingProjectId).pipe( + Effect.flatMap((moved) => + moved ? Effect.succeed(conflict.conflictingProjectId) : alreadyInProgress, + ), + ), + }), + ); yield* publish; - yield* launch(input.projectId); + yield* launch(projectId); + return projectId; }).pipe(Effect.tapError(() => remove(input.projectId))), ); return { - projectId: input.projectId, + projectId, cwd: prepared.destinationPath, remoteUrl: prepared.remoteUrl, repository: prepared.repository, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 9721864fcdfd..5564b801d6b8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2896,12 +2896,13 @@ export const layerWsRpc = ( }) .pipe( Effect.asVoid, - Effect.mapError( - (cause) => - new OrchestrationDispatchCommandError({ - message: "Failed to create clone project.", - cause, - }), + Effect.mapError((cause) => + cause._tag === "ProjectConflictError" + ? cause + : new OrchestrationDispatchCommandError({ + message: "Failed to create clone project.", + cause, + }), ), ), onCloned: (project) => diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 3a5752fcae10..3d9c064cfcb2 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -186,16 +186,15 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe } setSubmitting(true); setError(null); - const projectId = newProjectId(); try { - await addProjectToMachine({ + const projectId = await addProjectToMachine({ source: { environmentId: project.environmentId, cwd: project.workspaceRoot }, subdirectory: projectSubdirectory( project.repositoryIdentity?.rootPath, project.workspaceRoot, ), target: { environmentId: target.environmentId, label: target.label }, - projectId, + projectId: newProjectId(), title: project.title, remoteUrl, destinationPath: destinationPath.trim(), diff --git a/apps/web/src/components/CommandPalette.composition.browser.test.tsx b/apps/web/src/components/CommandPalette.composition.browser.test.tsx index 03cde4f46240..5a2682df6f65 100644 --- a/apps/web/src/components/CommandPalette.composition.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.composition.browser.test.tsx @@ -45,7 +45,8 @@ vi.mock("../hooks/useHandleNewThread", () => ({ vi.mock("../hooks/useOpenPanelPullRequestUrl", () => ({ useOpenPanelPullRequestUrl: () => null })); vi.mock("../connection/useDesktopLocalBootstraps", () => ({ useDesktopLocalBootstraps: () => [] })); vi.mock("../state/use-atom-command", () => ({ - useAtomCommand: () => async () => ({ _tag: "Success", value: undefined }), + // The add-project destination step starts a clone and follows its project id. + useAtomCommand: () => async () => ({ _tag: "Success", value: { projectId: "project-cloned" } }), })); vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => async () => ({ _tag: "Success", value: undefined }), diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index fd912fda2cc7..2e65d62188df 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2166,12 +2166,11 @@ function OpenCommandPaletteDialog(props: { return; } - const projectId = newProjectId(); setIsRemoteProjectCloning(true); const startResult = await startProjectClone({ environmentId: addProjectCloneFlow.environmentId, input: { - projectId, + projectId: newProjectId(), title: inferProjectTitleFromPath(destinationPath), // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309) createdAt: new Date().toISOString(), @@ -2197,7 +2196,10 @@ function OpenCommandPaletteDialog(props: { addProjectCloneFlow.environmentId, addProjectCloneFlow.remoteUrl, ); - const projectRef = scopeProjectRef(addProjectCloneFlow.environmentId, projectId); + const projectRef = scopeProjectRef( + addProjectCloneFlow.environmentId, + startResult.value.projectId, + ); await waitForProject(projectRef, 3_000).catch(() => null); const navigationResult = await settlePromise(() => handleNewThread(projectRef)); if (navigationResult._tag === "Failure") { diff --git a/apps/web/src/components/promptLinks/NewThreadLinkView.tsx b/apps/web/src/components/promptLinks/NewThreadLinkView.tsx index 918e3912b0a1..0cb3c5d5c155 100644 --- a/apps/web/src/components/promptLinks/NewThreadLinkView.tsx +++ b/apps/web/src/components/promptLinks/NewThreadLinkView.tsx @@ -213,13 +213,12 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) { return; } setState({ status: "opening" }); - const projectId = newProjectId(); const remoteUrl = `https://github.com/${repository.owner}/${repository.name}.git`; const settings = serverConfig.settings; const result = await startProjectClone({ environmentId, input: { - projectId, + projectId: newProjectId(), title: repository.name, createdAt: new Date().toISOString(), remoteUrl, @@ -249,9 +248,10 @@ export function NewThreadLinkView({ link }: { readonly link: NewThreadLink }) { environmentId, `https://github.com/${repository.owner}/${repository.name}.git`, ); - const project = await waitForProject(scopeProjectRef(environmentId, projectId), 5_000).catch( - () => null, - ); + const project = await waitForProject( + scopeProjectRef(environmentId, result.value.projectId), + 5_000, + ).catch(() => null); if (project === null) { setState({ status: "failed", message: "The clone started, but its project did not appear." }); return; diff --git a/apps/web/src/lib/addProjectToMachine.ts b/apps/web/src/lib/addProjectToMachine.ts index 0ef0467b934e..2d3bdc5259c8 100644 --- a/apps/web/src/lib/addProjectToMachine.ts +++ b/apps/web/src/lib/addProjectToMachine.ts @@ -97,12 +97,11 @@ export function dismissProjectFileCopy(ref: ScopedProjectRef) { } /** - * Clones a project onto another machine, then copies the chosen ignored files - * from the source. The client relays the files because the two servers never - * talk to each other. Resolves once the clone starts. The caller opens the new - * project, whose composer shows the clone and copy progress, so nothing toasts. + * Clones onto another machine, then relays the chosen ignored files, since the + * two servers never talk. Resolves with the cloning project once it starts; the + * caller opens it, and its composer shows progress, so nothing toasts. */ -export async function addProjectToMachine(input: AddProjectToMachineInput): Promise { +export async function addProjectToMachine(input: AddProjectToMachineInput): Promise { // Read first, so the copy reflects the files as they were when the user asked. const reads = await Promise.all( input.files.map(async (relativePath) => { @@ -120,11 +119,11 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom }), ); - const targetRef = { environmentId: input.target.environmentId, projectId: input.projectId }; - const copyKey = scopedProjectKey(targetRef); + const requestedRef = { environmentId: input.target.environmentId, projectId: input.projectId }; + const requestedKey = scopedProjectKey(requestedRef); // Marked before the start request, since the clone list can arrive before its reply. - silenceProjectCloneToasts(targetRef); - if (reads.length > 0) setFileCopy(copyKey, { phase: "copying" }); + silenceProjectCloneToasts(requestedRef); + if (reads.length > 0) setFileCopy(requestedKey, { phase: "copying" }); const started = await runAtomCommand( appAtomRegistry, sourceControlEnvironment.startProjectClone, @@ -141,14 +140,25 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom { label: "Add project to machine", reportFailure: false }, ); if (started._tag === "Failure") { - setFileCopy(copyKey, null); + setFileCopy(requestedKey, null); throw new Error(failureMessage(started)); } + // The server clones for the existing project when one already owns the empty destination. + const { projectId } = started.value; + const targetRef = { environmentId: input.target.environmentId, projectId }; + const copyKey = scopedProjectKey(targetRef); + if (projectId !== input.projectId) { + silenceProjectCloneToasts(targetRef); + if (reads.length > 0) { + setFileCopy(copyKey, { phase: "copying" }); + setFileCopy(requestedKey, null); + } + } void suggestAppAccessForRemote(input.target.environmentId, input.remoteUrl); - if (reads.length === 0) return; + if (reads.length === 0) return projectId; void (async () => { - const clone = await waitForClone(input.target.environmentId, input.projectId); + const clone = await waitForClone(input.target.environmentId, projectId); if (!clone) { setFileCopy(copyKey, null); return; @@ -188,4 +198,5 @@ export async function addProjectToMachine(input: AddProjectToMachineInput): Prom }, ); })(); + return projectId; } From 492f7119713047e19488f29913f9dd13ea1986e6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:45:32 -0800 Subject: [PATCH 018/436] fix(desktop): stable updates no longer show a nightly's release notes (#32832) Co-authored-by: Claude Opus 5.5 --- .../src/updates/DesktopUpdates.test.ts | 99 +++++++++++++++++++ apps/desktop/src/updates/DesktopUpdates.ts | 8 +- apps/desktop/src/updates/releaseNotes.ts | 16 +++ 3 files changed, 121 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 3b45d80bbc6e..604fbeda3c9f 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -1,5 +1,8 @@ +import * as NodeModule from "node:module"; + import { assert, describe, it } from "@effect/vitest"; import { DESKTOP_UPDATE_RESTART_MARKER_FILE } from "@t3tools/contracts"; +import { computeReleaseNotes } from "electron-updater/out/providers/GitHubProvider.js"; import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -22,6 +25,57 @@ import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts"; import * as DesktopUpdates from "./DesktopUpdates.ts"; import { flushCallbacks, makeHarness } from "./updatesTestHarness.ts"; +type ReleaseFeed = Parameters[2]; +type RunningVersion = Parameters[0]; + +// electron-updater's own dependencies, which apps/desktop does not declare. +const requireFromUpdater = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("electron-updater"), +); +const { parseXml } = requireFromUpdater("builder-util-runtime") as { + parseXml: (xml: string) => ReleaseFeed; +}; +const semver = requireFromUpdater("semver") as { parse: (version: string) => RunningVersion }; + +const releaseTitle = (version: string) => + version.includes("-nightly.") + ? `T3 Code Nightly ${version} (0123456789ab)` + : `T3 Code v${version}`; + +const releaseFeed = (...versions: ReadonlyArray) => + parseXml( + `${versions + .map( + (version) => + `${releaseTitle(version)}<ul><li>${version} change</li></ul>`, + ) + .join("")}`, + ); + +/** The update info electron-updater's GitHub provider reports when /releases/latest names `version`. */ +const stableUpdateInfo = ( + feed: ReleaseFeed, + version: string, + runningVersion: string, + fullChangelog: boolean, +) => { + const latestRelease = + feed + .getElements("entry") + .find((entry) => entry.element("link").attribute("href").endsWith(`/tag/v${version}`)) ?? + feed.element("entry"); + return { + version, + releaseName: latestRelease.elementValueOrEmpty("title"), + releaseNotes: computeReleaseNotes( + semver.parse(runningVersion), + fullChangelog, + feed, + latestRelease, + ), + }; +}; + describe("DesktopUpdates", () => { it.effect("updates Linux .deb installs and leaves other non-AppImage installs off", () => Effect.gen(function* () { @@ -109,6 +163,51 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect.each([ + { + name: "shows no notes for a Stable release missing from the releases feed", + runningVersion: "1.2.3", + feedVersions: ["1.2.5-nightly.20261102.1", "1.2.5-nightly.20261101.1"], + expected: [], + }, + { + name: "shows a Stable release's own notes from the releases feed", + runningVersion: "1.2.3", + feedVersions: ["1.2.5-nightly.20261102.1", "1.2.4", "1.2.4-nightly.20261030.1"], + expected: [{ version: "1.2.4", items: ["1.2.4 change"], totalItems: 1 }], + }, + { + name: "shows a Stable release's notes when switching down from a newer Nightly", + runningVersion: "1.2.5-nightly.20261027.1", + feedVersions: ["1.2.5-nightly.20261102.1", "1.2.4"], + expected: [{ version: "1.2.4", items: ["1.2.4 change"], totalItems: 1 }], + }, + ])("$name", ({ runningVersion, feedVersions, expected }) => { + const harness = makeHarness(); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + + harness.emit( + "update-available", + stableUpdateInfo( + releaseFeed(...feedVersions), + "1.2.4", + runningVersion, + harness.fullChangelog(), + ), + ); + yield* flushCallbacks; + + const state = yield* updates.getState; + assert.equal(state.availableVersion, "1.2.4"); + assert.deepEqual(state.releaseNotes, expected); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("preserves a queued installer when the feed has no update", () => { const harness = makeHarness(); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 14688e525806..36492ca7b906 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -36,7 +36,10 @@ import * as ElectronWindow from "../electron/ElectronWindow.ts"; import * as IpcChannels from "../ipc/channels.ts"; import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts"; import * as DesktopUpdatePolicy from "./DesktopUpdatePolicy.ts"; -import { normalizeDesktopUpdateReleaseNotes } from "./releaseNotes.ts"; +import { + normalizeDesktopUpdateReleaseNotes, + releaseNotesOfOfferedVersion, +} from "./releaseNotes.ts"; import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; import { compareSemverVersions } from "@t3tools/shared/semver"; import { @@ -72,6 +75,7 @@ const UpdateInfo = Schema.Struct({ version: Schema.String, // Malformed notes must not block update-state decoding; normalizeDesktopUpdateReleaseNotes validates separately. releaseNotes: Schema.optional(Schema.Unknown), + releaseName: Schema.optional(Schema.NullOr(Schema.String)), releaseDate: Schema.optional(Schema.String), }); @@ -939,7 +943,7 @@ export const make = Effect.gen(function* () { const checkedAt = yield* currentIsoTimestamp; const { releaseNotes, omittedReleaseCount } = normalizeDesktopUpdateReleaseNotes( - info.releaseNotes, + releaseNotesOfOfferedVersion(info), info.version, state.channel, info.releaseDate, diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts index a31989822209..715c1767e6a0 100644 --- a/apps/desktop/src/updates/releaseNotes.ts +++ b/apps/desktop/src/updates/releaseNotes.ts @@ -171,6 +171,22 @@ interface NormalizedDesktopUpdateReleaseNotes { readonly omittedReleaseCount: number; } +const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +/** + * Untagged notes come from the feed entry named by releaseName, which is the newest entry when the + * offered release is not on the feed's first page. Keep them only when that entry is the offered one. + */ +export function releaseNotesOfOfferedVersion(info: { + readonly version: string; + readonly releaseNotes?: unknown; + readonly releaseName?: string | null | undefined; +}): unknown { + if (typeof info.releaseNotes !== "string" || !info.releaseName) return info.releaseNotes; + const namesVersion = new RegExp(`(?:^|[^\\w.-])v?${escapeRegExp(info.version)}(?![\\w.-])`); + return namesVersion.test(info.releaseName) ? info.releaseNotes : undefined; +} + /** fullChangelog includes all greater semvers, so preview cuts sort above nightlies of the same base version. */ export function normalizeDesktopUpdateReleaseNotes( releaseNotes: unknown, From 2163d41409f0a41ac2afa59ef7e2c937ba777325 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:50:39 -0800 Subject: [PATCH 019/436] fix(shared): Open in Zed ignores the OpenZFS zed daemon on Linux (#33479) --- apps/desktop/src/app/DesktopApp.test.ts | 2 + .../src/process/externalLauncher.test.ts | 79 ++++++++++++++++++- apps/server/src/process/externalLauncher.ts | 13 +-- packages/shared/src/editor.ts | 43 ++++++++-- 4 files changed, 123 insertions(+), 14 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.test.ts b/apps/desktop/src/app/DesktopApp.test.ts index 6cb00baf897d..eab01fb0d52e 100644 --- a/apps/desktop/src/app/DesktopApp.test.ts +++ b/apps/desktop/src/app/DesktopApp.test.ts @@ -7,6 +7,7 @@ import * as Layer from "effect/Layer"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as HttpClient from "effect/http/HttpClient"; +import { ChildProcessSpawner } from "effect/process"; import * as NetService from "@t3tools/shared/Net"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; @@ -213,6 +214,7 @@ it.effect.each([false, true])( Effect.provide( Layer.mergeAll( Layer.mock(BrowserImport.BrowserImport, {}), + Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {}), Layer.mock(DesktopBackendConfiguration.DesktopBackendConfiguration, {}), Layer.mock(DesktopCliCommand.DesktopCliCommand, {}), Layer.mock(DesktopClientSettings.DesktopClientSettings, {}), diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 4a410df61279..f59b6a6187ec 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -517,7 +517,7 @@ it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directo ] as const) { yield* fs.makeDirectory(dir, { recursive: true }); const executable = path.join(dir, name); - yield* fs.writeFileString(executable, "#!/bin/sh\n"); + yield* fs.writeFileString(executable, "#!/bin/sh\necho 'Zed 0.200.0'\n"); yield* fs.chmod(executable, 0o755); } const editor = EDITORS.find((editor) => editor.id === "zed")!; @@ -545,6 +545,83 @@ it.effect.skipIf(windowsHost)("prefers zeditor in a later Linux fallback directo }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); +it.effect.skipIf(windowsHost)("does not offer the OpenZFS zed daemon as Zed on Linux", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-" }); + const binDir = path.join(home, "bin"); + const systemBin = path.join(home, "system-bin"); + yield* fs.makeDirectory(binDir, { recursive: true }); + yield* fs.makeDirectory(systemBin, { recursive: true }); + const zfsZed = path.join(binDir, "zed"); + // OpenZFS zed only takes short options: `--version` is rejected with usage on stderr. + yield* fs.writeFileString( + zfsZed, + "#!/bin/sh\necho \"Invalid option '--'\" >&2\necho 'Usage: zed [OPTION]...' >&2\nexit 1\n", + ); + yield* fs.chmod(zfsZed, 0o755); + const editor = EDITORS.find((editor) => editor.id === "zed")!; + const resolve = resolveEditorCommand(editor, { HOME: home, PATH: binDir }).pipe( + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(Path.Path, { + ...path, + join: (...parts) => + path.join( + ...parts.map((part) => + ["/usr/local/bin", "/usr/bin", "/snap/bin"].includes(part) ? systemBin : part, + ), + ), + }), + ); + assert.deepEqual(yield* resolve, Option.none()); + + const zedEditor = path.join(home, ".local/bin/zed"); + yield* fs.makeDirectory(path.dirname(zedEditor), { recursive: true }); + yield* fs.writeFileString(zedEditor, "#!/bin/sh\necho 'Zed 0.200.0'\n"); + yield* fs.chmod(zedEditor, 0o755); + assert.deepEqual(yield* resolve, Option.some({ command: zedEditor, baseArgs: [] })); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +it.effect.skipIf(windowsHost)("does not open Zed with the OpenZFS zed daemon on Linux", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-zed-zfs-launch-" }); + const binDir = path.join(home, "bin"); + yield* fs.makeDirectory(binDir, { recursive: true }); + yield* fs.writeFileString(path.join(binDir, "zed"), "#!/bin/sh\nexit 1\n"); + yield* fs.chmod(path.join(binDir, "zed"), 0o755); + + const spawned: ChildProcess.StandardCommand[] = []; + const exit = yield* Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + return yield* launcher.launchEditor({ editor: "zed", cwd: "/workspace" }).pipe(Effect.exit); + }).pipe( + Effect.provide( + layerTest({ + platform: "linux", + env: { HOME: home, PATH: binDir }, + onSpawn: (command) => spawned.push(command), + spawnResult: (command) => (command.args[0] === "--version" ? { exitCode: 1 } : undefined), + }), + ), + ); + assert.isTrue(Exit.isFailure(exit)); + if (Exit.isFailure(exit)) { + assert.instanceOf( + Cause.squash(exit.cause), + ExternalLauncher.ExternalLauncherCommandNotFoundError, + ); + } + assert.deepEqual( + spawned.map((command) => command.args), + [["--version"]], + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect.each([ { editor: "webstorm", installPath: "Applications/WebStorm 2026.2.app/Contents/MacOS/webstorm" }, { editor: "idea", installPath: "Applications/IntelliJ IDEA 2026.1.4.app/Contents/MacOS/idea" }, diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index b76f26c52870..b900823f16d0 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -477,13 +477,14 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( } if (editorDef.commands) { - const { command, baseArgs } = Option.getOrElse( - yield* resolveEditorCommand(editorDef, env), - () => ({ + const resolved = yield* resolveEditorCommand(editorDef, env); + if (Option.isNone(resolved)) { + return yield* new ExternalLauncherCommandNotFoundError({ + editor: editorDef.id, command: editorDef.commands[0], - baseArgs: "baseArgs" in editorDef ? editorDef.baseArgs : [], - }), - ); + }); + } + const { command, baseArgs } = resolved.value; return { editor: editorDef.id, target: input.cwd, diff --git a/packages/shared/src/editor.ts b/packages/shared/src/editor.ts index 57bc67afdcfa..fdde5f4ff704 100644 --- a/packages/shared/src/editor.ts +++ b/packages/shared/src/editor.ts @@ -3,9 +3,11 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as HostProcess from "./HostProcess.ts"; -import { isCommandAvailable } from "./shell.ts"; +import { isCommandAvailable, resolveCommandPath } from "./shell.ts"; type Editor = (typeof EDITORS)[number]; @@ -25,6 +27,28 @@ const isVersionedBundle = (entry: string, name: string) => { return /^\d[\d.]*$/.test(entry.slice(name.length + 1, -".app".length)); }; +// OpenZFS's event daemon is also named zed; it rejects `--version` instead of starting. +const isZedEditor = Effect.fn("editor.isZedEditor")( + function* (command: string) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const handle = yield* spawner.spawn( + ChildProcess.make(command, ["--version"], { + stdin: "ignore", + stderr: "ignore", + forceKillAfter: "1 second", + }), + ); + const [stdout, exitCode] = yield* Effect.all( + [handle.stdout.pipe(Stream.decodeText(), Stream.runHead), handle.exitCode], + { concurrency: "unbounded" }, + ); + return exitCode === 0 && Option.getOrElse(stdout, () => "").startsWith("Zed"); + }, + Effect.scoped, + Effect.timeout("2 seconds"), + Effect.catchCause(() => Effect.succeed(false)), +); + export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(function* ( editor: Editor, env: NodeJS.ProcessEnv, @@ -143,14 +167,19 @@ export const resolveEditorCommand = Effect.fn("editor.resolveEditorCommand")(fun } if (preferBundle) candidates.push(...editor.commands); + const rejected = new Set(); for (const candidate of candidates) { - if (yield* isCommandAvailable(candidate, { env })) { - return Option.some({ - command: candidate, - baseArgs: - editor.id === "kiro" && (platform === "darwin" || platform === "win32") ? [] : baseArgs, - }); + const resolved = yield* resolveCommandPath(candidate, { env }); + if (resolved === null || rejected.has(resolved)) continue; + if (preferZeditor && path.basename(candidate) === "zed" && !(yield* isZedEditor(resolved))) { + rejected.add(resolved); + continue; } + return Option.some({ + command: candidate, + baseArgs: + editor.id === "kiro" && (platform === "darwin" || platform === "win32") ? [] : baseArgs, + }); } return Option.none(); }); From 7e45dcdd61942973b4f026d01ca89b4128d438c8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:50:45 -0800 Subject: [PATCH 020/436] fix(mobile): chat code blocks colour diff, kotlin, sql and other languages again (#33680) Co-authored-by: Claude Opus 5.5 --- .../ui/AndroidAnchoredMenu.android.tsx | 39 +++-- apps/mobile/src/lib/menu-placement.test.ts | 27 ++++ apps/mobile/src/lib/menu-placement.ts | 28 ++++ apps/mobile/src/native/CodeBlockFrame.tsx | 98 +++++++++++++ .../src/native/EnrichedMarkdownText.tsx | 42 +++++- .../src/native/HighlightedCodeBlock.tsx | 137 ++++++++++++++++++ apps/mobile/src/native/MermaidCodeBlock.tsx | 76 ++-------- .../src/native/codeBlockMarkdown.test.ts | 30 ++++ apps/mobile/src/native/codeBlockMarkdown.ts | 54 +++++++ 9 files changed, 442 insertions(+), 89 deletions(-) create mode 100644 apps/mobile/src/lib/menu-placement.test.ts create mode 100644 apps/mobile/src/native/CodeBlockFrame.tsx create mode 100644 apps/mobile/src/native/HighlightedCodeBlock.tsx create mode 100644 apps/mobile/src/native/codeBlockMarkdown.test.ts create mode 100644 apps/mobile/src/native/codeBlockMarkdown.ts diff --git a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx index 369fcf19ef55..a17e48c2604c 100644 --- a/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx +++ b/apps/mobile/src/components/ui/AndroidAnchoredMenu.android.tsx @@ -6,7 +6,10 @@ import { Pressable, ScrollView, View } from "react-native"; import { useKeyboardState } from "react-native-keyboard-controller"; import { useHardwareBack } from "../../lib/backHandler"; -import { deriveMenuHorizontalPlacement } from "../../lib/menu-placement"; +import { + deriveMenuHorizontalPlacement, + deriveMenuVerticalPlacement, +} from "../../lib/menu-placement"; import { WindowHingeContext } from "../../native/window-hinge-context"; import { OverlayPortal } from "./OverlayPortal"; import { useAndroidControlSizing } from "./useAndroidControlSizing"; @@ -41,10 +44,9 @@ export type AndroidAnchoredMenuProps = { }; export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { - const { scale, menuWidth: desiredMenuWidth } = useAndroidControlSizing(); + const { scale, menuWidth: desiredMenuWidth, menuItemHeight } = useAndroidControlSizing(); const [anchor, setAnchor] = useState(null); const [path, setPath] = useState([]); - const [rootHeight, setRootHeight] = useState(null); const [overlay, setOverlay] = useState(null); const windowHinge = use(WindowHingeContext); // State, not a ref: `open` reaches render-prop children, and the compiler @@ -58,7 +60,6 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { setAnchor(null); setPath([]); setOverlay(null); - setRootHeight(null); }; const open = () => { @@ -70,7 +71,6 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { const measureOverlay = () => { overlayRef.current?.measureInWindow((x, y, width, height) => { setOverlay({ x, y, width, height }); - setRootHeight(height); }); }; @@ -110,17 +110,19 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { margin: SCREEN_MARGIN, hinge: windowHinge && { x: windowHinge.x - overlay.x, width: windowHinge.width }, }); - // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable. - const usableBottom = - overlay === null ? 0 : overlay.height - (keyboardVisible ? keyboardHeight : 0); - const spaceBelow = + const verticalPlacement = local === null || overlay === null - ? 0 - : usableBottom - (local.y + local.height) - ANCHOR_GAP - SCREEN_MARGIN; - const spaceAbove = local === null ? 0 : local.y - ANCHOR_GAP - SCREEN_MARGIN; - const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove; - const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480); - const placeable = local !== null && rootHeight !== null; + ? null + : deriveMenuVerticalPlacement({ + anchorY: local.y, + anchorHeight: local.height, + overlayHeight: overlay.height, + // This in-window menu preserves keyboard focus; subtract the IME area so its items remain tappable. + keyboardInset: keyboardVisible ? keyboardHeight : 0, + gap: ANCHOR_GAP, + margin: SCREEN_MARGIN, + minHeight: 2 * menuItemHeight + 14 * scale, + }); const onPressItem = (action: MenuAction) => { if ((action.subactions?.length ?? 0) > 0) { @@ -167,7 +169,7 @@ export function AndroidAnchoredMenu(props: AndroidAnchoredMenuProps) { onLayout={measureOverlay} > - {!placeable || local === null ? null : !anchor.keyboardWasVisible ? ( + {local === null ? null : !anchor.keyboardWasVisible ? ( {/* Compose DropdownMenu takes focus; in-window editor menus preserve the keyboard. */} diff --git a/apps/mobile/src/lib/menu-placement.test.ts b/apps/mobile/src/lib/menu-placement.test.ts new file mode 100644 index 000000000000..725a5c3ad879 --- /dev/null +++ b/apps/mobile/src/lib/menu-placement.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { deriveMenuVerticalPlacement } from "./menu-placement"; + +const base = { gap: 6, margin: 12, minHeight: 110 }; + +describe("deriveMenuVerticalPlacement", () => { + it.each([ + { + name: "anchor taller than the keyboard-free area stays on screen", + input: { anchorY: -100, anchorHeight: 1000, overlayHeight: 800, keyboardInset: 300 }, + expected: { maxHeight: 476, top: 12 }, + }, + { + name: "room below opens down", + input: { anchorY: 100, anchorHeight: 40, overlayHeight: 800, keyboardInset: 300 }, + expected: { maxHeight: 342, top: 146 }, + }, + { + name: "room above opens up", + input: { anchorY: 400, anchorHeight: 40, overlayHeight: 800, keyboardInset: 300 }, + expected: { maxHeight: 382, bottom: 406 }, + }, + ])("$name", ({ input, expected }) => { + expect(deriveMenuVerticalPlacement({ ...base, ...input })).toEqual(expected); + }); +}); diff --git a/apps/mobile/src/lib/menu-placement.ts b/apps/mobile/src/lib/menu-placement.ts index 8bd560e6a446..eb7262a41eaa 100644 --- a/apps/mobile/src/lib/menu-placement.ts +++ b/apps/mobile/src/lib/menu-placement.ts @@ -23,3 +23,31 @@ export function deriveMenuHorizontalPlacement(input: { const left = Math.min(Math.max(preferredLeft, start + input.margin), end - width - input.margin); return { left, width }; } + +/** In the overlay's coordinates; `bottom` is measured up from the overlay's bottom edge. */ +export function deriveMenuVerticalPlacement(input: { + readonly anchorY: number; + readonly anchorHeight: number; + readonly overlayHeight: number; + readonly keyboardInset: number; + readonly gap: number; + readonly margin: number; + readonly minHeight: number; +}) { + const usableBottom = input.overlayHeight - input.keyboardInset; + const spaceBelow = usableBottom - (input.anchorY + input.anchorHeight) - input.gap - input.margin; + const spaceAbove = input.anchorY - input.gap - input.margin; + const opensDown = spaceBelow >= 280 || spaceBelow >= spaceAbove; + const maxHeight = Math.min(opensDown ? spaceBelow : spaceAbove, 480); + if (maxHeight < input.minHeight) { + // Neither side fits (e.g. a code block taller than the screen): overlap the anchor instead. + const top = Math.max( + input.margin, + Math.min(input.anchorY, usableBottom - input.margin - input.minHeight), + ); + return { maxHeight: Math.min(usableBottom - input.margin - top, 480), top }; + } + return opensDown + ? { maxHeight, top: input.anchorY + input.anchorHeight + input.gap } + : { maxHeight, bottom: input.overlayHeight - input.anchorY + input.gap }; +} diff --git a/apps/mobile/src/native/CodeBlockFrame.tsx b/apps/mobile/src/native/CodeBlockFrame.tsx new file mode 100644 index 000000000000..1c80e759d4db --- /dev/null +++ b/apps/mobile/src/native/CodeBlockFrame.tsx @@ -0,0 +1,98 @@ +import type { ReactNode } from "react"; +import { Pressable, StyleSheet, Text, View } from "react-native"; + +import { SymbolView, type AppSymbolName } from "../components/ui/AppSymbol"; +import { themeColorWithAlpha } from "../lib/mobileTheme"; +import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types"; + +/** + * The native code block's border and header, for a fence drawn in React once it closes. + * The block slot already applies the code block's outer margins. + */ +export function CodeBlockFrame(props: { + readonly label: string; + readonly textStyle: NativeMarkdownTextStyle; + readonly actions: ReactNode; + readonly children: ReactNode; +}) { + const { textStyle } = props; + return ( + + + + {props.label} + + {props.actions} + + {props.children} + + ); +} + +/** A header icon; `active` draws it at full strength, as the native wrap toggle when on. */ +export function CodeBlockHeaderButton(props: { + readonly icon: AppSymbolName; + readonly label: string; + readonly textStyle: NativeMarkdownTextStyle; + readonly active?: boolean; + readonly onPress: () => void; +}) { + return ( + + + + ); +} + +const styles = StyleSheet.create({ + block: { + borderRadius: 8, + borderWidth: StyleSheet.hairlineWidth, + overflow: "hidden", + }, + header: { + minHeight: 32, + paddingHorizontal: 12, + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", + borderBottomWidth: StyleSheet.hairlineWidth, + }, + label: { fontWeight: "500" }, + actions: { flexDirection: "row", alignItems: "center", gap: 14 }, +}); diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 16bab62f0937..86bf8021bdd0 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -20,6 +20,8 @@ import { type MarkdownLinkOccurrence, type MarkdownStyle, } from "react-native-enriched-markdown"; +import { codeFenceRenderer } from "./codeBlockMarkdown"; +import { HighlightedCodeBlock } from "./HighlightedCodeBlock"; import { MermaidCodeBlock } from "./MermaidCodeBlock"; import type { SelectableMarkdownTextProps } from "./SelectableMarkdownText.types"; @@ -29,6 +31,7 @@ import { useEnrichedLinkVariants } from "./useEnrichedLinkVariants"; import { useRetryingImageSource } from "./useRetryingImageSource"; import * as Dialog from "../components/ui/Dialog"; import { copyTextWithHaptic } from "../lib/copyTextWithHaptic"; +import type { HighlightScheme } from "../lib/highlights"; import { ENRICHED_INLINE_FILE_LINK_REGEX, enrichedTextLinkRegex, @@ -166,19 +169,25 @@ function enrichedStyle( }; } -/** Diagram and math fences, as web draws them. A fence streams as native code until it closes. */ +/** + * Diagram and math fences, as web draws them, and code enriched-markdown cannot colour. + * Diagrams and math stay native until the library reports them complete; fallback code keeps one block throughout. + */ function codeBlockElement( block: MarkdownCodeBlock, textStyle: SelectableMarkdownTextProps["textStyle"], markdownStyle: MarkdownStyle, mathRenderingEnabled: boolean, + scheme: HighlightScheme, ): ReactElement | undefined { - if (!block.isComplete) return undefined; - if (block.language === "mermaid") { - return ; + const renderer = codeFenceRenderer(block.language, mathRenderingEnabled); + if (renderer.kind === "mermaid") { + return block.isComplete ? ( + + ) : undefined; } - if (block.language === "math" && mathRenderingEnabled) { - return ( + if (renderer.kind === "math") { + return block.isComplete ? ( + ) : undefined; + } + if (renderer.kind === "highlight" && markdownStyle.codeBlock) { + return ( + ); } return undefined; @@ -347,7 +369,13 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { } : undefined, code: (block: MarkdownCodeBlock) => - codeBlockElement(block, props.textStyle, baseMarkdownStyle, mathRenderingEnabled), + codeBlockElement( + block, + props.textStyle, + baseMarkdownStyle, + mathRenderingEnabled, + themeAppearance, + ), }; const resolveNativeImageSource = useRetryingImageSource(resolveImageSource); const renderMarkdown = (openAndroidMenu?: () => void) => { diff --git a/apps/mobile/src/native/HighlightedCodeBlock.tsx b/apps/mobile/src/native/HighlightedCodeBlock.tsx new file mode 100644 index 000000000000..b0c981d95e3f --- /dev/null +++ b/apps/mobile/src/native/HighlightedCodeBlock.tsx @@ -0,0 +1,137 @@ +import { useState } from "react"; +import { Pressable, ScrollView, Text } from "react-native"; +import type { MarkdownStyle } from "react-native-enriched-markdown"; + +import { Menu } from "../components/ui/Menu"; +import { useMarkdownCodeHighlight } from "../features/threads/markdownCodeHighlightState"; +import { copyTextWithHaptic } from "../lib/copyTextWithHaptic"; +import type { HighlightScheme } from "../lib/highlights"; +import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame"; +import { fencedCodeMarkdown } from "./codeBlockMarkdown"; +import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types"; + +// Header names from enriched-markdown's CodeBlockLanguages.cpp that are not the fence capitalized. +const FENCE_DISPLAY_NAMES: Readonly> = { + cc: "C++", + cpp: "C++", + cxx: "C++", + cs: "C#", + csharp: "C#", + graphql: "GraphQL", + objc: "Objective-C", + objectivec: "Objective-C", + php: "PHP", + rb: "Ruby", + scss: "SCSS", + sql: "SQL", + toml: "TOML", + xml: "XML", +}; + +// The native block's long-press menu, with its labels and iOS symbols. +const CODE_MENU_ACTIONS = [ + { id: "copy-code", title: "Copy", image: "doc.on.doc" }, + { id: "copy-markdown", title: "Copy as Markdown", image: "doc.text" }, +]; + +/** A fence in a language enriched-markdown cannot colour, drawn like its native block. */ +export function HighlightedCodeBlock(props: { + readonly code: string; + readonly fence: string; + readonly language: string; + /** False only while the library withholds an unclosed fence (`streamingAnimation`, which T3 never enables, so always true today); highlighting waits for it. */ + readonly complete: boolean; + readonly scheme: HighlightScheme; + readonly textStyle: NativeMarkdownTextStyle; + readonly codeStyle: NonNullable; +}) { + const { code, codeStyle, textStyle } = props; + const [wrapped, setWrapped] = useState(false); + const lines = useMarkdownCodeHighlight({ + code, + language: props.language, + theme: props.scheme, + enabled: props.complete, + }); + const fence = props.fence.toLowerCase(); + let offset = 0; + const text = ( + // Not selectable: as in the native block, a long-press opens the copy menu instead. + + {lines?.flatMap((line, lineIndex) => { + const separator = lineIndex > 0 ? "\n" : ""; + offset += separator.length; + return [ + separator, + ...line.map((token) => { + const start = offset; + offset += token.content.length; + return ( + + {token.content} + + ); + }), + ]; + }) ?? code} + + ); + // Inside the scroller: on iOS an ancestor JS responder disables a ScrollView's panning. + const content = ( + { + copyTextWithHaptic( + nativeEvent.event === "copy-markdown" ? fencedCodeMarkdown(code, props.fence) : code, + ); + }} + > + {text} + + ); + return ( + + setWrapped((value) => !value)} + /> + copyTextWithHaptic(code)} + /> + + } + > + {wrapped ? ( + content + ) : ( + + {content} + + )} + + ); +} diff --git a/apps/mobile/src/native/MermaidCodeBlock.tsx b/apps/mobile/src/native/MermaidCodeBlock.tsx index 345f99b1b635..154c7e11ee17 100644 --- a/apps/mobile/src/native/MermaidCodeBlock.tsx +++ b/apps/mobile/src/native/MermaidCodeBlock.tsx @@ -7,10 +7,10 @@ import { PixelRatio, Platform, Pressable, StyleSheet, Text, View } from "react-n import { parse, Svg, SvgXml } from "react-native-svg"; import { FilePreviewModal } from "../components/ui/FilePreviewModal"; -import { SymbolView, type AppSymbolName } from "../components/ui/AppSymbol"; import { copyTextWithHaptic } from "../lib/copyTextWithHaptic"; import { mermaidSvgForNative, withDiagramBackground } from "../lib/mermaidSvg"; import { themeColorWithAlpha } from "../lib/mobileTheme"; +import { CodeBlockFrame, CodeBlockHeaderButton } from "./CodeBlockFrame"; import type { NativeMarkdownTextStyle } from "./SelectableMarkdownText.types"; type Pele = typeof import("pele/lazy"); @@ -191,43 +191,29 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram ); }; - // The header copies the native code block's, which this block replaces once the fence closes. return ( - - - - Mermaid - - + {svg ? ( - setShowCode((value) => !value)} /> ) : null} - copyTextWithHaptic(code)} /> - - + + } + > {diagram?.status === "error" ? ( @@ -296,45 +282,11 @@ function MermaidBlock(props: MermaidCodeBlockProps & { readonly diagram: Diagram onRequestClose={() => setExpansion(null)} /> ) : null} - - ); -} - -function HeaderButton(props: { - readonly icon: AppSymbolName; - readonly label: string; - readonly color: string; - readonly onPress: () => void; -}) { - return ( - - - + ); } -// The block slot already applies the code block's outer margins. const styles = StyleSheet.create({ - block: { - borderRadius: 8, - borderWidth: StyleSheet.hairlineWidth, - overflow: "hidden", - }, - header: { - height: 32, - paddingHorizontal: 12, - flexDirection: "row", - alignItems: "center", - justifyContent: "space-between", - borderBottomWidth: StyleSheet.hairlineWidth, - }, - language: { fontWeight: "500" }, - actions: { flexDirection: "row", alignItems: "center", gap: 14 }, content: { padding: 12 }, diagramRow: { flexDirection: "row", justifyContent: "center" }, error: { marginBottom: 8 }, diff --git a/apps/mobile/src/native/codeBlockMarkdown.test.ts b/apps/mobile/src/native/codeBlockMarkdown.test.ts new file mode 100644 index 000000000000..1b254ed420ed --- /dev/null +++ b/apps/mobile/src/native/codeBlockMarkdown.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { codeFenceRenderer, fencedCodeMarkdown } from "./codeBlockMarkdown"; + +describe("fencedCodeMarkdown", () => { + it.each([ + ["a plain fence", "fun main() {}", "kotlin", "```kotlin\nfun main() {}\n```"], + ["a longer fence than the code's", "```\nx\n```", "md", "````md\n```\nx\n```\n````"], + ["no language", "x", "", "```\nx\n```"], + ])("writes %s", (_, code, language, expected) => { + expect(fencedCodeMarkdown(code, language)).toBe(expected); + }); +}); + +describe("codeFenceRenderer", () => { + it.each([ + ["mermaid", true, { kind: "mermaid" }], + ["math", true, { kind: "math" }], + ["math", false, { kind: "native" }], + ["kotlin", true, { kind: "highlight", language: "kotlin" }], + ["KOTLIN", true, { kind: "highlight", language: "kotlin" }], + ["diff", true, { kind: "highlight", language: "diff" }], + ["ts", true, { kind: "native" }], + ["python", true, { kind: "native" }], + ["", true, { kind: "native" }], + ["text", true, { kind: "native" }], + ])("draws %j with math rendering %s as %j", (fence, mathRenderingEnabled, expected) => { + expect(codeFenceRenderer(fence, mathRenderingEnabled)).toEqual(expected); + }); +}); diff --git a/apps/mobile/src/native/codeBlockMarkdown.ts b/apps/mobile/src/native/codeBlockMarkdown.ts new file mode 100644 index 000000000000..b4be181a2ba8 --- /dev/null +++ b/apps/mobile/src/native/codeBlockMarkdown.ts @@ -0,0 +1,54 @@ +import { resolveHighlightLanguage } from "../lib/highlightLanguage"; + +// Fences enriched-markdown colours itself: cpp/highlight/CodeBlockLanguages.cpp entries with a default grammar. +const NATIVE_HIGHLIGHT_FENCES = new Set([ + "bash", + "c", + "css", + "go", + "golang", + "html", + "java", + "javascript", + "js", + "json", + "jsx", + "markdown", + "md", + "py", + "python", + "rs", + "rust", + "sh", + "shell", + "ts", + "tsx", + "typescript", + "yaml", + "yml", + "zsh", +]); + +/** A fenced code block for `code`, with a backtick fence longer than any backtick run inside it. */ +export function fencedCodeMarkdown(code: string, language: string): string { + let longestRun = 0; + for (const [run] of code.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length); + const fence = "`".repeat(Math.max(3, longestRun + 1)); + return `${fence}${language}\n${code}\n${fence}`; +} + +type CodeFenceRenderer = + | { readonly kind: "mermaid" } + | { readonly kind: "math" } + | { readonly kind: "highlight"; readonly language: string } + | { readonly kind: "native" }; + +/** Mermaid and math fences first: highlights knows `mermaid` too, and would claim it as code. */ +export function codeFenceRenderer(fence: string, mathRenderingEnabled: boolean): CodeFenceRenderer { + if (fence === "mermaid") return { kind: "mermaid" }; + if (fence === "math" && mathRenderingEnabled) return { kind: "math" }; + const name = fence.toLowerCase(); + if (NATIVE_HIGHLIGHT_FENCES.has(name)) return { kind: "native" }; + const language = resolveHighlightLanguage({ language: name }); + return language === "text" ? { kind: "native" } : { kind: "highlight", language }; +} From 543ee27fa8e890cf0f6ce9e7f6a2d53dd3b1a7af Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 22:55:58 -0800 Subject: [PATCH 021/436] fix(server): fork Claude threads after project root changes (#22836) Co-authored-by: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 72 +++++++++++++++---- .../Adapters/ClaudeAdapterV2.testkit.ts | 6 +- .../Adapters/ClaudeAdapterV2.ts | 8 +-- .../claude_transcript.ndjson | 2 +- .../claude_transcript.ndjson | 2 +- .../claude_transcript.ndjson | 2 +- .../claude_transcript.ndjson | 4 +- 7 files changed, 70 insertions(+), 26 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 1add2822a01e..b98b5d372851 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2442,7 +2442,7 @@ describe("ClaudeAdapterV2 attachments", () => { }); describe("ClaudeAdapterV2 native fork", () => { - it.effect("forks at the source assistant cursor and resumes the forked session", () => + it.effect("forks a session from its original directory after the workspace root changes", () => Effect.scoped( Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -2450,19 +2450,61 @@ describe("ClaudeAdapterV2 native fork", () => { const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-claude-v2-fork-attachments-", }); + const configDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-claude-root-change-", + }); + const sourceSessionId = "11111111-1111-4111-8111-111111111111"; + const sourceCursor = "aaaaaaaa-0000-4000-8000-000000000002"; + const projectDir = NodePath.join(configDir, "projects", "-old-workspace"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + const entry = (uuid: string, parentUuid: string | null, message: unknown) => ({ + type: parentUuid === null ? "user" : "assistant", + uuid, + parentUuid, + sessionId: sourceSessionId, + cwd: "/old-workspace", + isSidechain: false, + timestamp: "2026-10-01T00:00:00.000Z", + message, + }); + yield* fileSystem.writeFileString( + NodePath.join(projectDir, `${sourceSessionId}.jsonl`), + [ + entry("aaaaaaaa-0000-4000-8000-000000000001", null, { role: "user", content: "hello" }), + entry(sourceCursor, "aaaaaaaa-0000-4000-8000-000000000001", { + role: "assistant", + content: [{ type: "text", text: "inherited answer" }], + }), + ] + .map((line) => JSON.stringify(line)) + .join("\n"), + ); + const realRunner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.pipe( + Effect.provide( + ClaudeAdapterV2.layerQueryRunner.pipe( + Layer.provide(PortScanner.layerTest), + Layer.provide( + Layer.succeed(ProviderEventLoggers.ProviderEventLoggers, { + native: undefined, + canonical: undefined, + }), + ), + ), + ), + ); const openedQueries: Array = []; const forkCalls: Array = []; const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, settings: DEFAULT_CLAUDE_SETTINGS, - environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" }, + environment: { CLAUDE_CONFIG_DIR: configDir }, attachmentsDir, fileSystem, path: yield* Path.Path, random: yield* SecureRandom.SecureRandom, idAllocator, queryRunner: { - allocateSessionId: Effect.succeed("source-native-session"), + allocateSessionId: Effect.succeed(sourceSessionId), open: (input) => Effect.sync(() => { openedQueries.push(input); @@ -2483,9 +2525,9 @@ describe("ClaudeAdapterV2 native fork", () => { }; }), forkSession: (input) => - Effect.sync(() => { + Effect.gen(function* () { forkCalls.push(input); - return { sessionId: "forked-native-session" }; + return yield* realRunner.forkSession(input); }), subagentLaunchToolUseId: () => Effect.succeed(null), assertComplete: Effect.void, @@ -2531,7 +2573,7 @@ describe("ClaudeAdapterV2 native fork", () => { runAttemptId: RunAttemptId.make("run-attempt-claude-source"), nativeTurnRef: { driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeId: "assistant-message-cursor", + nativeId: sourceCursor, strength: "weak", }, ordinal: 1, @@ -2546,17 +2588,22 @@ describe("ClaudeAdapterV2 native fork", () => { assert.deepEqual(forkCalls, [ { - sessionId: "source-native-session", + sessionId: sourceSessionId, options: { - dir: "/workspace", - upToMessageId: "assistant-message-cursor", + upToMessageId: sourceCursor, }, - environment: { CLAUDE_CONFIG_DIR: "/custom/claude-home" }, + environment: { CLAUDE_CONFIG_DIR: configDir }, threadId: targetThreadId, providerSessionId, }, ]); - assert.equal(forkedProviderThread.nativeThreadRef?.nativeId, "forked-native-session"); + const forkedSessionId = forkedProviderThread.nativeThreadRef?.nativeId; + assert.isString(forkedSessionId); + assert.notEqual(forkedSessionId, sourceSessionId); + const forkedTranscript = yield* fileSystem.readFileString( + NodePath.join(projectDir, `${forkedSessionId}.jsonl`), + ); + assert.include(forkedTranscript, "inherited answer"); assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id); assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId); @@ -2616,8 +2663,9 @@ describe("ClaudeAdapterV2 native fork", () => { }), }); - assert.equal(openedQueries[0]?.options.resume, "forked-native-session"); + assert.equal(openedQueries[0]?.options.resume, forkedSessionId); assert.equal(openedQueries[0]?.options.sessionId, undefined); + assert.equal(openedQueries[0]?.options.cwd, NodePath.resolve("/workspace")); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index 923aa7de509c..abb4c22ac780 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -2175,15 +2175,11 @@ async function recordClaudeForkSessionQuery(input: { type: "session.fork", sessionId: input.sessionId, options: { - dir: sanitizedReplayCwd(input.scenario), upToMessageId, }, }, }); - const forked = await forkSession(input.sessionId, { - dir: input.cwd, - upToMessageId, - }); + const forked = await forkSession(input.sessionId, { upToMessageId }); forkedNativeSessionIds.push(forked.sessionId); input.entries.push({ type: "emit_inbound", diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7b63b7efc0b6..bb914d54d1cd 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -12342,10 +12342,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const sourceNativeThreadId = yield* getNativeThreadId(forkInput.sourceProviderThread); yield* closeLiveQueryForNativeThread(sourceNativeThreadId); const upToMessageId = yield* resolveClaudeForkUpToMessageId(forkInput); - const forkOptions: ForkSessionOptions = { - ...(input.runtimePolicy.cwd === null ? {} : { dir: input.runtimePolicy.cwd }), - ...(upToMessageId === undefined ? {} : { upToMessageId }), - }; + // A moved project still has its transcript under the original cwd. + // Let the SDK find the session by ID within this Claude home. + const forkOptions: ForkSessionOptions = + upToMessageId === undefined ? {} : { upToMessageId }; const forked = yield* queryRunner.forkSession({ sessionId: sourceNativeThreadId, options: forkOptions, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/claude_transcript.ndjson index cd24f67e98ca..dc9335bf5a55 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native/claude_transcript.ndjson @@ -8,7 +8,7 @@ {"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"84451d3f-e7ba-4d80-aea3-4fbc442f4b3b","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9"}} {"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2066,"duration_api_ms":1815,"num_turns":1,"result":"source fork seed ok","stop_reason":"end_turn","session_id":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","total_cost_usd":0.01172175,"usage":{"input_tokens":3,"cache_creation_input_tokens":2339,"cache_read_input_tokens":9455,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":2339,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":9455,"cache_creation_input_tokens":2339,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":2339},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":9455,"cacheCreationInputTokens":2339,"webSearchRequests":0,"costUSD":0.01172175,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"892cdc1f-e2d5-440d-ae57-ca27d32f63f1"}} {"type":"runtime_exit","status":"success"} -{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","options":{"dir":"/tmp/claude-replay-thread_fork_native","upToMessageId":"68baa075-b7d4-4689-866b-96bd51e570c3"}}} +{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"8d0dafab-45d3-45eb-abef-41b9e55d5ff9","options":{"upToMessageId":"68baa075-b7d4-4689-866b-96bd51e570c3"}}} {"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad"}} {"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"7e7ad6ec-db4a-4510-85ff-59df35cf7fad","settings":{"showThinkingSummaries":true}}}} {"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with the following text: fork native ok"},"parent_tool_use_id":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson index 317d51456cb7..b08e908042b9 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson @@ -8,7 +8,7 @@ {"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1779846000,"rateLimitType":"five_hour","overageStatus":"rejected","overageDisabledReason":"org_level_disabled","isUsingOverage":false},"uuid":"94e56646-7610-4a7a-8245-9301469861ae","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d"}} {"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2928,"duration_api_ms":1977,"num_turns":1,"result":"fork local source alpha","stop_reason":"end_turn","session_id":"273fe17b-65fb-451f-ad99-ff19d323852d","total_cost_usd":0.0036539999999999997,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":11800,"output_tokens":7,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":7,"cache_read_input_tokens":11800,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":7,"cacheReadInputTokens":11800,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.0036539999999999997,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"684990a5-0d00-4928-a332-fdc2c66769c6"}} {"type":"runtime_exit","status":"success"} -{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"273fe17b-65fb-451f-ad99-ff19d323852d","options":{"dir":"/tmp/claude-replay-thread_fork_native_fork_local_rollback","upToMessageId":"7659a146-b729-47b6-aac2-8fc0c0981e92"}}} +{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"273fe17b-65fb-451f-ad99-ff19d323852d","options":{"upToMessageId":"7659a146-b729-47b6-aac2-8fc0c0981e92"}}} {"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"c9784d72-7e4f-4994-8c21-2e7e670ff91c"}} {"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"c9784d72-7e4f-4994-8c21-2e7e670ff91c","settings":{"showThinkingSummaries":true}}}} {"type":"expect_outbound","label":"prompt.offer:fork-first","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"For this fork-local rollback fixture, respond with exactly: fork local first"},"parent_tool_use_id":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson index f65c071d7bf3..e195e8db004b 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson @@ -12,7 +12,7 @@ {"type":"emit_inbound","label":"assistant","frame":{"type":"assistant","message":{"model":"claude-sonnet-4-6","id":"msg_0181K4CdzyVanM6Px26CQP7L","type":"message","role":"assistant","content":[{"type":"text","text":"fork boundary beta"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":23,"cache_read_input_tokens":11797,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":23},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"context_management":null},"parent_tool_use_id":null,"session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","uuid":"c517b74b-9537-4260-afcb-186c4056c0a4"}} {"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2545,"duration_api_ms":3001,"num_turns":1,"result":"fork boundary beta","stop_reason":"end_turn","session_id":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","total_cost_usd":0.01544235,"usage":{"input_tokens":3,"cache_creation_input_tokens":23,"cache_read_input_tokens":11797,"output_tokens":6,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":23,"ephemeral_5m_input_tokens":0},"inference_geo":"","iterations":[{"input_tokens":3,"output_tokens":6,"cache_read_input_tokens":11797,"cache_creation_input_tokens":23,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":23},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":6,"outputTokens":12,"cacheReadInputTokens":21252,"cacheCreationInputTokens":2365,"webSearchRequests":0,"costUSD":0.01544235,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"e4f26af4-3a60-45f3-8d5c-c0f8b968c400"}} {"type":"runtime_exit","status":"success"} -{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","options":{"dir":"/tmp/claude-replay-thread_fork_native_prior_turn","upToMessageId":"be0e3276-8c27-44bf-8ed0-0b4424e9f902"}}} +{"type":"expect_outbound","label":"session.fork","frame":{"type":"session.fork","sessionId":"a91391e1-0de3-4107-a7c9-db7b1bbd8b99","options":{"upToMessageId":"be0e3276-8c27-44bf-8ed0-0b4424e9f902"}}} {"type":"emit_inbound","label":"session.forked","frame":{"type":"session.forked","sessionId":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd"}} {"type":"expect_outbound","label":"query.open:fork","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"f5cc58dd-0d74-4950-9fb5-2a9fded47ddd","settings":{"showThinkingSummaries":true}}}} {"type":"expect_outbound","label":"prompt.offer:3","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content."},"parent_tool_use_id":null}}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/claude_transcript.ndjson index 37ada38b28b5..00db6482c307 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/thread_merge_back_siblings/claude_transcript.ndjson @@ -8,7 +8,7 @@ {"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"04dac113-90a6-48fa-ab30-d02d34e76f76","session_id":"093127f0-d3a7-42f8-938e-b1162927a0ea"}} {"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2354,"duration_api_ms":1892,"ttft_ms":1845,"num_turns":1,"result":"merge sibling source stored","stop_reason":"end_turn","session_id":"093127f0-d3a7-42f8-938e-b1162927a0ea","total_cost_usd":0.005823599999999999,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":18982,"output_tokens":8,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":3,"output_tokens":8,"cache_read_input_tokens":18982,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":8,"cacheReadInputTokens":18982,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.005823599999999999,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"148a66d3-6af8-42ec-95d9-51106ba6b80c"}} {"type":"runtime_exit","status":"success"} -{"type":"expect_outbound","label":"session.fork:1","frame":{"type":"session.fork","sessionId":"093127f0-d3a7-42f8-938e-b1162927a0ea","options":{"dir":"/tmp/claude-replay-thread_merge_back_siblings","upToMessageId":"1fc21da3-d746-4ed9-9a01-47a5bced6ad7"}}} +{"type":"expect_outbound","label":"session.fork:1","frame":{"type":"session.fork","sessionId":"093127f0-d3a7-42f8-938e-b1162927a0ea","options":{"upToMessageId":"1fc21da3-d746-4ed9-9a01-47a5bced6ad7"}}} {"type":"emit_inbound","label":"session.forked:1","frame":{"type":"session.forked","sessionId":"aeec447f-87e5-4874-8fe7-7f937f7c3311"}} {"type":"expect_outbound","label":"query.open:fork:1","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"aeec447f-87e5-4874-8fe7-7f937f7c3311","settings":{"showThinkingSummaries":true}}}} {"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Remember the fork-local marker merge-sibling-first-6V2J. Respond with exactly: first merge sibling stored"},"parent_tool_use_id":null}}} @@ -19,7 +19,7 @@ {"type":"emit_inbound","label":"rate_limit_event","frame":{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"},"uuid":"3b7a92ea-d3b5-47b8-94df-b214af9ccd75","session_id":"aeec447f-87e5-4874-8fe7-7f937f7c3311"}} {"type":"emit_inbound","label":"result","frame":{"type":"result","subtype":"success","is_error":false,"api_error_status":null,"duration_ms":2344,"duration_api_ms":1855,"ttft_ms":1992,"num_turns":1,"result":"first merge sibling stored","stop_reason":"end_turn","session_id":"aeec447f-87e5-4874-8fe7-7f937f7c3311","total_cost_usd":0.005865,"usage":{"input_tokens":3,"cache_creation_input_tokens":0,"cache_read_input_tokens":19120,"output_tokens":8,"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":3,"output_tokens":8,"cache_read_input_tokens":19120,"cache_creation_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-sonnet-4-6":{"inputTokens":3,"outputTokens":8,"cacheReadInputTokens":19120,"cacheCreationInputTokens":0,"webSearchRequests":0,"costUSD":0.005865,"contextWindow":200000,"maxOutputTokens":32000}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","uuid":"64da0416-b03b-4e9e-9ae9-9c85eb8ac0ef"}} {"type":"runtime_exit","status":"success"} -{"type":"expect_outbound","label":"session.fork:2","frame":{"type":"session.fork","sessionId":"093127f0-d3a7-42f8-938e-b1162927a0ea","options":{"dir":"/tmp/claude-replay-thread_merge_back_siblings","upToMessageId":"1fc21da3-d746-4ed9-9a01-47a5bced6ad7"}}} +{"type":"expect_outbound","label":"session.fork:2","frame":{"type":"session.fork","sessionId":"093127f0-d3a7-42f8-938e-b1162927a0ea","options":{"upToMessageId":"1fc21da3-d746-4ed9-9a01-47a5bced6ad7"}}} {"type":"emit_inbound","label":"session.forked:2","frame":{"type":"session.forked","sessionId":"f85cf945-d406-4573-b2ae-0e799d9a9365"}} {"type":"expect_outbound","label":"query.open:fork:2","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"resume":"f85cf945-d406-4573-b2ae-0e799d9a9365","settings":{"showThinkingSummaries":true}}}} {"type":"expect_outbound","label":"prompt.offer:3","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Remember the fork-local marker merge-sibling-second-9X5B. Respond with exactly: second merge sibling stored"},"parent_tool_use_id":null}}} From 8030067470b22e9aee2aa4c2e6cfa80485b9ed9b Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:06:11 +0100 Subject: [PATCH 022/436] fix(web): snooze times read naturally in context menus (#24945) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- apps/desktop/src/electron/ElectronMenu.ts | 5 ++++- apps/web/src/components/Sidebar.tsx | 3 ++- apps/web/src/components/threadActionMenu.logic.ts | 3 ++- apps/web/src/contextMenuFallback.test.ts | 8 ++++++++ apps/web/src/contextMenuFallback.ts | 11 +++++++++++ packages/contracts/src/ipc.ts | 3 +++ 6 files changed, 30 insertions(+), 3 deletions(-) diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index d4338b45e280..4ff3df6bf10f 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -75,7 +75,10 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM const normalizedItem: ContextMenuItem = { id: sourceItem.id, - label: sourceItem.label, + label: + typeof sourceItem.detail === "string" && sourceItem.detail.length > 0 + ? `${sourceItem.label} (${sourceItem.detail})` + : sourceItem.label, destructive: sourceItem.destructive === true, disabled: sourceItem.disabled === true, ...(sourceItem.separatorBefore === true ? { separatorBefore: true } : {}), diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index fb9e5d1da230..8fa58d8456f7 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2346,7 +2346,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve children: [ ...snoozePresets.map((preset) => ({ id: `snooze:${preset.id}`, - label: `${preset.label} (${preset.whenLabel})`, + label: preset.label, + detail: preset.whenLabel, disabled: !canOperateThreads(selectedThreads), })), { diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts index 36913c70c52b..1e3eddd0b938 100644 --- a/apps/web/src/components/threadActionMenu.logic.ts +++ b/apps/web/src/components/threadActionMenu.logic.ts @@ -155,7 +155,8 @@ export function buildThreadActionMenuItems( children: [ ...state.snoozePresets.map((preset) => ({ id: `snooze:${preset.id}` as const, - label: `${preset.label} (${preset.whenLabel})`, + label: preset.label, + detail: preset.whenLabel, })), { id: "snooze:custom" as const, diff --git a/apps/web/src/contextMenuFallback.test.ts b/apps/web/src/contextMenuFallback.test.ts index 3c7e6b742fe4..36369d40831b 100644 --- a/apps/web/src/contextMenuFallback.test.ts +++ b/apps/web/src/contextMenuFallback.test.ts @@ -237,4 +237,12 @@ describe("showContextMenuFallback", () => { await expect(selectionPromise).resolves.toBe("rename"); }); + + it("shows an item's detail beside its label and reads both to screen readers", () => { + void showContextMenuFallback([{ id: "snooze:hour", label: "In 1 hour", detail: "3:00 PM" }]); + const button = findButton("In 1 hour"); + + expect(button?.textContent).toBe("In 1 hour3:00 PM"); + expect(button?.attributes.get("aria-label")).toBe("In 1 hour, 3:00 PM"); + }); }); diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index a3e760ddc58a..55041deb60df 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -477,6 +477,17 @@ export function showContextMenuFallback( label.textContent = item.label; button.appendChild(label); + if (item.detail) { + // The comma gives screen readers a pause between label and detail. + button.setAttribute("aria-label", `${item.label}, ${item.detail}`); + const detail = document.createElement("span"); + detail.className = "ms-auto shrink-0 ps-4 text-muted-foreground text-xs"; + detail.style.cssText = + "margin-inline-start:auto;flex-shrink:0;padding-inline-start:1rem;color:var(--contrast-muted-foreground);font-size:0.75rem;"; + detail.textContent = item.detail; + button.appendChild(detail); + } + if (hasChildren) { button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false"); diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 29be3d6d0219..39f96754a636 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -24,6 +24,7 @@ import type { export interface ContextMenuItem { id: T; label: string; + detail?: string; destructive?: boolean; disabled?: boolean; header?: boolean; @@ -40,6 +41,7 @@ export type QuitShortcutHintEvent = export interface ContextMenuItemSchemaType { readonly id: string; readonly label: string; + readonly detail?: string; readonly destructive?: boolean; readonly disabled?: boolean; readonly header?: boolean; @@ -52,6 +54,7 @@ export interface ContextMenuItemSchemaType { export const ContextMenuItemSchema: Schema.Codec = Schema.Struct({ id: Schema.String, label: Schema.String, + detail: Schema.optionalKey(Schema.String), destructive: Schema.optionalKey(Schema.Boolean), disabled: Schema.optionalKey(Schema.Boolean), header: Schema.optionalKey(Schema.Boolean), From dea84724384fcc68ef802e7db8440d9abaf0ef26 Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:06:30 +0100 Subject: [PATCH 023/436] feat(web): label chips show the label's description on hover (#28732) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../pullRequest/PullRequestSummaryTab.tsx | 1 + .../pullRequest/pullRequestPresentation.tsx | 15 ++++++++-- packages/contracts/src/pullRequest.ts | 1 + .../ForgejoSourceControlProvider.test.ts | 9 +++++- .../src/server/forgejoPullRequestJson.ts | 6 +++- .../src/server/GitHubPullRequestApi.test.ts | 13 ++++++-- .../src/server/gitHubPullRequestJson.ts | 5 +++- .../src/server/pullRequestListings.graphql | 1 + .../src/server/pullRequestListings.graphql.ts | 8 +++-- .../src/server/pullRequestReads.graphql | 1 + .../src/server/pullRequestReads.graphql.ts | 30 +++++++++---------- 11 files changed, 64 insertions(+), 26 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 21a444cd2737..58be7cfb2948 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -901,6 +901,7 @@ export function PullRequestSummaryTab({ label={label} size="default" className="max-w-48" + focusable /> )) )} diff --git a/apps/web/src/components/pullRequest/pullRequestPresentation.tsx b/apps/web/src/components/pullRequest/pullRequestPresentation.tsx index 3f1b6d499ce4..d211c54bbbd1 100644 --- a/apps/web/src/components/pullRequest/pullRequestPresentation.tsx +++ b/apps/web/src/components/pullRequest/pullRequestPresentation.tsx @@ -40,25 +40,36 @@ export function PullRequestLabelChip({ label, size = "sm", className, + focusable = false, children, }: { - label: Pick; + label: Pick; size?: "sm" | "default"; className?: string; + focusable?: boolean; children?: ReactNode; }) { const color = pullRequestLabelColor(label.color); - return ( + const badge = ( {label.name} + {label.description ? : {label.description} : null} {children} ); + if (!label.description) return badge; + return ( + + + {label.description} + + ); } function reviewDecisionPresentation(decision: PullRequestReviewDecision) { diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index fd449585180b..0e66710c71f6 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -89,6 +89,7 @@ export type PullRequestActor = typeof PullRequestActor.Type; export const PullRequestLabel = Schema.Struct({ name: TrimmedNonEmptyString, color: Schema.NullOr(Schema.String), + description: Schema.optional(Schema.NullOr(Schema.String)), }); export type PullRequestLabel = typeof PullRequestLabel.Type; diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts index cd5e9fb2832d..3ee3cd47eb5c 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts @@ -573,7 +573,10 @@ it.effect.each([ updated_at: "2026-09-16T00:00:00Z", closed_at: null, merged_at: null, - labels: [], + labels: [ + { id: 1, name: "bug", color: "ee0701", description: "Something is broken" }, + { id: 2, name: "triage", color: "c5def5", description: "" }, + ], }; const requests: string[] = []; return Effect.gen(function* () { @@ -603,6 +606,10 @@ it.effect.each([ const detail = yield* provider.getChangeRequest(input); assert.strictEqual(list.items.length, 1); assert.strictEqual(detail.headSha, "head"); + assert.deepStrictEqual(detail.labels, [ + { name: "bug", color: "ee0701", description: "Something is broken" }, + { name: "triage", color: "c5def5", description: null }, + ]); for (const result of [list.items[0]!, summary, detail]) { assert.strictEqual(result.mergeability, mergeability); assert.strictEqual(result.isDraft, isDraft); diff --git a/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts b/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts index d06518a0674d..38ddae9ad40f 100644 --- a/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts +++ b/packages/source-control-forgejo/src/server/forgejoPullRequestJson.ts @@ -147,7 +147,11 @@ export function forgejoChangeRequest(pr: typeof ForgejoPullRequest.Type) { closedAt: pr.closed_at === null ? null : toIsoUtc(pr.closed_at), mergedAt: pr.merged_at === null ? null : toIsoUtc(pr.merged_at), reviewRequestLogins: (pr.requested_reviewers ?? []).map((user) => user.login), - labels: (pr.labels ?? []).map((label) => ({ name: label.name, color: label.color ?? null })), + labels: (pr.labels ?? []).map((label) => ({ + name: label.name, + color: label.color ?? null, + description: label.description || null, + })), } satisfies ProviderChangeRequest; } diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 68edb5006425..13d3b9adc525 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -475,7 +475,7 @@ function searchItem(number: number, repository: string, updatedAt: string) { updatedAt, repository: { nameWithOwner: repository }, reviewRequests: { nodes: [{ requestedReviewer: { __typename: "User", login: "hubot" } }] }, - labels: { nodes: [{ name: "bug", color: "ff0000" }] }, + labels: { nodes: [{ name: "bug", color: "ff0000", description: "Something is broken" }] }, }; } @@ -1612,6 +1612,9 @@ layer("GitHubPullRequestApi.layer", (it) => { [0, 0], ], ); + assert.deepStrictEqual(batch.items[0]?.labels, [ + { name: "bug", color: "ff0000", description: "Something is broken" }, + ]); assert.isFalse(batch.truncated); }), ); @@ -3513,7 +3516,9 @@ layer("GitHubPullRequestApi.layer", (it) => { }, ], }, - labels: { nodes: [{ name: "bug", color: "ff0000" }] }, + labels: { + nodes: [{ name: "bug", color: "ff0000", description: "Something is broken" }], + }, commits: { nodes: [ { @@ -3564,7 +3569,9 @@ layer("GitHubPullRequestApi.layer", (it) => { avatarUrl: "https://avatars.githubusercontent.com/t/1", }, ]); - expect(detail.labels).toEqual([{ name: "bug", color: "ff0000" }]); + expect(detail.labels).toEqual([ + { name: "bug", color: "ff0000", description: "Something is broken" }, + ]); expect(detail.checks).toHaveLength(2); expect(detail.checksState).toBe("failing"); }), diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index f3cb11012e73..44f33caa3be3 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -113,6 +113,7 @@ interface ListItemFields { interface LabelFields { readonly name: string; readonly color?: string | null | undefined; + readonly description?: string | null | undefined; } interface ReviewRequestFields { @@ -546,7 +547,9 @@ function toReviewDecision(value: string | null | undefined): PullRequestReviewDe function toLabels(raw: ReadonlyArray | undefined): ReadonlyArray { return (raw ?? []).flatMap((label) => { const name = trimmed(label.name); - return name === null ? [] : [{ name, color: trimmed(label.color) }]; + return name === null + ? [] + : [{ name, color: trimmed(label.color), description: trimmed(label.description) }]; }); } diff --git a/packages/source-control-github/src/server/pullRequestListings.graphql b/packages/source-control-github/src/server/pullRequestListings.graphql index f6bb42405c3d..785f313bcb2f 100644 --- a/packages/source-control-github/src/server/pullRequestListings.graphql +++ b/packages/source-control-github/src/server/pullRequestListings.graphql @@ -67,6 +67,7 @@ fragment PullRequestRow on PullRequest { nodes { name color + description } } # GitHub's rollup for the head commit, one enum, rather than the whole check list: measured at a diff --git a/packages/source-control-github/src/server/pullRequestListings.graphql.ts b/packages/source-control-github/src/server/pullRequestListings.graphql.ts index e2ac98f83bfd..5f11931a3488 100644 --- a/packages/source-control-github/src/server/pullRequestListings.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestListings.graphql.ts @@ -121,7 +121,9 @@ export const Label = Schema.Struct({ /** Identifies the label name. */ name: Schema.String, /** Identifies the label color. */ - color: Schema.String + color: Schema.String, + /** A brief description of this label. */ + description: Schema.NullOr(Schema.String) }) export interface Label extends Schema.Struct.Type {} @@ -268,7 +270,7 @@ export const PullRequestSearch = GraphQL.query("PullRequestSearch", { { name: "search", body: ["(query:$", "q", " type:ISSUE first:$", "first", " after:$", "after", "){pageInfo{hasNextPage endCursor}nodes{__typename...", "PullRequestRow", "}}"] } ], fragments: [ - { name: "PullRequestRow", body: ["on PullRequest{stack@include(if:$", "stacks", "){number size baseRefName}stackEntry@include(if:$", "stacks", "){position}number title url author{__typename login avatarUrl...on User{name}}headRefName baseRefName state isDraft mergeable reviewDecision latestReviews(first:20){nodes{state isMinimized author{__typename login}}}additions@include(if:$", "stats", ")deletions@include(if:$", "stats", ")createdAt updatedAt mergedAt repository{nameWithOwner}reviewRequests(first:20){nodes{requestedReviewer{__typename...on User{login}...on Team{slug}}}}labels(first:20){nodes{name color}}commits(last:1){nodes{commit{statusCheckRollup{state}}}}}"] } + { name: "PullRequestRow", body: ["on PullRequest{stack@include(if:$", "stacks", "){number size baseRefName}stackEntry@include(if:$", "stacks", "){position}number title url author{__typename login avatarUrl...on User{name}}headRefName baseRefName state isDraft mergeable reviewDecision latestReviews(first:20){nodes{state isMinimized author{__typename login}}}additions@include(if:$", "stats", ")deletions@include(if:$", "stats", ")createdAt updatedAt mergedAt repository{nameWithOwner}reviewRequests(first:20){nodes{requestedReviewer{__typename...on User{login}...on Team{slug}}}}labels(first:20){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{state}}}}}"] } ] }, variables: { @@ -320,7 +322,7 @@ export const PullRequestList = GraphQL.query("PullRequestList", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequests(first:$", "first", " after:$", "after", " states:$", "states", " orderBy:{field:CREATED_AT direction:DESC}){pageInfo{hasNextPage endCursor}nodes{...", "PullRequestRow", "}}}"] } ], fragments: [ - { name: "PullRequestRow", body: ["on PullRequest{stack@include(if:$", "stacks", "){number size baseRefName}stackEntry@include(if:$", "stacks", "){position}number title url author{__typename login avatarUrl...on User{name}}headRefName baseRefName state isDraft mergeable reviewDecision latestReviews(first:20){nodes{state isMinimized author{__typename login}}}additions@include(if:$", "stats", ")deletions@include(if:$", "stats", ")createdAt updatedAt mergedAt repository{nameWithOwner}reviewRequests(first:20){nodes{requestedReviewer{__typename...on User{login}...on Team{slug}}}}labels(first:20){nodes{name color}}commits(last:1){nodes{commit{statusCheckRollup{state}}}}}"] } + { name: "PullRequestRow", body: ["on PullRequest{stack@include(if:$", "stacks", "){number size baseRefName}stackEntry@include(if:$", "stacks", "){position}number title url author{__typename login avatarUrl...on User{name}}headRefName baseRefName state isDraft mergeable reviewDecision latestReviews(first:20){nodes{state isMinimized author{__typename login}}}additions@include(if:$", "stats", ")deletions@include(if:$", "stats", ")createdAt updatedAt mergedAt repository{nameWithOwner}reviewRequests(first:20){nodes{requestedReviewer{__typename...on User{login}...on Team{slug}}}}labels(first:20){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{state}}}}}"] } ] }, variables: { diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index ef40a4ab46bc..96588a2a5872 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -144,6 +144,7 @@ query PullRequestCore( nodes { name color + description } } commits(last: 1) { diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index 0a0f1aec68a3..ebb43f6d7c75 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -340,7 +340,9 @@ export const PullRequestCoreRepositoryPullRequestLabelsNodesLabel = Schema.Struc /** Identifies the label name. */ name: Schema.String, /** Identifies the label color. */ - color: Schema.String + color: Schema.String, + /** A brief description of this label. */ + description: Schema.NullOr(Schema.String) }) export interface PullRequestCoreRepositoryPullRequestLabelsNodesLabel extends Schema.Struct.Type {} @@ -503,7 +505,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "requestedReviewers", body: "Int!" } ], selections: [ - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } @@ -1227,23 +1229,12 @@ export declare namespace ReviewerCandidates { export type Result = typeof ReviewerCandidates.result.Type } -/** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */ -export const RepositoryLabelsNodesLabel = Schema.Struct({ - /** Identifies the label name. */ - name: Schema.String, - /** Identifies the label color. */ - color: Schema.String, - /** A brief description of this label. */ - description: Schema.NullOr(Schema.String) -}) -export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type {} - /** The connection type for Label. */ export const LabelCandidatesRepositoryLabelsLabelConnection = Schema.Struct({ /** Information to aid in pagination. */ pageInfo: AssignableUsersPageInfoPageInfo, /** A list of nodes. */ - nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel))) + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCoreRepositoryPullRequestLabelsNodesLabel))) }) export interface LabelCandidatesRepositoryLabelsLabelConnection extends Schema.Struct.Type {} @@ -1305,12 +1296,21 @@ export declare namespace LabelCandidates { export type Result = typeof LabelCandidates.result.Type } +/** A label for categorizing Issues, Pull Requests, Milestones, or Discussions with a given Repository. */ +export const RepositoryLabelsNodesLabel = Schema.Struct({ + /** Identifies the label name. */ + name: Schema.String, + /** Identifies the label color. */ + color: Schema.String +}) +export interface RepositoryLabelsNodesLabel extends Schema.Struct.Type {} + /** The connection type for Label. */ export const RepositoryLabelsRepositoryLabelsLabelConnection = Schema.Struct({ /** Information to aid in pagination. */ pageInfo: AssignableUsersPageInfoPageInfo, /** A list of nodes. */ - nodes: Schema.NullOr(Schema.Array(Schema.NullOr(PullRequestCoreRepositoryPullRequestLabelsNodesLabel))) + nodes: Schema.NullOr(Schema.Array(Schema.NullOr(RepositoryLabelsNodesLabel))) }) export interface RepositoryLabelsRepositoryLabelsLabelConnection extends Schema.Struct.Type {} From b6d30973790aad715218c9d80e65263b62c59255 Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:06:47 +0100 Subject: [PATCH 024/436] feat(web): composer strip names the worktree folder (#28459) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- apps/web/src/components/BranchToolbar.logic.test.ts | 11 +++++++++++ apps/web/src/components/BranchToolbar.logic.ts | 2 +- .../src/components/BranchToolbarEnvModeSelector.tsx | 3 ++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index 8b2222c4f74a..c80d3cbe05f7 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -8,6 +8,7 @@ import { resolveEffectiveEnvMode, resolveBranchToolbarPrBranch, resolveLocalCheckoutBranchMismatch, + resolveLockedWorkspaceLabel, sanitizeNewRefName, shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; @@ -92,6 +93,16 @@ describe("resolveEffectiveEnvMode", () => { }); }); +describe("resolveLockedWorkspaceLabel", () => { + it.each([ + ["/home/me/.t3/worktrees/app/t3-ff466c42", "t3-ff466c42"], + ["/home/me/.t3/worktrees/app/t3-ff466c42/", "t3-ff466c42"], + ["C:\\Users\\me\\worktrees\\feature-x", "feature-x"], + ])("names the worktree at %s", (path, label) => { + expect(resolveLockedWorkspaceLabel(path, "worktree")).toBe(label); + }); +}); + describe("deriveLocalBranchNameFromRemoteRef", () => { it("supports remote names that contain slashes", () => { expect(deriveLocalBranchNameFromRemoteRef("my-org/upstream/feature/demo")).toBe( diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index a967c3171fbd..018422f1fdab 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -107,7 +107,7 @@ export function resolveLockedWorkspaceLabel( activeWorktreePath: string | null, effectiveEnvMode: EnvMode, ): string { - if (activeWorktreePath) return "Worktree"; + if (activeWorktreePath) return activeWorktreePath.split(/[\\/]/).findLast(Boolean) ?? "Worktree"; return effectiveEnvMode === "worktree" ? resolveEnvModeLabel("worktree") : "Local checkout"; } diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx index ca511de43642..e9ca7d3f7c94 100644 --- a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -97,7 +97,8 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe {forceNewWorktree ? "Each model starts in its own worktree." - : resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode)} + : (activeWorktreePath ?? + resolveLockedWorkspaceLabel(activeWorktreePath, effectiveEnvMode))} ); From 362ef9a88a18b7f692864409c35c15cc28d7a09e Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Wed, 11 Nov 2026 08:07:05 +0100 Subject: [PATCH 025/436] feat(gitlab): revert a merged merge request (#30556) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../src/server/GitLabPullRequestCli.test.ts | 180 ++++++++++++++++++ .../src/server/GitLabPullRequestCli.ts | 128 +++++++++++++ .../server/GitLabPullRequestProvider.test.ts | 1 + .../src/server/GitLabPullRequestProvider.ts | 2 + .../src/server/gitLabMergeRequestJson.ts | 31 +++ .../src/shared/definition.ts | 1 + 6 files changed, 343 insertions(+) diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index 8c481399d78e..550fb3cac9d4 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -87,6 +87,10 @@ function mergeRequestJson(overrides: Record): string { }); } +function commitJson(id: string) { + return { id, title: "Commit", committed_date: "2026-07-01T00:00:00Z" }; +} + function sourceBranchJson(overrides: Record): string { return JSON.stringify({ data: { @@ -871,6 +875,182 @@ layer("GitLabPullRequestCli.layer", (it) => { }), ); + it.effect("reverts a merged merge request onto a new branch and opens a merge request", () => + Effect.gen(function* () { + const mergeCommit = "dac72fa101758a44b0068a23666559920a74478f"; + mockedExecute + .mockReturnValueOnce( + Effect.succeed( + output( + mergeRequestJson({ + state: "merged", + merge_commit_sha: mergeCommit, + squash_commit_sha: "cb2d9f660ebe946e5056ae98993db5ea72b9bad1", + }), + ), + ), + ) + .mockReturnValue(Effect.succeed(output("{}"))); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + yield* cli.runMergeRequestAction({ + cwd: "/w", + repository: "acme/web", + number: 7, + action: "revert", + }); + + expect( + mockedExecute.mock.calls.map(([input]) => [ + input.args[1], + input.stdin && JSON.parse(input.stdin), + ]), + ).toEqual([ + ["projects/acme%2Fweb/merge_requests/7", undefined], + ["projects/acme%2Fweb/repository/branches", { branch: "revert-dac72fa1", ref: "main" }], + [ + `projects/acme%2Fweb/repository/commits/${mergeCommit}/revert`, + { branch: "revert-dac72fa1" }, + ], + [ + "projects/acme%2Fweb/merge_requests", + { + source_branch: "revert-dac72fa1", + target_branch: "main", + title: 'Revert "Merge request 7"', + description: "This reverts merge request !7", + remove_source_branch: true, + }, + ], + ]); + }), + ); + + it.effect.each([ + ["the revert conflicts", "/revert", "Failure"], + ["opening the merge request fails", "/merge_requests", "Failure"], + ["the request is interrupted", "/revert", "Interrupt"], + ] as const)("deletes the revert branch when %s", ([, failingPath, outcome]) => + Effect.gen(function* () { + mockedExecute.mockImplementation(({ args, cwd }) => + args[1]?.endsWith(failingPath) && args.includes("POST") + ? outcome === "Interrupt" + ? Effect.interrupt + : Effect.fail( + new GitLabCli.GitLabCliCommandError({ + operation: "execute", + command: "glab", + cwd, + cause: new Error("GitLab rejected the write"), + }), + ) + : Effect.succeed( + output( + mergeRequestJson({ + state: "merged", + merge_commit_sha: null, + squash_commit_sha: "abc12345ff", + }), + ), + ), + ); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const exit = yield* Effect.exit( + cli.runMergeRequestAction({ + cwd: "/w", + repository: "acme/web", + number: 7, + action: "revert", + }), + ); + + expect(exit._tag).toBe("Failure"); + expect(mockedExecute.mock.calls.at(-1)?.[0].args.slice(1, 4)).toEqual([ + "projects/acme%2Fweb/repository/branches/revert-abc12345", + "--method", + "DELETE", + ]); + }), + ); + + it.effect.each([ + ["reverts the sole commit of", [commitJson("1111111122")], "revert-11111111"], + [ + "refuses to revert several commits of", + [commitJson("1111111122"), commitJson("2222222233")], + "GitLabRevertUnavailableError", + ], + ] as const)("%s a fast-forward merge without squash", ([, commits, expected]) => + Effect.gen(function* () { + mockedExecute + .mockReturnValueOnce( + Effect.succeed( + output( + mergeRequestJson({ + state: "merged", + merge_commit_sha: null, + squash_commit_sha: null, + }), + ), + ), + ) + .mockReturnValueOnce(Effect.succeed(output(JSON.stringify(commits)))) + .mockReturnValue(Effect.succeed(output("{}"))); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const result = yield* Effect.result( + cli.runMergeRequestAction({ + cwd: "/w", + repository: "acme/web", + number: 7, + action: "revert", + }), + ); + + expect(argsOfCall(1)[1]).toBe("projects/acme%2Fweb/merge_requests/7/commits?per_page=2"); + if (expected === "GitLabRevertUnavailableError") { + expect(result).toMatchObject({ _tag: "Failure", failure: { _tag: expected } }); + } else { + expect(JSON.parse(callAt(2).stdin ?? "")).toEqual({ branch: expected, ref: "main" }); + } + }), + ); + + it.effect("refuses to revert a merge request that is not merged before any write", () => + Effect.gen(function* () { + mockedExecute + .mockReturnValueOnce( + Effect.succeed( + output( + mergeRequestJson({ + state: "opened", + merge_commit_sha: null, + squash_commit_sha: null, + }), + ), + ), + ) + .mockReturnValue(Effect.succeed(output(JSON.stringify([commitJson("1111111122")])))); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const result = yield* Effect.result( + cli.runMergeRequestAction({ + cwd: "/w", + repository: "acme/web", + number: 7, + action: "revert", + }), + ); + + expect(result).toMatchObject({ + _tag: "Failure", + failure: { _tag: "GitLabRevertUnavailableError", reason: "not-merged" }, + }); + expect(mockedExecute).toHaveBeenCalledTimes(1); + }), + ); + it.effect("sends a comment body over stdin, never in argv", () => Effect.gen(function* () { mockedExecute.mockReturnValueOnce(Effect.succeed(output(""))); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index c0bb3d5a8e1e..ebd506df2a65 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -43,6 +43,7 @@ import { decodeCommitDiffRefsJson, decodeCommitsJson, decodeDiffRefsJson, + decodeRevertTargetJson, decodeDiscussionsJson, decodeMaintainerEditsPermissionJson, decodeLabelNameJson, @@ -143,6 +144,26 @@ export class GitLabDiffRefsUnavailableError extends Schema.TaggedError()( + "GitLabRevertUnavailableError", + { + command: Schema.Literal("glab"), + cwd: Schema.String, + number: Schema.Int, + reason: Schema.Literals(["not-merged", "several-commits"]), + }, +) { + get detail(): string { + return this.reason === "not-merged" + ? "Only a merged merge request can be reverted." + : "This merge request landed as several commits, so there is no single commit to revert."; + } + + override get message(): string { + return `GitLab CLI failed in runMergeRequestAction: ${this.detail}`; + } +} + export class GitLabDiffCursorError extends Schema.TaggedError()( "GitLabDiffCursorError", { @@ -302,6 +323,7 @@ export type GitLabPullRequestCliError = | GitLabDiffCommitParentUnavailableError | GitLabDiffFileContentsUnavailableError | GitLabDiffRefsUnavailableError + | GitLabRevertUnavailableError | GitLabViewerUnavailableError | GitLabMutationRefusedError; @@ -989,6 +1011,7 @@ function actionArgs( case "reopen": return ["reopen"]; case "revert": + return []; case "approve-workflows": case "delete-branch": throw new Error(`GitLab merge request action ${action} is unsupported`); @@ -1342,6 +1365,110 @@ export const make = Effect.gen(function* () { }), ); + /** GitLab reverts a fast-forward merge without squash only when it landed as one commit. */ + const soleCommitSha = (input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly repository: string; + readonly number: number; + }) => + api({ + cwd: input.cwd, + host: input.host, + path: `projects/${projectPath(input.repository)}/merge_requests/${input.number}/commits?per_page=2`, + }).pipe( + Effect.flatMap((result) => { + const decoded = decodeCommitsJson(result.stdout.trim()); + if (!Result.isSuccess(decoded)) { + return Effect.fail( + new GitLabMergeRequestReadError({ + command: "glab", + cwd: input.cwd, + operation: "runMergeRequestAction", + cause: decoded.failure, + }), + ); + } + const [only, ...rest] = decoded.success; + return Effect.succeed(only !== undefined && rest.length === 0 ? only.oid : null); + }), + ); + + /** What GitLab's own Revert button does: revert onto a new branch and open a merge request. */ + const revertMergeRequest = Effect.fn("GitLabPullRequestCli.revertMergeRequest")( + function* (input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly repository: string; + readonly number: number; + }) { + const project = `projects/${projectPath(input.repository)}`; + const write = (path: string, body: object) => + api({ + cwd: input.cwd, + host: input.host, + path: `${project}/${path}`, + method: "POST", + stdin: JSON.stringify(body), + }); + const raw = yield* api({ + cwd: input.cwd, + host: input.host, + path: `${project}/merge_requests/${input.number}`, + }); + const decoded = decodeRevertTargetJson(raw.stdout.trim()); + if (!Result.isSuccess(decoded)) { + return yield* new GitLabMergeRequestReadError({ + command: "glab", + cwd: input.cwd, + operation: "runMergeRequestAction", + cause: decoded.failure, + }); + } + const target = decoded.success; + if (!target.merged) { + return yield* new GitLabRevertUnavailableError({ + command: "glab", + cwd: input.cwd, + number: input.number, + reason: "not-merged", + }); + } + const commitSha = target.commitSha ?? (yield* soleCommitSha(input)); + if (commitSha === null) { + return yield* new GitLabRevertUnavailableError({ + command: "glab", + cwd: input.cwd, + number: input.number, + reason: "several-commits", + }); + } + const branch = `revert-${commitSha.slice(0, 8)}`; + yield* write("repository/branches", { branch, ref: target.targetBranch }); + yield* Effect.andThen( + write(`repository/commits/${commitSha}/revert`, { branch }), + write("merge_requests", { + source_branch: branch, + target_branch: target.targetBranch, + title: `Revert "${target.title}"`, + description: `This reverts merge request !${input.number}`, + remove_source_branch: true, + }), + ).pipe( + // Leaving the branch behind would make every retry fail on creating it again. Runs on + // interruption too, which a cancelled request or a dropped socket causes. + Effect.onError(() => + api({ + cwd: input.cwd, + host: input.host, + path: `${project}/repository/branches/${encodeURIComponent(branch)}`, + method: "DELETE", + }).pipe(Effect.ignore), + ), + ); + }, + ); + const getDiffRefs = (input: { readonly cwd: string; readonly host?: string | undefined; @@ -2558,6 +2685,7 @@ export const make = Effect.gen(function* () { } = decoded.success; return summary; } + if (input.action === "revert") return yield* revertMergeRequest(input); const executeMr = (subcommand: string, ...flags: ReadonlyArray) => gitlab.execute({ cwd: input.cwd, diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts index 080d128ca6cf..5beb59cb3a8c 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.test.ts @@ -139,6 +139,7 @@ describe("gitLabViewerPermissions", () => { "update-branch", "enable-auto-merge", "disable-auto-merge", + "revert", "delete-branch", ], comment: true, diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index b4a6cfff6e9c..7334d93a6738 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -58,12 +58,14 @@ const UNAVAILABLE_REQUIREMENT = { * The actions `user.can_merge` answers for. Rebasing writes to the source branch rather than to * the target, so it is not literally the same permission — but GitLab reports nothing narrower, * and someone it will not let land this change has no business rewriting its branch either. + * Reverting pushes a branch to the target project, which the same permission covers. */ const MERGE_ACTIONS: ReadonlySet = new Set([ "merge", "update-branch", "enable-auto-merge", "disable-auto-merge", + "revert", ]); /** Authors may close/reopen/change draft state regardless of role; REST omits authorship. */ diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 6af07442403f..2b9d2d22f07a 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -149,6 +149,14 @@ const RawDiffRefsSchema = Schema.Struct({ diff_refs: Schema.optional(Schema.NullOr(RawDiffRefs)), }); +const RawRevertTargetSchema = Schema.Struct({ + title: Schema.String, + state: Schema.String, + target_branch: Schema.String, + merge_commit_sha: Schema.optional(Schema.NullOr(Schema.String)), + squash_commit_sha: Schema.optional(Schema.NullOr(Schema.String)), +}); + const RawCommitSchema = Schema.Struct({ id: TrimmedNonEmptyString, title: Schema.optional(Schema.NullOr(Schema.String)), @@ -564,6 +572,7 @@ const decodeMergeRequestChanges = decodeJsonResult( const decodeDiffEntry = Schema.decodeUnknownExit(RawDiffSchema); const decodeDiscussionEntry = Schema.decodeUnknownExit(RawDiscussionSchema); const decodeDiffRefs = decodeJsonResult(RawDiffRefsSchema); +const decodeRevertTarget = decodeJsonResult(RawRevertTargetSchema); const decodeViewer = decodeJsonResult(RawViewerSchema); const decodeProjectMergeSettings = decodeJsonResult(RawProjectMergeSettingsSchema); @@ -867,6 +876,28 @@ export function decodeDiffRefsJson( return Result.succeed(refs ? toDiffRefs(refs) : null); } +export interface GitLabRevertTarget { + readonly merged: boolean; + readonly title: string; + readonly targetBranch: string; + /** Null for a fast-forward merge without squash, which records neither SHA. */ + readonly commitSha: string | null; +} + +export function decodeRevertTargetJson( + raw: string, +): Result.Result { + const decoded = decodeRevertTarget(raw); + if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure); + const mr = decoded.success; + return Result.succeed({ + merged: mr.state === "merged", + title: mr.title, + targetBranch: mr.target_branch, + commitSha: trimmed(mr.merge_commit_sha) ?? trimmed(mr.squash_commit_sha), + }); +} + export function decodeNotesJson( raw: string, ): Result.Result< diff --git a/packages/source-control-gitlab/src/shared/definition.ts b/packages/source-control-gitlab/src/shared/definition.ts index 96d6f7be7200..20224eb56514 100644 --- a/packages/source-control-gitlab/src/shared/definition.ts +++ b/packages/source-control-gitlab/src/shared/definition.ts @@ -63,6 +63,7 @@ export const definition = defineSourceControl({ "update-branch", "enable-auto-merge", "disable-auto-merge", + "revert", "delete-branch", ] as const), checkoutCommand: ({ number }) => `glab mr checkout ${number}`, From 399df485a4da38ad5df6c0b8365ebccc3701e020 Mon Sep 17 00:00:00 2001 From: Bin Jamshid Date: Wed, 11 Nov 2026 11:11:29 +0400 Subject: [PATCH 026/436] fix(claude): version errors from a custom endpoint no longer say to run claude update (#34176) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 46 ++++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 45 +++++++++++++++++- apps/server/src/provider/ClaudeProvider.ts | 13 +++--- .../src/provider/Drivers/ClaudeSkills.ts | 11 +++++ 4 files changed, 106 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index b98b5d372851..c949323b91c9 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6635,9 +6635,42 @@ describe("ClaudeAdapterV2 background wake turns", () => { expected: "Claude stopped: the prompt exceeds the model's context window. Run /compact or start a new thread.", }, + ...[ + { + name: "a model version error rewritten by a custom endpoint", + baseUrl: "https://gateway.example.test/v1", + installed: "2.1.322", + expected: + "The custom API endpoint gateway.example.test reported Claude Code 2.1.280, but this session runs Claude Code 2.1.322. Running claude update will not fix this; the endpoint or a proxy behind it rewrote the version.", + }, + { name: "a model version error without a custom endpoint", installed: "2.1.322" }, + { + name: "a model version error from a Claude Code still below the required version", + baseUrl: "https://gateway.example.test/v1", + installed: "2.1.285", + }, + ].map((row) => { + const result = + "API Error: 400 Claude Code 2.1.280 does not support this model; version 2.1.290 or newer is required. Run 'claude update', or update the Claude desktop app, then try again."; + return { + ...row, + isError: true, + result, + errors: undefined, + apiErrorStatus: undefined, + terminalReason: undefined, + environment: { + CLAUDE_CONFIG_DIR: "/synthetic/no-claude-config", + ...(row.baseUrl === undefined ? {} : { ANTHROPIC_BASE_URL: row.baseUrl }), + }, + expected: row.expected ?? result, + }; + }), ])("reports terminal API error text for $name", (input) => Effect.gen(function* () { - const harness = yield* makeWakeHarness; + const harness = yield* makeWakeHarnessWithOptions( + "environment" in input ? { environment: input.environment } : undefined, + ); const now = yield* DateTime.now; yield* harness.runtime.startTurn( makeClaudeTestTurnInput({ @@ -6650,6 +6683,17 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); const apiErrorStatus = input.apiErrorStatus ?? 400; + if ("installed" in input) { + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "init", + uuid: "00000000-0000-4000-8000-000000000698", + session_id: WAKE_NATIVE_SESSION, + claude_code_version: input.installed, + }), + ); + } yield* Queue.offer( harness.sdkMessages, makeResultFrame({ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index bb914d54d1cd..829cc0dbe4be 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -84,6 +84,7 @@ import { import { AgentScope } from "@t3tools/shared/AgentScope"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model"; +import { compareSemverVersions } from "@t3tools/shared/semver"; import { CLAUDE_RESUME_COMPACTION_COMPACT_ANSWER, CLAUDE_RESUME_COMPACTION_NEVER_ANSWER, @@ -165,7 +166,9 @@ import { } from "../../provider/Drivers/ClaudeSkillDispatch.ts"; import { claudeLaunchArgDirectories, + customClaudeApiEndpointHost, discoverClaudeSkills, + readClaudeSettingsEnv, } from "../../provider/Drivers/ClaudeSkills.ts"; import { compileClaudeModelSelection, @@ -4106,6 +4109,25 @@ function gatewayCooldownResetAt( : undefined; } +const CLAUDE_UNSUPPORTED_VERSION_ERROR = + /^API Error: 400 Claude Code (\d+\.\d+\.\d+) does not support this model; version (\d+\.\d+\.\d+) or newer is required\./; + +/** The version a gateway sent in place of the session's own, when the session itself meets the requirement. */ +function claudeRewrittenVersion( + message: SDKResultMessage, + sessionVersion: string | undefined, +): string | undefined { + if (message.subtype !== "success" || message.terminal_reason !== "api_error") return undefined; + const [, reported, required] = CLAUDE_UNSUPPORTED_VERSION_ERROR.exec(message.result.trim()) ?? []; + if (reported === undefined || required === undefined || sessionVersion === undefined) { + return undefined; + } + return compareSemverVersions(reported, sessionVersion) < 0 && + compareSemverVersions(sessionVersion, required) >= 0 + ? reported + : undefined; +} + function providerFailureFromResult( message: SDKResultMessage, receivedAt: DateTime.Utc, @@ -4446,6 +4468,7 @@ interface ClaudeLiveQueryContext { receivedInit: boolean; // From system/init; feature-detects control requests such as MCP Apps. capabilities: ReadonlySet; + claudeCodeVersion: string | undefined; permissionMode: PermissionMode; stopping: boolean; readonly subagentsFromEarlierProcesses: ReadonlySet; @@ -10083,12 +10106,30 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // The CLI also labels 403 authentication_failed; show its text because login cannot grant access. const permissionDenied = message.subtype === "success" && message.api_error_status === 403; + const rewrittenVersion = claudeRewrittenVersion(message, liveQuery.claudeCodeVersion); + const endpointHost = + rewrittenVersion === undefined + ? undefined + : customClaudeApiEndpointHost( + (yield* readClaudeSettingsEnv( + adapterOptions.settings, + context.input.runtimePolicy.cwd ?? undefined, + adapterOptions.environment, + ).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + )).ANTHROPIC_BASE_URL ?? adapterOptions.environment.ANTHROPIC_BASE_URL, + ); + const rewrittenVersionError = + endpointHost === undefined + ? undefined + : `The custom API endpoint ${endpointHost} reported Claude Code ${rewrittenVersion}, but this session runs Claude Code ${liveQuery.claudeCodeVersion}. Running claude update will not fix this; the endpoint or a proxy behind it rewrote the version.`; const failureHint = permissionDenied ? message.result : (context.authenticationFailureMessage ?? (usageLimited ? "Claude usage limit reached. Send the message again once the limit resets." - : undefined)); + : rewrittenVersionError)); // Usage-limited /compact reports success; fail it so queued messages wait for the limit to clear. const limitedCompaction = usageLimited && message.subtype === "success" && message.local_command === "compact" @@ -11077,6 +11118,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( openedPermissionMode: queryOptions.permissionMode, receivedInit: false, capabilities: new Set(), + claudeCodeVersion: undefined, permissionMode: queryOptions.permissionMode, stopping: false, handedOffSubagents: new Set(), @@ -11117,6 +11159,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message.permissionMode ?? context.openedPermissionMode; context.receivedInit = true; context.capabilities = new Set(message.capabilities ?? []); + context.claudeCodeVersion = message.claude_code_version; } if ( message.type === "system" && diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 72221ff3187b..47eaf7aa1486 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -45,7 +45,11 @@ import { hasClaudeManagedMcpConfig, makeClaudeEnvironment, } from "./Drivers/ClaudeHome.ts"; -import { discoverClaudeSkills, readClaudeSettingsEnv } from "./Drivers/ClaudeSkills.ts"; +import { + customClaudeApiEndpointHost, + discoverClaudeSkills, + readClaudeSettingsEnv, +} from "./Drivers/ClaudeSkills.ts"; import type { ProviderWorkspaceSnapshot } from "@t3tools/provider-core/server/driver"; import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; import { @@ -671,12 +675,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( const baseUrl = (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ?? resolvedEnvironment.ANTHROPIC_BASE_URL; - const endpoint = URL.parse(baseUrl?.trim() ?? ""); - const customApiEndpoint = - endpoint !== null && - (endpoint.protocol === "http:" || endpoint.protocol === "https:") && - endpoint.hostname !== "" && - endpoint.hostname !== "api.anthropic.com"; + const customApiEndpoint = customClaudeApiEndpointHost(baseUrl) !== undefined; if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") { const path = yield* Path.Path; const configDir = (yield* makeClaudeEnvironment(claudeSettings, resolvedEnvironment)) diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index 0d62109cce82..ada8a39e1ed5 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -472,6 +472,17 @@ export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function return settingsEnv; }); +/** The host of an `ANTHROPIC_BASE_URL` that is not Anthropic's own API. */ +export function customClaudeApiEndpointHost(baseUrl: string | undefined): string | undefined { + const endpoint = URL.parse(baseUrl?.trim() ?? ""); + return endpoint !== null && + (endpoint.protocol === "http:" || endpoint.protocol === "https:") && + endpoint.hostname !== "" && + endpoint.hostname !== "api.anthropic.com" + ? endpoint.hostname + : undefined; +} + // Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value. export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray { const directories: string[] = []; From 8cbc95923a7168b3ee85c9dbeb224f57ca48f820 Mon Sep 17 00:00:00 2001 From: "M.Umais Adeed" <165276382+Umais-Adeed@users.noreply.github.com> Date: Wed, 11 Nov 2026 12:11:35 +0500 Subject: [PATCH 027/436] fix(web): files marked Viewed stay folded when a pull request's Code tab opens again (#34168) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- .../PullRequestCodeTab.browser.test.tsx | 59 ++++++++++++++++++- .../pullRequest/PullRequestCodeTab.tsx | 57 +++++++++--------- .../pullRequest/pullRequestDiff.logic.test.ts | 29 ++++++--- .../pullRequest/pullRequestDiff.logic.ts | 31 +++++----- 4 files changed, 125 insertions(+), 51 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 96ef692c4aa1..b06f3d117b9b 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -56,12 +56,43 @@ const { diffAtom, pagedDiffAtom } = await vi.hoisted(async () => { }; }); -const mocks = vi.hoisted(() => ({ paged: false, diffCommits: [] as Array })); +const mocks = vi.hoisted(() => ({ + paged: false, + diffCommits: [] as Array, + viewedPaths: null as ReadonlySet | null, + viewedListeners: new Set<() => void>(), +})); + +function deliverViewedPaths(paths: ReadonlySet | null) { + mocks.viewedPaths = paths; + for (const listener of mocks.viewedListeners) listener(); +} vi.mock(import("~/state/use-atom-command"), async (original) => ({ ...(await original()), useAtomCommand: (() => vi.fn()) as never, })); +vi.mock(import("./usePullRequestFilesViewed"), async () => { + const { useSyncExternalStore } = await import("react"); + const subscribe = (listener: () => void) => { + mocks.viewedListeners.add(listener); + return () => mocks.viewedListeners.delete(listener); + }; + return { + usePullRequestFilesViewed: () => { + const viewedPaths = useSyncExternalStore(subscribe, () => mocks.viewedPaths); + return { + enabled: viewedPaths !== null, + isViewed: (path: string) => viewedPaths?.has(path) === true, + isStale: () => false, + setViewed: () => {}, + truncated: false, + error: null, + refresh: () => {}, + }; + }, + }; +}); vi.mock(import("~/state/pullRequests"), async (original) => { const actual = await original(); return { @@ -136,6 +167,8 @@ function setup({ paged }: { paged: boolean }) { __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); mocks.paged = paged; mocks.diffCommits = []; + mocks.viewedPaths = null; + mocks.viewedListeners.clear(); } const tab = ( @@ -174,6 +207,30 @@ it("keeps the diff after a refresh that brings back the same page", async () => await expect.element(screen.getByText("1 file", { exact: true })).toBeVisible(); }); +// regression: #13279 a Viewed answer that lands after a link reveals a file must not fold it +it("keeps a revealed file open when its Viewed mark loads afterwards", async () => { + setup({ paged: false }); + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + using _preferences = { + [Symbol.dispose]() { + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }, + }; + mocks.viewedPaths = new Set(); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render(tab(0, { path: "a.ts", nonce: 1 }), { container }); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); + + deliverViewedPaths(new Set(["a.ts"])); + await expect.element(screen.getByRole("checkbox", { name: "Viewed" })).toBeChecked(); + + await expect + .element(screen.getByRole("button", { name: "Collapse diff" })) + .toHaveAttribute("aria-expanded", "true"); + await expect.element(screen.getByText("three()", { exact: true })).toBeVisible(); +}); + function pagedContainer() { const container = document.createElement("div"); container.className = "flex h-[500px] w-[900px]"; diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index e25725023ae2..68525756e2d9 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -123,8 +123,9 @@ import { getFileViewedRange, isFileDiffCollapsed, isLineInFileDiff, - toggleFileDiffFoldForViewed, + withFileDiffFold, type DiffFoldOverride, + type FileDiffFoldChoices, } from "./pullRequestDiff.logic"; import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation"; import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState"; @@ -385,7 +386,7 @@ function PullRequestCodeTab({ diffLayout: settings.diffLayout, wordWrap: settings.wordWrap, })); - const [toggledFiles, setToggledFiles] = useState>(() => new Set()); + const [foldChoices, setFoldChoices] = useState(() => new Map()); const [lastViewedFileKey, setLastViewedFileKey] = useState(null); const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); const [foldOverride, setFoldOverride] = useState(null); @@ -430,7 +431,7 @@ function PullRequestCodeTab({ setLastViewedFileKey(null); setDraft(null); setSelectedLines(null); - setToggledFiles(new Set()); + setFoldChoices(new Map()); setFoldOverride(null); setVisibleCommitCount(COMMIT_PAGE_SIZE); setOrphansOpen(false); @@ -740,9 +741,17 @@ function PullRequestCodeTab({
); + // A stale mark means the file changed since it was viewed; Fold all and Expand all outrank marks. + const foldsAsViewed = (path: string) => + foldOverride === null && filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); const items: CodeViewDiffItem[] = annotatedFiles.map( ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => { - const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles); + const collapsed = isFileDiffCollapsed( + fileKey, + effectiveFoldOverride, + foldChoices, + foldsAsViewed(path), + ); const viewedMark = filesViewedEnabled ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` : ""; @@ -783,13 +792,17 @@ function PullRequestCodeTab({ ); }; - const toggleFile = (fileKey: string) => - setToggledFiles((current) => { - const next = new Set(current); - if (next.has(fileKey)) next.delete(fileKey); - else next.add(fileKey); - return next; - }); + const toggleFile = (fileKey: string) => { + const path = annotatedFiles.find((file) => file.fileKey === fileKey)?.path; + const viewed = path !== undefined && foldsAsViewed(path); + setFoldChoices((current) => + withFileDiffFold( + current, + fileKey, + !isFileDiffCollapsed(fileKey, effectiveFoldOverride, current, viewed), + ), + ); + }; const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { const range = getFileViewedRange( @@ -799,12 +812,8 @@ function PullRequestCodeTab({ ); setLastViewedFileKey(fileKey); for (const file of range) setViewed(file.path, viewed); - setToggledFiles((current) => - range.reduce( - (next, file) => - toggleFileDiffFoldForViewed(file.fileKey, viewed, effectiveFoldOverride, next), - current, - ), + setFoldChoices((current) => + range.reduce((next, file) => withFileDiffFold(next, file.fileKey, viewed), current), ); }; const fileViewedToggle = { @@ -817,19 +826,15 @@ function PullRequestCodeTab({ const revealFile = (path: string, range?: SelectedLineRange) => { const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); if (item === undefined) return; - // Unfold only: a second reveal before the unfold renders must not fold the file again. - if (item.collapsed === true) { - setToggledFiles((current) => - toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current), - ); - } + // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. + setFoldChoices((current) => withFileDiffFold(current, item.id, false)); if (range) setSelectedLines({ id: item.id, range }); codeViewReveal.request(item.id, range); }; const toggleAllFiles = () => { setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded"); - setToggledFiles(new Set()); + setFoldChoices(new Map()); }; const orderedCommits = // GitLab preserves UTC offsets, so compare instants. @@ -971,9 +976,7 @@ function PullRequestCodeTab({ onPostRender: codeViewReveal.flush, // Find may repeat requests before render; only unfold, never toggle. onRevealSearchMatch: (item: CodeViewItem) => - setToggledFiles((current) => - toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current), - ), + setFoldChoices((current) => withFileDiffFold(current, item.id, false)), }; const runThreadCommand = async ( diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts index 552fa748f07f..47f309b3e32c 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.test.ts @@ -5,7 +5,7 @@ import { getFileViewedRange, isFileDiffCollapsed, isLineInFileDiff, - toggleFileDiffFoldForViewed, + withFileDiffFold, } from "./pullRequestDiff.logic"; function fileWithHunks( @@ -43,16 +43,29 @@ describe("isLineInFileDiff", () => { describe("isFileDiffCollapsed", () => { // regression: #9174 diffs now expand by default; a reader's fold must survive new slices it("keeps a file the reader folded closed as the next slice arrives", () => { - const toggled = new Set(["b.ts"]); - expect(isFileDiffCollapsed("b.ts", null, toggled)).toBe(true); - expect(isFileDiffCollapsed("c.ts", null, toggled)).toBe(false); + const choices = new Map([["b.ts", true]]); + expect(isFileDiffCollapsed("b.ts", "expanded", choices)).toBe(true); + expect(isFileDiffCollapsed("c.ts", "expanded", choices)).toBe(false); + }); + + it("folds a file marked Viewed when the Code tab mounts again with no fold choices", () => { + expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), true)).toBe(true); + expect(isFileDiffCollapsed("a.ts", "expanded", new Map(), false)).toBe(false); + }); + + it("keeps a reader's choice when the file's Viewed mark loads later", () => { + const choices = new Map([["a.ts", false]]); + expect(isFileDiffCollapsed("a.ts", "expanded", choices, false)).toBe(false); + expect(isFileDiffCollapsed("a.ts", "expanded", choices, true)).toBe(false); }); }); -describe("toggleFileDiffFoldForViewed", () => { - it("moves against whatever the toolbar last asked for", () => { - expect([...toggleFileDiffFoldForViewed("a.ts", true, "expanded", new Set())]).toEqual(["a.ts"]); - expect(toggleFileDiffFoldForViewed("a.ts", false, "expanded", new Set()).size).toBe(0); +describe("withFileDiffFold", () => { + it("records an absolute choice and keeps the same map when nothing changes", () => { + const folded = withFileDiffFold(new Map(), "a.ts", true); + expect(folded.get("a.ts")).toBe(true); + expect(withFileDiffFold(folded, "a.ts", true)).toBe(folded); + expect(withFileDiffFold(folded, "a.ts", false).get("a.ts")).toBe(false); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts index f175c0151431..da3844e90e1b 100644 --- a/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDiff.logic.ts @@ -16,28 +16,29 @@ export function isLineInFileDiff( export type DiffFoldOverride = "expanded" | "folded" | null; -/** Keep fold choices relative to the toolbar so later pages inherit Fold all. */ +/** The reader's own fold choice per file. It is absolute, so a Viewed mark loading later keeps it. */ +export type FileDiffFoldChoices = ReadonlyMap; + +/** + * A reader's own choice wins. Otherwise the toolbar decides, and a file still marked Viewed + * starts folded. Fold all and Expand all clear the choices, so later pages follow the toolbar. + */ export function isFileDiffCollapsed( fileKey: string, foldOverride: DiffFoldOverride, - toggledFileKeys: ReadonlySet, + choices: FileDiffFoldChoices, + viewed = false, ): boolean { - const foldedByDefault = foldOverride === "folded"; - return toggledFileKeys.has(fileKey) ? !foldedByDefault : foldedByDefault; + return choices.get(fileKey) ?? (foldOverride === "folded" || viewed); } -export function toggleFileDiffFoldForViewed( +export function withFileDiffFold( + choices: FileDiffFoldChoices, fileKey: string, - viewed: boolean, - foldOverride: DiffFoldOverride, - toggledFileKeys: ReadonlySet, -): ReadonlySet { - if (isFileDiffCollapsed(fileKey, foldOverride, toggledFileKeys) === viewed) - return toggledFileKeys; - const next = new Set(toggledFileKeys); - if (next.has(fileKey)) next.delete(fileKey); - else next.add(fileKey); - return next; + collapsed: boolean, +): FileDiffFoldChoices { + if (choices.get(fileKey) === collapsed) return choices; + return new Map(choices).set(fileKey, collapsed); } export function getFileViewedRange( From 4e1be34436df1936c0eae22e4f19979d01b0cd94 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 23:12:57 -0800 Subject: [PATCH 028/436] feat(server): watched GitHub pull requests react to host events, not only the 2-minute sweep (#33548) Co-authored-by: Claude Opus 5.5 --- .../PullRequestWatchReactor.ts | 101 ++++++- .../src/orchestration-v2/runtimeLayer.test.ts | 121 ++++++++ .../src/pullRequest/PullRequestService.ts | 24 ++ .../src/server/PullRequestProvider.ts | 9 + .../src/server/GitHubPullRequestApi.ts | 3 + .../src/server/GitHubPullRequestProvider.ts | 2 + .../server/gitHubPullRequestEvents.test.ts | 195 ++++++++++++ .../src/server/gitHubPullRequestEvents.ts | 282 ++++++++++++++++++ 8 files changed, 722 insertions(+), 15 deletions(-) create mode 100644 packages/source-control-github/src/server/gitHubPullRequestEvents.test.ts create mode 100644 packages/source-control-github/src/server/gitHubPullRequestEvents.ts diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index f37a69c08ee0..6eca0cb39aa2 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -20,12 +20,14 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FiberMap from "effect/FiberMap"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; import { type ProviderChangeRequestWatchFingerprint, @@ -252,6 +254,10 @@ export const make = Effect.gen(function* () { Effect.suspend(() => reportEnd(lifeKey(target), lifeOf(target), reason)); const readFailures = new Map(); + /** The last sweep's groups, whose pull requests get host change feeds. */ + let currentGroups: ReadonlyArray = []; + // A pass reads watches and records new ones, so passes must not overlap. + const passes = Semaphore.makeUnsafe(1); const lastReads = new Map(); const threadTails = new Map< string, @@ -585,19 +591,26 @@ export const make = Effect.gen(function* () { }); }); - const sweep = Effect.gen(function* () { + /** Every watch, or with `changed`, only that pull request's after its host reported a change. */ + // The sweep and change reads each name their own span. + const pass = Effect.fnUntraced(function* (changed: string | undefined) { const threads = yield* projections.getThreadsWithPullRequests(); const targets = threads.flatMap((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).flatMap((link) => - link.watch === undefined ? [] : [{ thread, link, watch: link.watch }], + link.watch === undefined || + (changed !== undefined && threadPullRequestKeyOf(link) !== changed) + ? [] + : [{ thread, link, watch: link.watch }], ), ); - const present = new Set(targets.map(lifeKey)); - yield* Effect.forEach( - [...lives].filter(([key]) => !present.has(key)), - ([key, life]) => reportEnd(key, life, "stopped"), - { discard: true }, - ); + if (changed === undefined) { + const present = new Set(targets.map(lifeKey)); + yield* Effect.forEach( + [...lives].filter(([key]) => !present.has(key)), + ([key, life]) => reportEnd(key, life, "stopped"), + { discard: true }, + ); + } for (const target of targets) lifeOf(target); const byPullRequest = new Map>(); const ending: Array = []; @@ -616,8 +629,11 @@ export const make = Effect.gen(function* () { targets: members, fingerprint: [...new Set(members.map(snapshotFingerprint))].toSorted().join("\n"), })); - for (const cache of [readFailures, lastReads, threadTails]) { - for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key); + if (changed === undefined) { + currentGroups = groups; + for (const cache of [readFailures, lastReads, threadTails]) { + for (const key of cache.keys()) if (!byPullRequest.has(key)) cache.delete(key); + } } yield* Effect.forEach( ending, @@ -639,7 +655,24 @@ export const make = Effect.gen(function* () { yield* Effect.forEach( groups, (group) => - fingerprintOf(group).pipe( + // The host just reported a change, so a cached fingerprint may predate it. + (changed === undefined + ? Effect.void + : pullRequests.invalidate({ reference: referenceOf(group) }) + ).pipe( + Effect.andThen(fingerprintOf(group)), + Effect.tap((fingerprint) => { + const last = lastReads.get(group.key); + // Open pull request views refresh only when the host state moved. + return changed !== undefined && + fingerprint !== null && + fingerprint !== "paused" && + (last === undefined || + last.status !== fingerprint.status || + last.remarks !== fingerprint.remarks) + ? pullRequests.invalidate({ reference: referenceOf(group) }, { notifyReaders: true }) + : Effect.void; + }), Effect.flatMap((fingerprint) => fingerprint === "paused" ? Effect.void @@ -654,16 +687,54 @@ export const make = Effect.gen(function* () { ), { concurrency: "unbounded", discard: true }, ); - }).pipe( + }, passes.withPermit); + + const sweep = pass(undefined).pipe( Effect.catchCause(logFailure("pull request watch sweep failed", {})), Effect.withSpan("PullRequestWatchReactor.sweep"), ); - const start: PullRequestWatchReactor["Service"]["start"] = () => - forkParked( - sweep.pipe(Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)), Effect.asVoid), + const pullRequestOf = (group: WatchGroup) => threadPullRequestKeyOf(group.targets[0]!.link); + + const readOnChange = (pullRequest: string) => + pass(pullRequest).pipe( + Effect.catchCause(logFailure("pull request watch change read failed", { pullRequest })), + Effect.withSpan("PullRequestWatchReactor.readOnChange"), ); + const start: PullRequestWatchReactor["Service"]["start"] = Effect.fn( + "PullRequestWatchReactor.start", + )(function* () { + // One feed per pull request: the host keeps one subscription per pull request and account. + const feeds = yield* FiberMap.make(); + const follow = Effect.gen(function* () { + const wanted = new Map(currentGroups.map((group) => [pullRequestOf(group), group])); + const stale = Array.from(feeds, ([pullRequest]) => pullRequest).filter( + (pullRequest) => !wanted.has(pullRequest), + ); + yield* Effect.forEach(stale, (pullRequest) => FiberMap.remove(feeds, pullRequest), { + discard: true, + }); + for (const [pullRequest, group] of wanted) { + // An ended feed restarts here, so a host that refused it is asked again each sweep. + yield* FiberMap.run(feeds, pullRequest, { onlyIfMissing: true })( + pullRequests.changes(referenceOf(group)).pipe( + // A review sends an event per comment; those landing during a read make one more. + Stream.buffer({ capacity: 1, strategy: "sliding" }), + Stream.runForEach(() => readOnChange(pullRequest)), + ), + ); + } + }); + yield* forkParked( + sweep.pipe( + Effect.andThen(follow), + Effect.repeat(Schedule.spaced(`${SWEEP_MINUTES} minutes`)), + Effect.asVoid, + ), + ); + }); + return { start, sweep } satisfies PullRequestWatchReactor["Service"]; }); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index a49e323770cc..25ccef8c1108 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -3890,6 +3890,127 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect( + "reads a watched pull request when the host reports a change, and wakes once per change", + () => + Effect.scoped( + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-pull-request-watch-host-event"); + const projectId = ProjectId.make("pr-watch-host-event-project"); + yield* seedProject({ + projectId, + title: "Watch host events", + workspaceRoot: "/workspace/watch-host-event", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("pr-watch-host-event-create"), + threadId, + projectId, + title: "Watch host events", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const key = { host: "github.com", repository: "pingdotgg/t3code", number: 15 }; + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-host-event-start"), + threadId, + ...key, + watching: true, + link: { url: "https://github.com/pingdotgg/t3code/pull/15", source: "agent" }, + }); + + let checks: PullRequestDetail["checks"] = [ + { name: "lint", status: "pending", description: null, url: null, required: true }, + ]; + let fingerprints = 0; + const events = yield* Queue.unbounded(); + const following = yield* Deferred.make(); + const detailReads = yield* Queue.unbounded(); + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + detail: () => + Queue.offer(detailReads, undefined).pipe( + Effect.as({ + ...watchedPullRequestDetail({ + projectId, + number: 15, + at: "2026-10-02T12:00:00.000Z", + }), + headSha: "aaaaaaaaaa", + checks, + }), + ), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + // A fresh fingerprint every time, so every pass reads the detail. + watchFingerprint: () => + Effect.sync(() => ({ status: String(++fingerprints), remarks: "" })), + invalidate: () => Effect.void, + changes: () => + Stream.fromEffectDrain(Deferred.succeed(following, undefined)).pipe( + Stream.concat(Stream.fromQueue(events)), + ), + }), + ); + const wakes = Effect.map( + orchestrator.getThreadRecords(threadId, ["messages"]), + ({ messages }) => + messages.filter( + (message) => message.notification !== undefined && message.notification !== null, + ), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* reactor.start(); + // The feed starts after the first sweep has read the pull request. + yield* Deferred.await(following); + yield* Queue.take(detailReads); + + checks = [ + { name: "lint", status: "failure", description: null, url: null, required: true }, + ]; + yield* Queue.offer(events, undefined); + // The clock never moves, so no sweep can be the one that reads the failure. + yield* Queue.take(detailReads); + // Nothing new: this read must compare against the watch the last one recorded. + yield* Queue.offer(events, undefined); + yield* Queue.take(detailReads); + // A sweep waits for the change read in flight. + yield* reactor.sweep; + yield* worker.drain(); + const woken = yield* wakes; + assert.lengthOf(woken, 1); + assert.include(woken[0]!.notification?.summary ?? "", "failed"); + + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make("pr-watch-host-event-end"), + threadId, + ...key, + watching: false, + }); + }), + ), + ); + it.effect("wakes for checks that complete after the no-checks notice on the same head", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 0140a3aa96e2..ec7ed5bb4b07 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -236,6 +236,8 @@ export class PullRequestService extends Context.Service< readonly activity: ( input: PullRequestRef, ) => Effect.Effect; + /** Emits when the host reports a change; empty where the host has no event feed. */ + readonly changes: (input: PullRequestRef) => Stream.Stream; readonly threadComments: ( input: PullRequestThreadCommentsInput, ) => Effect.Effect; @@ -570,6 +572,10 @@ function withRateLimitBackoff( api.getChangeRequestWatchFingerprint, ), }), + // A long-lived feed, not a read: the quota guard would hold its lease for hours. + ...(api.changeRequestEvents === undefined + ? {} + : { changeRequestEvents: api.changeRequestEvents }), getChangeRequestActivity: wrap("getChangeRequestActivity", api.getChangeRequestActivity), ...(api.getReviewThreadComments === undefined ? {} @@ -1084,6 +1090,23 @@ export const make = Effect.gen(function* () { }; }); + const changes: PullRequestService["Service"]["changes"] = (input) => + Stream.unwrap( + requireProject(input).pipe( + Effect.map((project) => + project.api.changeRequestEvents === undefined + ? Stream.empty + : project.api.changeRequestEvents({ + cwd: project.project.workspaceRoot, + repository: project.repository, + host: project.host, + number: input.number, + }), + ), + Effect.orElseSucceed(() => Stream.empty), + ), + ); + // Access can change after page load; recheck every write. const viewerPermissionsOf = ( project: SupportedProject, @@ -3815,6 +3838,7 @@ export const make = Effect.gen(function* () { Cache.get(watchFingerprintCache, refCacheKey(input)), ), activity: credentialCached(activity), + changes, preview: credentialCached(preview), threadComments, diff: credentialCached(diff), diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 0c58f64c47a1..be60f64c9c9a 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -1,5 +1,6 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import type * as Stream from "effect/Stream"; import type { PullRequestStackMembership, PullRequestAction, @@ -397,6 +398,14 @@ export interface PullRequestProviderApi { input: ProviderRepositoryRef & { readonly number: number }, ) => Effect.Effect; + /** + * Emits whenever the host says the change request may have changed, and once on connecting. + * Ends where the host or account offers no such feed; readers then rely on polling alone. + */ + readonly changeRequestEvents?: ( + input: ProviderRepositoryRef & { readonly number: number }, + ) => Stream.Stream; + readonly getChangeRequestStack?: ( input: ProviderRepositoryRef & { readonly includeDetails?: boolean; readonly number: number }, ) => Effect.Effect; diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.ts index 6db55da02841..0fede602068d 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.ts @@ -47,6 +47,7 @@ import { import * as GitHubAppAccess from "./GitHubAppAccess.ts"; import * as GitHubRest from "./GitHubRest.ts"; +import * as GitHubPullRequestEvents from "./gitHubPullRequestEvents.ts"; import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts"; import * as GitHubGraphQlClient from "./gitHubGraphQlClient.ts"; import { PullRequestBatchesGraphQLGroup } from "./pullRequestBatches.graphql.ts"; @@ -481,6 +482,7 @@ export class GitHubPullRequestApi extends Context.Service< readonly host: string; readonly number: number; }) => Effect.Effect; + readonly pullRequestEvents: Effect.Success; readonly revalidateChecks: Effect.Success; @@ -2019,6 +2021,7 @@ export const make = Effect.gen(function* () { getPullRequestSummary, getPullRequestWatchFingerprint, + pullRequestEvents: yield* GitHubPullRequestEvents.make, getPullRequestDetail, getPullRequestPreview: Effect.fn("GitHubPullRequestApi.getPullRequestPreview")( diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts index 3d5b7ed04dcf..723f96769d76 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts @@ -453,6 +453,8 @@ export const make = Effect.gen(function* () { .getPullRequestWatchFingerprint(input) .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))), + changeRequestEvents: (input) => cli.pullRequestEvents(input), + getChangeRequestPreview: (input) => cli.getPullRequestPreview(input).pipe(Effect.mapError(fail("getChangeRequestPreview"))), diff --git a/packages/source-control-github/src/server/gitHubPullRequestEvents.test.ts b/packages/source-control-github/src/server/gitHubPullRequestEvents.test.ts new file mode 100644 index 000000000000..cc944ff0a0b2 --- /dev/null +++ b/packages/source-control-github/src/server/gitHubPullRequestEvents.test.ts @@ -0,0 +1,195 @@ +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpClient, HttpClientResponse } from "effect/http"; + +import * as GitHubPullRequestEvents from "./gitHubPullRequestEvents.ts"; +import { GitHubApiNotFoundError, GitHubApiResponseError } from "./GitHubRequestPolicy.ts"; +import * as GitHubRest from "./GitHubRest.ts"; + +const target = { host: "github.com", repository: "pingdotgg/t3code", number: 15 }; + +const sse = (...frames: ReadonlyArray) => + frames.map(([event, data]) => `event: ${event}\ndata: ${data}\n\n`).join(""); + +function fakeRest( + subscribe: ( + count: number, + ) => Effect.Effect, + signedIn = true, +) { + const posts: Array = []; + const deletes: Array = []; + const rest = GitHubRest.GitHubRest.of({ + rest: (input) => + input.method === "DELETE" + ? Effect.sync(() => { + deletes.push(input.path); + return { status: 204, headers: {}, body: "", truncated: false, invalidUtf8: false }; + }) + : Effect.suspend(() => { + posts.push(input.body); + return subscribe(posts.length); + }).pipe( + Effect.map((body) => ({ + status: 201, + headers: {}, + body, + truncated: false, + invalidUtf8: false, + })), + ), + credential: (_host, options) => + Effect.succeed( + options?.personal === true + ? { token: Redacted.make("user-token"), fingerprint: "user", source: "gh" as const } + : { token: Redacted.make("app-token"), fingerprint: "app", source: "app" as const }, + ), + appCredential: () => + Effect.succeed( + signedIn + ? Option.some({ + token: Redacted.make("app-token"), + fingerprint: "app", + source: "app" as const, + }) + : Option.none(), + ), + }); + return { rest, posts, deletes }; +} + +const eventsOf = (rest: GitHubRest.GitHubRest["Service"], httpClient: HttpClient.HttpClient) => + GitHubPullRequestEvents.make.pipe( + Effect.provideService(GitHubRest.GitHubRest, rest), + Effect.provideService(HttpClient.HttpClient, httpClient), + ); + +const subscription = (id: number) => + Effect.succeed( + JSON.stringify({ id, events_url: `https://api.github.com/event-subscriptions/${id}/events` }), + ); + +it.effect("follows a pull request across a refused app token, reconnects, and renewals", () => + Effect.gen(function* () { + const { rest, posts, deletes } = fakeRest(subscription); + const connections: Array = []; + const answers = [ + // The app is not installed on this repository; the user's own token reads it. + () => new Response(null, { status: 404 }), + () => + new Response( + sse( + ["com.github.pull_request.head.changed.v1", "{}"], + ["github.stream.end", '{"outcome":"reconnect","reason":"shutdown"}'], + ), + ), + () => + new Response( + sse(["github.stream.end", '{"outcome":"subscription_ended","reason":"expired"}']), + ), + () => new Response(": heartbeat\n\n"), + ]; + const httpClient = HttpClient.make((request) => + Effect.sync(() => { + connections.push(`${request.url} ${request.headers.authorization}`); + return HttpClientResponse.fromWeb(request, answers[connections.length - 1]!()); + }), + ); + + const events = yield* eventsOf(rest, httpClient); + const fiber = yield* events(target).pipe(Stream.take(4), Stream.runCount, Effect.forkChild); + yield* TestClock.adjust("5 minutes"); + // An open per connection plus the head change. + assert.equal(yield* Fiber.join(fiber), 4); + + assert.deepEqual(connections, [ + "https://api.github.com/event-subscriptions/1/events Bearer app-token", + "https://api.github.com/event-subscriptions/1/events Bearer user-token", + "https://api.github.com/event-subscriptions/1/events Bearer user-token", + "https://api.github.com/event-subscriptions/2/events Bearer app-token", + ]); + assert.deepEqual(posts[0], { + resource_url: "https://github.com/pingdotgg/t3code/pull/15", + event_types: [ + "com.github.pull_request.review.submitted.v1", + "com.github.pull_request.head.changed.v1", + "com.github.pull_request.state.changed.v1", + "com.github.pull_request.merge_conflict.v1", + ], + }); + assert.deepEqual(deletes, ["event-subscriptions/1", "event-subscriptions/2"]); + }), +); + +it.effect("gives up on a silent stream and deletes its subscription", () => + Effect.gen(function* () { + const { rest, posts, deletes } = fakeRest(subscription); + let connections = 0; + // Answers, then never sends a byte, not even a keep-alive. + const httpClient = HttpClient.make((request) => + Effect.sync(() => { + connections += 1; + return HttpClientResponse.fromWeb(request, new Response(new ReadableStream())); + }), + ); + const events = yield* eventsOf(rest, httpClient); + const fiber = yield* events(target).pipe(Stream.runCount, Effect.forkChild); + yield* TestClock.adjust("15 minutes"); + + assert.equal(yield* Fiber.join(fiber), 7, "one catch-up read per connection"); + assert.equal(connections, 7); + assert.equal(posts.length, 1); + assert.deepEqual(deletes, ["event-subscriptions/1"]); + }), +); + +it.effect("leaves users without the app sign-in, other hosts, and refusals to polling", () => + Effect.gen(function* () { + const httpClient = HttpClient.make(() => Effect.die("no stream without a subscription")); + const signedOut = fakeRest(subscription, false); + assert.equal(yield* Stream.runCount((yield* eventsOf(signedOut.rest, httpClient))(target)), 0); + assert.equal(signedOut.posts.length, 0); + + const signedIn = fakeRest(subscription); + const enterprise = { ...target, host: "ghe.example.com" }; + assert.equal( + yield* Stream.runCount((yield* eventsOf(signedIn.rest, httpClient))(enterprise)), + 0, + ); + assert.equal(signedIn.posts.length, 0); + + const refused = fakeRest(() => + Effect.fail( + new GitHubApiResponseError({ + host: "github.com", + operation: "subscribePullRequestEvents", + status: 403, + }), + ), + ); + const events = yield* eventsOf(refused.rest, httpClient); + assert.equal(yield* Stream.runCount(events(target)), 0); + assert.equal(yield* Stream.runCount(events({ ...target, number: 16 })), 0); + assert.equal(refused.posts.length, 1, "a refused account is not asked again for an hour"); + yield* TestClock.adjust("61 minutes"); + assert.equal(yield* Stream.runCount(events(target)), 0); + assert.equal(refused.posts.length, 2); + + const missing = fakeRest(() => + Effect.fail( + new GitHubApiNotFoundError({ host: "github.com", operation: "subscribePullRequestEvents" }), + ), + ); + const missingEvents = yield* eventsOf(missing.rest, httpClient); + assert.equal(yield* Stream.runCount(missingEvents(target)), 0); + assert.equal(yield* Stream.runCount(missingEvents(target)), 0); + assert.equal(missing.posts.length, 1, "a pull request it cannot see is not asked again"); + assert.equal(yield* Stream.runCount(missingEvents({ ...target, number: 16 })), 0); + assert.equal(missing.posts.length, 2, "other pull requests on the host still subscribe"); + }), +); diff --git a/packages/source-control-github/src/server/gitHubPullRequestEvents.ts b/packages/source-control-github/src/server/gitHubPullRequestEvents.ts new file mode 100644 index 000000000000..7afccc73990b --- /dev/null +++ b/packages/source-control-github/src/server/gitHubPullRequestEvents.ts @@ -0,0 +1,282 @@ +import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils"; +import * as Clock from "effect/Clock"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Random from "effect/Random"; +import * as Redacted from "effect/Redacted"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; +import * as Sse from "effect/encoding/Sse"; +import { HttpClient, HttpClientRequest } from "effect/http"; + +import * as GitHubRest from "./GitHubRest.ts"; + +/** Events only say that something changed; readers fetch the pull request for what. */ +const EVENT_TYPES = [ + "com.github.pull_request.review.submitted.v1", + "com.github.pull_request.head.changed.v1", + "com.github.pull_request.state.changed.v1", + "com.github.pull_request.merge_conflict.v1", +]; +const API_ORIGIN = "https://api.github.com"; +/** GitHub sends a keep-alive at least every 15 seconds while a stream is idle. */ +const SILENCE_LIMIT = Duration.seconds(45); +/** A connection open this long was healthy, however it ended. */ +const HEALTHY_AFTER = Duration.minutes(2); +/** GitHub enables event streams per account, so a refusal holds for a while. */ +const REFUSED_PAUSE = Duration.hours(1); +/** Another watch ending may free a slot under the per-account subscription limit. */ +const LIMIT_PAUSE = Duration.minutes(10); +const MAX_FAILURES = 6; +const MAX_BACKOFF_MS = 60_000; + +const Subscription = Schema.Struct({ + id: Schema.Union([Schema.String, Schema.Number]), + events_url: Schema.String, +}); +const decodeSubscription = Schema.decodeUnknownOption(Schema.fromJsonString(Subscription)); + +const decodeStreamEnd = Schema.decodeUnknownOption( + Schema.fromJsonString(Schema.Struct({ outcome: Schema.String })), +); + +/** + * How a connection ended. `renew` means the subscription expired or lost access, and `personal` + * that the app's token was refused where the user's own may still read. + */ +type Ending = "reconnect" | "renew" | "personal" | "stop"; + +const endingOf = (data: string): Ending => + Option.match(decodeStreamEnd(data), { + onNone: () => "reconnect", + onSome: ({ outcome }) => (outcome === "subscription_ended" ? "renew" : "reconnect"), + }); + +export interface PullRequestEventsInput { + readonly host: string; + readonly repository: string; + readonly number: number; +} + +/** + * Emits when a connection opens, so a reader catches up on what it missed, then once per change + * GitHub reports. Ends quietly when GitHub refuses the subscription; the caller polls meanwhile. + */ +export const make = Effect.gen(function* () { + const rest = yield* GitHubRest.GitHubRest; + const httpClient = yield* HttpClient.HttpClient; + /** Keyed by host for account-wide refusals, and by pull request for one it cannot read. */ + const pausedUntil = new Map(); + + const subscribe = Effect.fn("GitHubPullRequestEvents.subscribe")(function* ( + input: PullRequestEventsInput, + ) { + const resourceUrl = `https://${input.host}/${input.repository}/pull/${input.number}`; + const now = yield* Clock.currentTimeMillis; + if (Math.max(pausedUntil.get(input.host) ?? 0, pausedUntil.get(resourceUrl) ?? 0) > now) { + return Option.none(); + } + const pause = (key: string, duration: Duration.Duration) => + Effect.sync(() => pausedUntil.set(key, now + Duration.toMillis(duration))); + const response = yield* rest + .rest({ + host: input.host, + operation: "subscribePullRequestEvents", + method: "POST", + path: "event-subscriptions", + body: { resource_url: resourceUrl, event_types: EVENT_TYPES }, + }) + .pipe( + Effect.asSome, + Effect.catchTags({ + GitHubApiNotFoundError: () => + pause(resourceUrl, REFUSED_PAUSE).pipe(Effect.as(Option.none())), + GitHubApiResponseError: (error) => + (error.status === 403 + ? pause(input.host, REFUSED_PAUSE) + : error.status === 422 + ? pause(input.host, LIMIT_PAUSE) + : Effect.void + ).pipe(Effect.as(Option.none())), + }), + Effect.catch((error) => + Effect.logDebug("pull request event subscription failed", { error }).pipe( + Effect.as(Option.none()), + ), + ), + ); + if (Option.isNone(response)) return Option.none(); + // The stream request carries the token, so its URL must stay on GitHub's API. + return decodeSubscription(response.value.body).pipe( + Option.filter(({ events_url }) => URL.parse(events_url)?.origin === API_ORIGIN), + ); + }); + + const unsubscribe = Effect.fn("GitHubPullRequestEvents.unsubscribe")(function* ( + host: string, + id: string | number, + ) { + yield* rest + .rest({ + host, + operation: "unsubscribePullRequestEvents", + method: "DELETE", + path: `event-subscriptions/${encodeURIComponent(String(id))}`, + }) + .pipe(Effect.ignore); + }); + + /** One SSE connection: "changed" when it opens and per event, and last, how it ended. */ + const connection = ( + host: string, + eventsUrl: string, + personal: boolean, + ): Stream.Stream<"changed" | Ending> => + Stream.unwrap( + Effect.gen(function* () { + const held = yield* rest.credential(host, { personal }); + const response = yield* httpClient + .execute( + HttpClientRequest.get(eventsUrl).pipe( + HttpClientRequest.setHeaders({ + accept: "text/event-stream", + "x-github-api-version": "2022-11-28", + "user-agent": "t3code", + authorization: `Bearer ${Redacted.value(held.token)}`, + }), + ), + ) + // Client spans would carry the subscription URL. + .pipe(Effect.provideService(HttpClient.TracerDisabledWhen, () => true)); + if (response.status === 403 || response.status === 404) { + return Stream.succeed(held.source === "app" ? "personal" : "stop"); + } + if (response.status !== 200) return Stream.succeed("reconnect"); + return response.stream.pipe( + Stream.timeoutOrElse({ duration: SILENCE_LIMIT, orElse: () => Stream.fail("silent") }), + Stream.decodeText, + Stream.pipeThroughChannel(Sse.decode()), + Stream.map((frame): "changed" | Ending => + frame.event === "github.stream.end" ? endingOf(frame.data) : "changed", + ), + Stream.prepend(["changed" as const]), + // A close without GitHub's end frame is reconnected like one with it. + Stream.concat(Stream.succeed("reconnect")), + Stream.takeUntil((element) => element !== "changed"), + ); + }), + ).pipe( + Stream.catchCause((cause) => + Stream.fromEffect( + Effect.logDebug("pull request event stream failed", { cause }).pipe( + Effect.as("reconnect"), + ), + ), + ), + ); + + const backoff = Effect.fn("GitHubPullRequestEvents.backoff")(function* (failures: number) { + const jitter = yield* Random.next; + yield* Effect.sleep( + Duration.millis(Math.min(MAX_BACKOFF_MS, 1_000 * 2 ** failures) * (0.5 + jitter / 2)), + ); + }); + + return (input: PullRequestEventsInput): Stream.Stream => { + const target = { ...input, host: normalizeHost(input.host) }; + if (target.host !== "github.com") return Stream.empty; + + /** Follows one subscription; sets `session.renew` when it needs replacing. */ + const follow = ( + session: { renew: boolean }, + eventsUrl: string, + personal: boolean, + failuresSoFar: number, + ): Stream.Stream => + Stream.unwrap( + Clock.currentTimeMillis.pipe( + Effect.map((openedAt) => { + let ending: Ending = "reconnect"; + let changes = 0; + return connection(target.host, eventsUrl, personal).pipe( + Stream.flatMap((element) => { + if (element === "changed") { + changes += 1; + return Stream.succeed(undefined); + } + ending = element; + return Stream.empty; + }), + Stream.concat( + Stream.unwrap( + Clock.currentTimeMillis.pipe( + Effect.map((closedAt) => { + // The first change is the opening; an event or a long life proves it worked. + const healthy = + changes > 1 || closedAt - openedAt >= Duration.toMillis(HEALTHY_AFTER); + const failures = healthy ? 0 : failuresSoFar + 1; + switch (ending) { + case "stop": + return Stream.empty; + case "renew": + session.renew = true; + return Stream.empty; + case "personal": + return personal + ? Stream.empty + : follow(session, eventsUrl, true, failuresSoFar); + case "reconnect": + return failures > MAX_FAILURES + ? Stream.empty + : Stream.fromEffectDrain(backoff(failures)).pipe( + Stream.concat(follow(session, eventsUrl, personal, failures)), + ); + } + }), + ), + ), + ), + ); + }), + ), + ); + + /** One subscription, deleted once its stream has closed. */ + const subscription = (session: { renew: boolean }): Stream.Stream => + Stream.unwrap( + Effect.acquireRelease(subscribe(target), (held) => + Option.isSome(held) ? unsubscribe(target.host, held.value.id) : Effect.void, + ).pipe( + Effect.map( + Option.match({ + onNone: () => Stream.empty, + onSome: ({ events_url }) => follow(session, events_url, false, 0), + }), + ), + ), + ); + + const subscribed = (): Stream.Stream => + Stream.suspend(() => { + const session = { renew: false }; + return subscription(session).pipe( + Stream.concat( + Stream.suspend(() => + session.renew + ? Stream.fromEffectDrain(backoff(0)).pipe(Stream.concat(subscribed())) + : Stream.empty, + ), + ), + ); + }); + + // Event streams are a GitHub preview, so only the app sign-in, itself opt-in, uses them. + return Stream.unwrap( + rest.appCredential(target.host).pipe( + Effect.map((app) => (Option.isSome(app) ? subscribed() : Stream.empty)), + Effect.orElseSucceed(() => Stream.empty), + ), + ); + }; +}); From 5badea5b454c8e39e15e95be5e0e096b25b7b577 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 23:17:07 -0800 Subject: [PATCH 029/436] fix(server): hide passive Claude Stop-hook summaries (#22964) --- .../Adapters/ClaudeAdapterV2.test.ts | 64 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 12 +++- 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index c949323b91c9..4550692f3e18 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8431,6 +8431,70 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // The passive row is the frame Claude 2.1.303 emits for a Stop hook returning a systemMessage. + it.effect.each([ + { name: "hides a passive summary", level: "notice", visible: false }, + { name: "shows a blocking notice", level: "notice", preventContinuation: true, visible: true }, + { name: "shows a warning", level: "warning", visible: true }, + ])("Claude Stop-hook notices: $name", ({ level, preventContinuation, visible }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("claude-stop-hook-notice-attempt"), + text: "Continue.", + attachments: [], + }), + ); + const content = "Stop says: 40 scans, 0 findings"; + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "informational", + content, + level, + ...(preventContinuation === undefined + ? {} + : { prevent_continuation: preventContinuation }), + session_id: WAKE_NATIVE_SESSION, + uuid: "00000000-0000-4000-8000-000000000820", + }), + ); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000821", result: content }), + ); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "system_notice" + ? [event.turnItem.message] + : [], + ), + visible ? [content] : [], + ); + assert.isFalse( + harness.events.some( + (event) => event.type === "message.updated" && event.message.role === "assistant", + ), + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + IdAllocator.layer, + McpProviderSessions.layer, + ), + ), + ), + ); + it.effect("shows a hook-dropped Claude prompt once and skips info-level lines", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 829cc0dbe4be..4a252d6092ed 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -9361,9 +9361,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (message.subtype === "model_refusal_fallback" || (message.subtype === "informational" && message.level !== "info")) ) { + context.assistant.noticeTexts.add(message.content); + // A Stop hook's systemMessage arrives as a passive notice after every turn. + // Warnings and notices that prevent continuation explain a blocked turn. + if ( + message.subtype === "informational" && + message.level === "notice" && + message.content.startsWith("Stop says: ") && + message.prevent_continuation !== true + ) { + return; + } const now = yield* DateTime.now; const nativeItemId = message.uuid; - context.assistant.noticeTexts.add(message.content); yield* emitProviderEvent({ type: "turn_item.updated", driver: CLAUDE_PROVIDER, From 75b22bf56ceee0d62a8e43c009d5a9ad3a9ab804 Mon Sep 17 00:00:00 2001 From: Lakshmi Tanmay Date: Wed, 11 Nov 2026 12:51:54 +0530 Subject: [PATCH 030/436] fix(web): dismiss image path tooltips after preview and scroll (#30620) Co-authored-by: Julius Marminge --- .../chat/ExpandedImageDialog.browser.test.tsx | 41 +++++++++++++++++- .../components/chat/ExpandedImageDialog.tsx | 14 +++--- .../components/ui/tooltip.browser.test.tsx | 43 +++++++++++++++++++ apps/web/src/components/ui/tooltip.tsx | 4 +- 4 files changed, 94 insertions(+), 8 deletions(-) create mode 100644 apps/web/src/components/ui/tooltip.browser.test.tsx diff --git a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx index ff1473876692..7287547df71f 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx @@ -1,6 +1,7 @@ +import { useState } from "react"; import type { SnapShotSource } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; @@ -19,7 +20,45 @@ const snapShotSource: SnapShotSource = { const D2_SVG = ''; +function ImagePreviewOpener() { + const [open, setOpen] = useState(false); + return ( + <> + + {open && ( + setOpen(false)} + /> + )} + + ); +} + describe("ExpandedImageDialog", () => { + it.each([ + { opener: "mouse", focusVisible: false }, + { opener: "keyboard", focusVisible: true }, + ])("returns $opener focus to the opener on close", async (c) => { + await using screen = await render(, { + // The opener renders no links and reads no route. + router: false, + }); + const opener = screen.getByRole("button", { name: "Open preview" }); + if (c.opener === "mouse") { + await userEvent.click(opener); + } else { + await userEvent.keyboard("{Tab}"); + await userEvent.keyboard("{Enter}"); + } + await expect.element(page.getByRole("button", { name: "Close image preview" })).toHaveFocus(); + await userEvent.keyboard("{Escape}"); + await expect.element(opener).toHaveFocus(); + expect(opener.element().matches(":focus-visible")).toBe(c.focusVisible); + }); + it.each(["/work/pipeline.svg", "/work/diagram#v2.svg", "/work/diagram?v2.svg"])( "fits a markdown SVG without intrinsic size to the viewer: %s", async (path) => { diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index a39e11978126..dad9280ad6dc 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -85,15 +85,17 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ const [failedImageSrc, setFailedImageSrc] = useState(null); const [accessibilityDetailsSrc, setAccessibilityDetailsSrc] = useState(null); const zoomableImageRef = useRef(null); - const [returnFocusTarget] = useState(() => - document.activeElement instanceof HTMLElement ? document.activeElement : null, - ); + const [returnFocus] = useState(() => { + const target = document.activeElement instanceof HTMLElement ? document.activeElement : null; + return { target, focusVisible: target?.matches(":focus-visible") ?? false }; + }); // The host unmounts the dialog outright, so Base UI never runs finalFocus. Without // this, focus stays on the removed dialog, and the composer that owned the opener - // reads that as a blur and rests. + // reads that as a blur and rests. Preserve mouse focus when Escape closes it. const close = () => { flushSync(onClose); - if (returnFocusTarget?.isConnected) returnFocusTarget.focus({ preventScroll: true }); + const { target, focusVisible } = returnFocus; + if (target?.isConnected) target.focus({ preventScroll: true, focusVisible }); }; const closeButtonRef = useRef(null); const imageCount = preview.images.length; @@ -177,7 +179,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ className="row-start-1 h-full max-h-[92vh] w-[92vw] max-w-[92vw] items-center justify-center overflow-visible [--media-width:92vw] [--media-height:min(calc((100vh-var(--native-titlebar-height,0px))*0.86),calc(100vh-var(--native-titlebar-height,0px)-160px))] sm:[--media-width:calc(92vw-96px)]" onKeyDown={onKeyDown} initialFocus={closeButtonRef} - finalFocus={() => returnFocusTarget} + finalFocus={() => returnFocus.target} onClick={(event) => { if (event.target === event.currentTarget) close(); }} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx new file mode 100644 index 000000000000..24d76784e8a5 --- /dev/null +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -0,0 +1,43 @@ +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; + +it.each([ + { focus: "mouse", keptOpen: false }, + { focus: "keyboard", keptOpen: true }, +])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + + Timeline action + Description + +
+ , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + screen.getByTestId("timeline").element().scrollTop = 20; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index ff8b9e8f1644..614943364b1e 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -31,7 +31,9 @@ function createTooltipHoverTracker() { }, dismissUnfocused() { const tooltip = hovered; - if (!tooltip || tooltip.trigger.contains(tooltip.trigger.ownerDocument.activeElement)) { + if (!tooltip) return; + const focused = tooltip.trigger.ownerDocument.activeElement; + if (focused && tooltip.trigger.contains(focused) && focused.matches(":focus-visible")) { return; } hovered = null; From b0f12e12e37947629278f62e623442c39eba1a3b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 23:27:43 -0800 Subject: [PATCH 031/436] fix(server): PR sync and run-status checks stop reading whole thread histories (#25728) Co-authored-by: Claude Opus 5.5 --- .../orchestration-v2/ProjectionStore.test.ts | 3 +- .../src/orchestration-v2/ProjectionStore.ts | 22 +++++++- .../ProviderTurnControlService.test.ts | 1 + .../ProviderTurnStartService.test.ts | 51 +++++++++++++++---- .../ProviderTurnStartService.ts | 26 ++++------ 5 files changed, 76 insertions(+), 27 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 40b770987058..557160816bbb 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -4676,7 +4676,8 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { ); const settledPayload = (settledAt: string | null, archivedAt: string | null) => sql` UPDATE orchestration_v2_projection_threads - SET payload_json = json_set(payload_json, '$.settledAt', ${settledAt}, '$.archivedAt', ${archivedAt}) + SET payload_json = json_set(payload_json, '$.settledAt', ${settledAt}, '$.archivedAt', ${archivedAt}), + archived_at = ${archivedAt} WHERE thread_id = ${readThreadId} `; yield* settledPayload(DateTime.formatIso(now), null); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 0c4976dc9059..89183b48a8ef 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -678,6 +678,10 @@ export interface ProjectionStoreV2Shape { threadId: ThreadId, runId: RunId, ) => Effect.Effect; + readonly getRun: ( + threadId: ThreadId, + runId: RunId, + ) => Effect.Effect; readonly canStartQueuedRun: ( threadId: ThreadId, ) => Effect.Effect; @@ -5588,6 +5592,21 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + const getRun: ProjectionStoreV2Shape["getRun"] = (threadId, runId) => + sql + .withTransaction( + Effect.gen(function* () { + yield* requireThread(threadId); + const rows = yield* sql` + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE run_id = ${runId} AND thread_id = ${threadId}`; + return rows[0] === undefined + ? undefined + : yield* decodeRunPayload(rows[0].payload_json); + }), + ) + .pipe(Effect.mapError(controlReadError(threadId))); + const canStartQueuedRun: ProjectionStoreV2Shape["canStartQueuedRun"] = (threadId) => sql .withTransaction( @@ -7218,7 +7237,7 @@ export const layer: Layer.Layer = SELECT t.payload_json FROM orchestration_v2_projection_threads t WHERE t.deleted_at IS NULL${ threadId === undefined - ? sql` AND json_extract(t.payload_json, '$.archivedAt') IS NULL` + ? sql` AND t.archived_at IS NULL` : sql` AND t.thread_id = ${threadId}` }${ unsettledOnly @@ -7639,6 +7658,7 @@ export const layer: Layer.Layer = getCheckpointCaptureContext: readOnReader(getCheckpointCaptureContext), getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext), getRunMessage: readOnReader(getRunMessage), + getRun: readOnReader(getRun), canStartQueuedRun: readOnReader(canStartQueuedRun), getHeldQueuedRuns: readOnReader(getHeldQueuedRuns), getPendingNativeUserInputs: readOnReader(getPendingNativeUserInputs), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 8b30a961c099..25daa45a847f 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -268,6 +268,7 @@ it.effect( getCheckpointRollbackContext: () => Effect.die("unused rollback context"), getCheckpointCaptureContext: () => Effect.die("not used"), getRunMessage: () => Effect.die("not used"), + getRun: () => Effect.die("not used"), isNodeStored: () => Effect.die("not used"), canStartQueuedRun: () => Effect.die("not used"), getHeldQueuedRuns: () => Effect.die("not used"), diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7c58e6ad079e..a4f0149551a2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -919,6 +919,18 @@ function makeLocalCommandHarness(input: { ), }), ); + const getRuntimeRecoveryProjection = vi.fn< + ProjectionStore.ProjectionStoreV2Shape["getRuntimeRecoveryProjection"] + >(() => + Effect.as(failReadIfRunning, { + ...projection, + hasConversation: projection.messages.some( + (m) => + m.role === "user" && + (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), + ), + }), + ); const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( @@ -968,15 +980,12 @@ function makeLocalCommandHarness(input: { Layer.mock(ProjectionStore.ProjectionStoreV2)({ getThreadRecords, getTurnStartContext, - getRuntimeRecoveryProjection: () => - Effect.as(failReadIfRunning, { - ...projection, - hasConversation: projection.messages.some( - (m) => - m.role === "user" && - (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), - ), - }), + getRuntimeRecoveryProjection, + getRun: (_threadId, id) => + Effect.as( + failReadIfRunning, + projection.runs.find((candidate) => candidate.id === id), + ), getTurnStartHistory: () => input.sideChat !== undefined ? Effect.succeed([]) @@ -1017,6 +1026,7 @@ function makeLocalCommandHarness(input: { settledRuns, getThreadRecords, getTurnStartContext, + getRuntimeRecoveryProjection, setProjection: (next: OrchestrationV2ThreadProjection) => { projection = next; }, @@ -1764,6 +1774,29 @@ effectIt.effect("does not overwrite a run interrupted while its provider session }), ); +effectIt.effect("checks the run's status without loading the thread's history", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + previousTurn: { runStatus: "completed", turnStatus: "completed" }, + }); + + yield* harness.start; + + const controls = harness.startRootRun.mock.calls[0]?.[0]; + expect(controls).toBeDefined(); + if (controls === undefined) return; + expect(yield* controls.shouldStartProviderTurn!()).toBe(true); + expect(yield* controls.shouldFinalizeRun!()).toBe(true); + // Each check needs one run row; the recovery projection reads every run and open turn item. + // The one read left is the start's inherited background items snapshot, not a status check. + expect( + harness.getRuntimeRecoveryProjection.mock.calls.length, + "recovery projection reads beyond the inherited background items snapshot", + ).toBe(1); + }), +); + effectIt.effect("fails the run instead of replacing a native thread another client holds", () => Effect.gen(function* () { const detail = "This conversation is open in another Codex client."; diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 98652036118f..a9e0b3f29b3a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -237,13 +237,16 @@ export const layer: Layer.Layer< typeof RunExecutionService.selectInheritedBackgroundTurnItems >; }) => { + const isCurrentAttemptIn = (statuses: ReadonlyArray) => + projectionStore + .getRun(input.threadId, input.runId) + .pipe( + Effect.map( + (run) => run?.activeAttemptId === input.attemptId && statuses.includes(run.status), + ), + ); const isCurrentAttemptInStatus = (expectedStatus: OrchestrationV2Run["status"]) => - projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe( - Effect.map((current) => { - const run = current.runs.find((candidate) => candidate.id === input.runId); - return run?.activeAttemptId === input.attemptId && run.status === expectedStatus; - }), - ); + isCurrentAttemptIn([expectedStatus]); return { isCurrentAttemptInStatus, loadInheritedBackgroundTurnItems: () => @@ -260,16 +263,7 @@ export const layer: Layer.Layer< Effect.catchCause(() => Effect.succeed(input.inheritedBackgroundTurnItems)), ), shouldStartProviderTurn: () => isCurrentAttemptInStatus("running"), - shouldFinalizeRun: () => - projectionStore.getRuntimeRecoveryProjection(input.threadId).pipe( - Effect.map((current) => { - const run = current.runs.find((candidate) => candidate.id === input.runId); - return ( - run?.activeAttemptId === input.attemptId && - (run.status === "starting" || run.status === "running") - ); - }), - ), + shouldFinalizeRun: () => isCurrentAttemptIn(["starting", "running"]), hasUnpairedRunInterruptRequest: () => projectionStore .hasUnpairedRunInterruptRequest( From 950c34226cc08ca4d9fc0e387b059a30463a1e47 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 10 Nov 2026 23:27:50 -0800 Subject: [PATCH 032/436] fix(server): preview snapshots keep page text beside large accessibility trees (#33745) Co-authored-by: Claude Opus 5.5 --- apps/server/src/mcp/McpHttpServer.test.ts | 15 ++++++++++-- apps/server/src/mcp/McpHttpServer.ts | 29 ++++++++++++++++------- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 8f922c2786cb..4c7509bf051a 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -688,10 +688,21 @@ it.effect("bounds large ARIA trees without dropping every server locator", () => { length: 2_000 }, (_, index) => `- button "删除 ${index}" [ref=t3-snapshot-e${index}]`, ).join("\n"); - yield* serveSnapshots("mcp-large-server-refs", { ...snapshotResult, accessibilityTree }); + const visibleText = Array.from({ length: 700 }, (_, index) => `Row ${index} value`).join( + "\n", + ); + yield* serveSnapshots("mcp-large-server-refs", { + ...snapshotResult, + visibleText, + accessibilityTree, + }); const result = yield* callSnapshot({ includeImage: false }); expect(result.isError).toBe(false); - const metadata = result.structuredContent as { accessibilityTree: string }; + const metadata = result.structuredContent as { + accessibilityTree: string; + visibleText: string; + }; + expect(metadata.visibleText.slice(0, 1_000)).toBe(visibleText.slice(0, 1_000)); expect(metadata.accessibilityTree).toContain("[ref=t3-snapshot-e0]"); expect(metadata.accessibilityTree.length).toBeLessThan(accessibilityTree.length); const body = result.content[1]; diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index f838412f14f8..a160f1fcab59 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -255,6 +255,8 @@ const layerMcpAuthMiddleware = HttpRouter.middleware<{ /** Claude Code spills oversized results to files, losing locators; bound both text and its preferred structuredContent. */ export const MAX_SNAPSHOT_TEXT_BYTES = 20_000; const MAX_SNAPSHOT_VISIBLE_TEXT_CHARS = 8_000; +// Page text and the ARIA tree both shrink to this before either drops below it. +const SNAPSHOT_TEXT_FLOOR_CHARS = 2_000; const MAX_SNAPSHOT_ELEMENT_NAME_CHARS = 200; const MAX_SNAPSHOT_LOG_ENTRIES = 40; const MAX_SNAPSHOT_LOG_TEXT_CHARS = 500; @@ -298,6 +300,11 @@ type SnapshotMetadata = { readonly [key: string]: unknown; }; +const halveToFloor = (chars: number) => + chars > SNAPSHOT_TEXT_FLOOR_CHARS + ? Math.max(SNAPSHOT_TEXT_FLOOR_CHARS, Math.floor(chars / 2)) + : Math.floor(chars / 2); + const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { const omitted: Array = []; const { accessibilityTree, ...withoutTree } = metadata; @@ -370,23 +377,27 @@ const boundSnapshotMetadata = (metadata: SnapshotMetadata) => { }); let text = encodeJsonText(value()); while (utf8Length(text) > MAX_SNAPSHOT_TEXT_BYTES) { - // Elements carry the locators, so they go last; logs shed newest-last. + // Logs shed first, oldest first. Below the floors, locator-bearing elements and tree go last. const key = shedOrder.find( (candidate) => candidate !== "interactiveElements" && lists[candidate].length > 0, ) ?? - (visibleTextChars > 0 + (visibleTextChars > SNAPSHOT_TEXT_FLOOR_CHARS ? "visibleText" - : lists.interactiveElements.length > 0 - ? "interactiveElements" - : ariaTreeChars > 0 - ? "accessibilityTree" - : undefined); + : ariaTreeChars > SNAPSHOT_TEXT_FLOOR_CHARS + ? "accessibilityTree" + : visibleTextChars > 0 + ? "visibleText" + : lists.interactiveElements.length > 0 + ? "interactiveElements" + : ariaTreeChars > 0 + ? "accessibilityTree" + : undefined); if (key === undefined) break; if (key === "visibleText") { - visibleTextChars = Math.floor(visibleTextChars / 2); + visibleTextChars = halveToFloor(visibleTextChars); } else if (key === "accessibilityTree") { - ariaTreeChars = Math.floor(ariaTreeChars / 2); + ariaTreeChars = halveToFloor(ariaTreeChars); } else { const keep = Math.floor(lists[key].length / 2); dropped[key] += lists[key].length - keep; From 40c3682543fdcb9f8b7d4106ed2ab970c25b7dc5 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Wed, 11 Nov 2026 13:16:03 +0530 Subject: [PATCH 033/436] feat(web): screen readers can hear the agent's messages and steps during a turn (#33900) Co-authored-by: Claude Fable 5.2 --- .../components/chat/MessagesTimeline.logic.ts | 4 +- .../src/components/chat/MessagesTimeline.tsx | 7 + .../ThreadActivityAnnouncer.browser.test.tsx | 157 +++++++++ .../chat/ThreadActivityAnnouncer.tsx | 160 ++++++++- .../components/chat/timelineMinimapItems.ts | 5 + .../chat/turnDetailAnnouncement.test.ts | 320 ++++++++++++++++++ .../components/chat/turnDetailAnnouncement.ts | 202 +++++++++++ .../components/settings/SettingsPanels.tsx | 65 ++++ .../src/components/settings/settingsSearch.ts | 8 + docs/user/activity-log.md | 12 + packages/contracts/src/settings.ts | 8 + 11 files changed, 935 insertions(+), 13 deletions(-) create mode 100644 apps/web/src/components/chat/ThreadActivityAnnouncer.browser.test.tsx create mode 100644 apps/web/src/components/chat/turnDetailAnnouncement.test.ts create mode 100644 apps/web/src/components/chat/turnDetailAnnouncement.ts diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 94fbe68e2952..9e9d82a11fcb 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -79,7 +79,7 @@ import { } from "@t3tools/shared/toolActivity"; import { isWindowsAbsolutePath } from "@t3tools/shared/path"; -function timelineEntryRunId(entry: TimelineEntry): RunId | null { +export function timelineEntryRunId(entry: TimelineEntry): RunId | null { if (entry.kind === "message") { return entry.message.role === "assistant" ? (entry.message.runId ?? null) : null; } @@ -917,7 +917,7 @@ function timelineEntryIsSteer(entry: TimelineEntry): boolean { ); } -function timelineEntryStartsResponse(entry: TimelineEntry): boolean { +export function timelineEntryStartsResponse(entry: TimelineEntry): boolean { return ( (entry.kind === "message" && entry.message.role === "user" && !timelineEntryIsSteer(entry)) || (entry.kind === "work" && entry.entry.itemType === "notification") diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 61d5c4d97e45..a2b39ffd143f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -200,6 +200,7 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END = { }, } as const satisfies MaintainScrollAtEndOptions; const EMPTY_RUN_IDS: ReadonlySet = new Set(); +const EMPTY_TIMELINE_ENTRIES: ReadonlyArray = []; const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = { ...TIMELINE_MAINTAIN_SCROLL_AT_END, animated: true, @@ -552,6 +553,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ } const preferredToolCallVisibility = useClientSettings((settings) => settings.toolCallVisibility); + const screenReaderAnnouncements = useClientSettings( + (settings) => settings.screenReaderAnnouncements, + ); const toolCallVisibility = findActive && preferredToolCallVisibility === "zen" ? "hideAll" : preferredToolCallVisibility; const revealedMessageId = citationRequest?.citation.messageId ?? null; @@ -1078,6 +1082,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ runId={announcedRun?.runId ?? null} runStatus={announcedRun?.status ?? null} detailBehind={detailBehindShell} + level={screenReaderAnnouncements} + entries={screenReaderAnnouncements === "status" ? EMPTY_TIMELINE_ENTRIES : timelineEntries} + workspaceRoot={workspaceRoot} /> ); const listHeaderLeadingContent = diff --git a/apps/web/src/components/chat/ThreadActivityAnnouncer.browser.test.tsx b/apps/web/src/components/chat/ThreadActivityAnnouncer.browser.test.tsx new file mode 100644 index 000000000000..b9efe2dcd610 --- /dev/null +++ b/apps/web/src/components/chat/ThreadActivityAnnouncer.browser.test.tsx @@ -0,0 +1,157 @@ +import { MessageId, RunId } from "@t3tools/contracts"; +import { type ComponentProps } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { act, fakeTimers, render } from "../../../test/render"; +import type { TimelineEntry } from "../../session-logic"; +import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer"; + +const run = RunId.make("run-1"); +const at = "2026-01-01T00:00:00.000Z"; + +const message = (id: string, role: "user" | "assistant", streaming = false): TimelineEntry => ({ + kind: "message", + id, + createdAt: at, + message: { + id: MessageId.make(id), + role, + text: id, + runId: role === "assistant" ? run : null, + streaming, + createdAt: at, + updatedAt: at, + }, +}); +const command = (program: string): TimelineEntry => ({ + kind: "work", + id: program, + createdAt: at, + entry: { + id: program, + createdAt: at, + runId: run, + label: program, + tone: "tool", + itemType: "command_execution", + command: program, + toolLifecycleStatus: "inProgress", + }, +}); +const prompt = message("prompt", "user"); + +const announcer = (props: Partial>) => ( + +); + +const regions = (container: HTMLElement) => { + const [detail, status] = container.querySelectorAll('[aria-live="polite"]'); + return { detail: detail!, status: status! }; +}; + +describe("ThreadActivityAnnouncer", () => { + it("drops a waiting step once the agent has moved on", async () => { + // The announcer reads no route. + await using screen = await render(announcer({ status: "idle", runStatus: "completed" }), { + router: false, + }); + const { detail, status } = regions(screen.container); + { + // Restored before the assertions, which poll on real timers. + using _timers = fakeTimers(); + await screen.rerender(announcer({})); + await screen.rerender(announcer({ entries: [prompt, command("git")] })); + await screen.rerender( + announcer({ entries: [prompt, command("git"), message("reply", "assistant", true)] }), + ); + await act(() => vi.advanceTimersByTime(5_000)); + } + + await expect.element(status).toHaveTextContent("Working"); + await expect.element(detail).toBeEmptyDOMElement(); + }); + + it("holds a waiting step while the thread's detail is behind, then reads it", async () => { + // The announcer reads no route. + await using screen = await render(announcer({ status: "idle", runStatus: "completed" }), { + router: false, + }); + const { detail } = regions(screen.container); + const entries = [prompt, command("git")]; + const heard: string[] = []; + { + // Restored before the assertion, which polls on real timers. + using _timers = fakeTimers(); + await screen.rerender(announcer({})); + await screen.rerender(announcer({ entries })); + await screen.rerender(announcer({ entries, detailBehind: true })); + await act(() => vi.advanceTimersByTime(5_000)); + heard.push(detail.textContent); + await screen.rerender(announcer({ entries })); + await act(() => vi.advanceTimersByTime(2_000)); + } + + expect(heard).toEqual([""]); + await expect.element(detail).toHaveTextContent("Running git"); + }); + + it("keeps a message beside the status that follows it, then reads the newest step", async () => { + // The announcer reads no route. + await using screen = await render(announcer({ status: "idle", runStatus: "completed" }), { + router: false, + }); + const { detail, status } = regions(screen.container); + const entries = [prompt, message("Checking the repo", "assistant"), command("git")]; + const heard: Array<[status: string, detail: string]> = []; + using _timers = fakeTimers(); + for (const props of [ + {}, + { entries }, + { entries, status: "approval", requestId: "request-1" }, + { entries: [...entries, command("rg")] }, + ] satisfies ReadonlyArray>>) { + await screen.rerender(announcer(props)); + heard.push([status.textContent, detail.textContent]); + } + await act(() => vi.advanceTimersByTime(2_000)); + heard.push([status.textContent, detail.textContent]); + + expect(heard).toEqual([ + ["Working", ""], + ["Working", "T3 Code: Checking the repo"], + ["Needs approval", "T3 Code: Checking the repo"], + ["Needs approval", "T3 Code: Checking the repo"], + ["Needs approval", "Running rg"], + ]); + }); + + it("reads a status that lands with a message as the message's last sentence", async () => { + // The announcer reads no route. + await using screen = await render(announcer({ status: "idle", runStatus: "completed" }), { + router: false, + }); + const { detail, status } = regions(screen.container); + await screen.rerender(announcer({})); + await screen.rerender( + announcer({ + entries: [prompt, message("Checking the repo", "assistant"), command("git")], + status: "approval", + requestId: "request-1", + }), + ); + + await expect.element(detail).toHaveTextContent("T3 Code: Checking the repo. Needs approval"); + await expect.element(status).toHaveTextContent("Working"); + }); +}); diff --git a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx index 998b9e1522ad..0dc54f3f2df0 100644 --- a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx +++ b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx @@ -1,14 +1,46 @@ +import type { ScreenReaderAnnouncements } from "@t3tools/contracts"; import { memo, useEffect, useRef } from "react"; import { useLiveRegion } from "../../hooks/useLiveRegion"; +import type { TimelineEntry } from "../../session-logic"; import { nextThreadAnnouncement, type ThreadActivitySnapshot, type ThreadAnnouncementMemory, } from "./threadActivityAnnouncement"; +import { + nextTurnDetailAnnouncement, + NO_TURN_DETAIL, + turnDetail, + type TurnDetailMemory, +} from "./turnDetailAnnouncement"; + +// Long enough for a screen reader to finish a short label before the next one. +const ACTIVITY_GAP_MS = 2_000; +// A polite region queues what it can't say yet, so steps written while a +// message is still being read would all be heard late. They wait this long. +const MESSAGE_HOLD_MS_PER_CHARACTER = 50; +const MESSAGE_HOLD_MAX_MS = 15_000; + +function holdAfter(text: string) { + return Math.min( + MESSAGE_HOLD_MAX_MS, + Math.max(ACTIVITY_GAP_MS, text.length * MESSAGE_HOLD_MS_PER_CHARACTER), + ); +} + +/** One write, since a second write to a region replaces the first before it is heard. */ +function asOneAnnouncement(texts: ReadonlyArray) { + return texts + .map((text, index) => (index === texts.length - 1 || /[.!?:…]$/.test(text) ? text : `${text}.`)) + .join(" "); +} -/** One polite live region for the open thread. */ +/** + * The open thread's polite live regions. Status has its own, so "Needs + * approval" landing a moment after a message doesn't replace it unheard. + */ export const ThreadActivityAnnouncer = memo(function ThreadActivityAnnouncer({ threadKey, status, @@ -16,35 +48,141 @@ export const ThreadActivityAnnouncer = memo(function ThreadActivityAnnouncer({ runId, runStatus, detailBehind, + level, + entries, + workspaceRoot, }: ThreadActivitySnapshot & { /** Null while the timeline shows another thread during a switch. */ readonly threadKey: string | null; /** See isDetailBehindShell. */ readonly detailBehind: boolean; + readonly level: ScreenReaderAnnouncements; + /** The thread's entries before any are hidden; unread at the "status" level. */ + readonly entries: ReadonlyArray; + readonly workspaceRoot: string | undefined; }) { const { regionRef, announce, clear } = useLiveRegion(); - const memoryRef = useRef<{ threadKey: string; memory: ThreadAnnouncementMemory } | null>(null); + const { + regionRef: detailRegionRef, + announce: announceDetail, + clear: clearDetail, + } = useLiveRegion(); + const memoryRef = useRef<{ + threadKey: string; + level: ScreenReaderAnnouncements; + memory: ThreadAnnouncementMemory; + detail: TurnDetailMemory; + } | null>(null); + // Messages are written at once; a step waits its turn, and a newer one replaces it. + const stepRef = useRef<{ + quietUntil: number; + waiting: { label: string; timer: ReturnType } | null; + }>({ quietUntil: 0, waiting: null }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes thread status changes to the aria-live region after commit + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- writes the turn's status, messages and steps to the aria-live region after commit useEffect(() => { + const step = stepRef.current; + const write = (text: string, quietMs: number) => { + announceDetail(text); + step.quietUntil = Date.now() + quietMs; + }; + const takeWaiting = () => { + const label = step.waiting?.label ?? null; + if (step.waiting !== null) clearTimeout(step.waiting.timer); + step.waiting = null; + return label; + }; + if (threadKey === null) { + takeWaiting(); memoryRef.current = null; clear(); + clearDetail(); + return; + } + const waitingLabel = takeWaiting(); + if (detailBehind) { + // The dropped step counts as unsaid, so it is read once the detail catches up. + if (waitingLabel !== null && memoryRef.current !== null) { + const { detail } = memoryRef.current; + memoryRef.current = { ...memoryRef.current, detail: { ...detail, activity: null } }; + } return; } - if (detailBehind) return; - const previous = memoryRef.current?.threadKey === threadKey ? memoryRef.current.memory : null; - const { memory, announcement } = nextThreadAnnouncement(previous, { + const previous = memoryRef.current?.threadKey === threadKey ? memoryRef.current : null; + const turn = nextThreadAnnouncement(previous?.memory ?? null, { status, requestId, runId, runStatus, }); - memoryRef.current = { threadKey, memory }; - if (previous === null) clear(); - else if (announcement !== null) announce(announcement); - }, [threadKey, status, requestId, runId, runStatus, detailBehind, announce, clear]); + // A new level starts from what the turn already holds, so raising it mid-turn replays nothing. + const previousDetail = previous?.level === level ? previous.detail : null; + const detail = nextTurnDetailAnnouncement(previousDetail, { + ...(level === "status" + ? NO_TURN_DETAIL + : turnDetail(entries, workspaceRoot, previousDetail?.tailId ?? null)), + level, + status, + }); + memoryRef.current = { threadKey, level, memory: turn.memory, detail: detail.memory }; + if (previous === null) { + step.quietUntil = 0; + clear(); + clearDetail(); + return; + } + if (detail.messages.length > 0) { + // NVDA reads two regions written in the same frame in either order, so a + // status that lands with a message is read as its last sentence. + const text = asOneAnnouncement( + turn.announcement === null ? detail.messages : [...detail.messages, turn.announcement], + ); + write(text, holdAfter(text)); + } else if (turn.announcement !== null) { + announce(turn.announcement); + step.quietUntil = Math.max(step.quietUntil, Date.now() + ACTIVITY_GAP_MS); + } + // A waiting label is stale once its step is over or the level no longer reads steps. + const label = + level !== "everything" || detail.memory.activity === null + ? null + : (detail.activity ?? waitingLabel); + if (label === null) return; + const speakStep = () => { + step.waiting = null; + write(label, ACTIVITY_GAP_MS); + }; + const wait = step.quietUntil - Date.now(); + if (wait <= 0) { + speakStep(); + return; + } + const timer = setTimeout(speakStep, wait); + step.waiting = { label, timer }; + // The next run takes the label over; after an unmount nothing is left to speak it. + return () => clearTimeout(timer); + }, [ + threadKey, + status, + requestId, + runId, + runStatus, + detailBehind, + level, + entries, + workspaceRoot, + announce, + clear, + announceDetail, + clearDetail, + ]); // No role="status": Orca 50 maps it to a status bar in Chromium and drops its updates. - return
; + return ( + <> +
+
+ + ); }); diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 3c730df680e5..386abbaa013a 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -89,6 +89,11 @@ function markdownNodeText(node: Nodes): string { return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; } +/** Markdown as one line of the text it renders, without markup or link targets. */ +export function markdownPlainText(markdown: string): string { + return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); +} + function compactMinimapPreview(text: string | null | undefined) { const compact = text?.replace(/\s+/g, " ").trim() ?? ""; return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/chat/turnDetailAnnouncement.test.ts b/apps/web/src/components/chat/turnDetailAnnouncement.test.ts new file mode 100644 index 000000000000..c5eaa080ff92 --- /dev/null +++ b/apps/web/src/components/chat/turnDetailAnnouncement.test.ts @@ -0,0 +1,320 @@ +import { MessageId, RunAttemptId, RunId, type ScreenReaderAnnouncements } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import type { TimelineAttempt, TimelineEntry, WorkLogEntry } from "../../session-logic"; +import { + nextTurnDetailAnnouncement, + turnDetail, + type TurnDetailMemory, + type TurnDetailSnapshot, + type TurnMessage, +} from "./turnDetailAnnouncement"; + +const run = RunId.make("run-1"); +const at = "2026-01-01T00:00:00.000Z"; + +function message( + id: string, + role: "user" | "assistant", + fields: Partial["message"]> = {}, +): TimelineEntry { + return { + kind: "message", + id, + createdAt: at, + message: { + id: MessageId.make(id), + role, + text: id, + runId: role === "assistant" ? run : null, + streaming: false, + createdAt: at, + updatedAt: at, + ...fields, + }, + }; +} + +function work(id: string, fields: Partial = {}): TimelineEntry { + return { + kind: "work", + id, + createdAt: at, + entry: { id, createdAt: at, runId: run, label: id, tone: "tool", ...fields }, + }; +} + +const prompt = message("prompt", "user"); +const command = (id: string, fields: Partial = {}) => + work(id, { + itemType: "command_execution", + command: "git status", + toolLifecycleStatus: "inProgress", + ...fields, + }); +const notice = work("notice", { itemType: "system_notice", tone: "info", label: "Heads up" }); +const steer = message("steer", "user", { inputIntent: "steer" }); +const time = (clock: string) => DateTime.makeUnsafe(`2026-01-01T${clock}.000Z`); +const inAttempt = ( + entry: TimelineEntry, + id: string, + status: TimelineAttempt["status"], + completed?: string, +): TimelineEntry => ({ + ...entry, + attempt: { + id: RunAttemptId.make(id), + runId: run, + attemptOrdinal: 1, + rootNodeId: `${id}-root` as TimelineAttempt["rootNodeId"], + status, + completedAt: completed === undefined ? null : time(completed), + }, +}); +const completedAt = (entry: TimelineEntry, clock: string) => + ({ + ...entry, + projectedItem: { + item: { type: "assistant_message", status: "completed", completedAt: time(clock) }, + }, + }) as TimelineEntry; + +describe("turnDetail", () => { + it.each<{ + name: string; + entries: ReadonlyArray; + activity: string | null; + }>([ + { name: "a running command", entries: [prompt, command("git")], activity: "Running git" }, + { + name: "reasoning, without its text", + entries: [ + prompt, + work("thought", { itemType: "reasoning", tone: "thinking", detail: "Private idea." }), + ], + activity: "Thinking", + }, + { + name: "a file change, with the verb its icon stands for", + entries: [prompt, work("edit", { itemType: "file_change", changedFiles: ["search.ts"] })], + activity: "Editing search.ts", + }, + { + name: "the step under a request and a notice", + entries: [prompt, command("git"), work("ask", { itemType: "approval_request" }), notice], + activity: "Running git", + }, + { + name: "nothing for a failed step", + entries: [prompt, command("git", { toolLifecycleStatus: "failed" })], + activity: null, + }, + { + name: "nothing once the agent is writing again", + entries: [prompt, command("git"), message("reply", "assistant", { streaming: true })], + activity: null, + }, + { + name: "nothing while the context is compacted", + entries: [ + prompt, + command("git"), + work("compact", { tone: "info", sourceActivityKind: "context-compaction" }), + ], + activity: null, + }, + { + name: "nothing from the turn before", + entries: [message("earlier", "user"), command("git"), prompt], + activity: null, + }, + ])("names $name", ({ entries, activity }) => { + expect(turnDetail(entries, undefined, null).activity).toBe(activity); + }); + + it.each<{ + name: string; + entries: ReadonlyArray; + finished: ReadonlyArray; + }>([ + { + name: "a message the agent kept working after, but not its last", + entries: [ + prompt, + message("first", "assistant"), + command("git"), + message("last", "assistant"), + ], + finished: ["first"], + }, + { + name: "a message once the next one starts", + entries: [ + prompt, + message("first", "assistant"), + message("second", "assistant", { streaming: true }), + ], + finished: ["first"], + }, + { + name: "no reply a steer cut off", + entries: [ + prompt, + inAttempt(message("cut off", "assistant"), "attempt-1", "superseded"), + steer, + inAttempt(command("git"), "attempt-2", "running"), + ], + finished: [], + }, + { + name: "a reply that completed before a steer replaced its attempt", + entries: [ + prompt, + completedAt( + inAttempt(message("complete", "assistant"), "attempt-1", "superseded", "00:00:10"), + "00:00:04", + ), + steer, + inAttempt(command("git"), "attempt-2", "running"), + ], + finished: ["complete"], + }, + { + name: "no last message that only a notice follows", + entries: [prompt, command("git"), message("last", "assistant"), notice], + finished: [], + }, + { + name: "no last message when another run picks the thread up", + entries: [ + prompt, + message("last", "assistant"), + command("git", { runId: RunId.make("run-2") }), + ], + finished: [], + }, + ])("counts $name as finished", ({ entries, finished }) => { + const { messages } = turnDetail(entries, undefined, null); + expect(messages.filter((spoken) => spoken.finished).map((spoken) => spoken.text)).toEqual( + finished, + ); + }); + + it.each<{ name: string; knownTailId: string | null; fresh: ReadonlyArray }>([ + { name: "after the entry last seen", knownTailId: "seen", fresh: [false, true] }, + { name: "after a prompt that was last seen", knownTailId: "prompt", fresh: [true, true] }, + { name: "not when the entry last seen is gone", knownTailId: "gone", fresh: [false, false] }, + ])("marks messages as fresh $name", ({ knownTailId, fresh }) => { + const entries = [ + prompt, + message("loaded", "assistant"), + command("seen"), + message("new", "assistant"), + command("git"), + ]; + expect( + turnDetail(entries, undefined, knownTailId).messages.map((spoken) => spoken.fresh), + ).toEqual(fresh); + }); +}); + +type Frame = Pick; +const said = (id: string, finished = true, fresh = false): TurnMessage => ({ + id, + text: id, + finished, + fresh, +}); +const frame = ( + activity: string | null, + messages: ReadonlyArray = [], + status: TurnDetailSnapshot["status"] = "working", +): Frame => ({ status, activity, messages }); + +function speak(level: ScreenReaderAnnouncements, frames: ReadonlyArray) { + let memory: TurnDetailMemory | null = null; + const spoken: string[] = []; + for (const next of frames) { + const result = nextTurnDetailAnnouncement(memory, { ...next, level, tailId: null }); + memory = result.memory; + spoken.push(...result.messages); + if (result.activity !== null) spoken.push(result.activity); + } + return spoken; +} + +describe("nextTurnDetailAnnouncement", () => { + const turn = [ + frame(null), + frame("Running git", [said("first", false)]), + frame("Running git", [said("first", false)]), + frame("Reading a.ts", [said("first"), said("second", false)]), + frame(null, [said("first"), said("second")]), + ]; + + it.each<{ level: ScreenReaderAnnouncements; spoken: ReadonlyArray }>([ + { level: "status", spoken: [] }, + { level: "messages", spoken: ["T3 Code: first", "T3 Code: second"] }, + { + level: "everything", + spoken: ["Running git", "T3 Code: first", "Reading a.ts", "T3 Code: second"], + }, + ])("says each message and step once at the $level level", ({ level, spoken }) => { + expect(speak(level, turn)).toEqual(spoken); + }); + + it("stays silent about what was there when the thread opened", () => { + expect( + speak("everything", [ + frame("Running git", [said("first")]), + frame("Running git", [said("first")]), + frame("Reading a.ts", [said("first"), said("second", true, true)]), + ]), + ).toEqual(["T3 Code: second", "Reading a.ts"]); + }); + + it("stays silent about history loaded above the messages it knows", () => { + expect( + speak("messages", [ + frame(null, [said("recent")]), + frame(null, [said("older"), said("recent")]), + frame(null, [said("older"), said("recent")]), + ]), + ).toEqual([]); + }); + + it("reads Markdown as the text it renders and skips a message with none", () => { + const first = { + ...said("first", true, true), + text: "**Tests** pass in `web`.\n\n- See [the docs](https://x.test/a(b)c?token=secret)
", + }; + expect( + speak("messages", [ + frame(null), + frame(null, [first, { ...said("empty", true, true), text: "" }]), + ]), + ).toEqual(["T3 Code: Tests pass in web. See the docs"]); + }); + + it("says a step again after waiting on the user", () => { + expect( + speak("everything", [ + frame(null), + frame("Running git"), + frame("Running git", [], "approval"), + frame("Running git"), + ]), + ).toEqual(["Running git", "Running git"]); + }); + + it("stays silent about a turn that already ended", () => { + expect( + speak("everything", [ + frame(null, [], "idle"), + frame("Running git", [said("first", true, true)], "idle"), + frame("Running git", [said("first")]), + ]), + ).toEqual(["Running git"]); + }); +}); diff --git a/apps/web/src/components/chat/turnDetailAnnouncement.ts b/apps/web/src/components/chat/turnDetailAnnouncement.ts new file mode 100644 index 000000000000..0728674ad874 --- /dev/null +++ b/apps/web/src/components/chat/turnDetailAnnouncement.ts @@ -0,0 +1,202 @@ +import type { RunId, ScreenReaderAnnouncements } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import type { TimelineEntry, WorkLogEntry } from "../../session-logic"; +import { + liveWorkEntryLabel, + timelineEntryRunId, + timelineEntryStartsResponse, +} from "./MessagesTimeline.logic"; +import { markdownPlainText } from "./timelineMinimapItems"; + +export interface TurnMessage { + readonly id: string; + /** Markdown. */ + readonly text: string; + /** The agent stopped writing it and went on working. A turn's closing reply never is. */ + readonly finished: boolean; + /** It arrived after the entry the caller last saw, unlike history loaded above it. */ + readonly fresh: boolean; +} + +export interface TurnDetail { + /** The step the agent is on, or null when its newest output is not a step. */ + readonly activity: string | null; + /** The agent's messages in the latest turn, oldest first. */ + readonly messages: ReadonlyArray; + /** The thread's newest entry. */ + readonly tailId: string | null; +} + +export const NO_TURN_DETAIL: TurnDetail = { activity: null, messages: [], tailId: null }; + +const ACTIVITY_MAX_LENGTH = 120; +// Parsing is synchronous, and nobody listens to a longer message through a live region. +const MESSAGE_MAX_LENGTH = 2_000; + +// On screen these labels are a path or a query beside an icon. +function withVerb(work: WorkLogEntry, label: string) { + if (work.itemType === "file_change") return `Editing ${label}`; + if (work.itemType !== "file_search" && work.itemType !== "web_search") return label; + if (/^search(?:ed|ing)?\s/i.test(label)) return label; + return `${work.itemType === "web_search" ? "Searching the web for" : "Searching for"} ${label}`; +} + +type MessageEntry = Extract; + +// A steer starts a new attempt in the same run. The reply it cut off also stops streaming, +// so only one that completed before the steer finished; see completeSupersededReplyEntryIds. +function completedBeforeSuperseded(entry: MessageEntry) { + const item = entry.projectedItem?.item; + const supersededAt = entry.attempt?.completedAt ?? null; + return ( + item?.type === "assistant_message" && + item.status === "completed" && + item.completedAt !== null && + supersededAt !== null && + DateTime.isLessThan(item.completedAt, supersededAt) + ); +} + +function stepLabel(work: WorkLogEntry, workspaceRoot: string | undefined): string | null { + // Reasoning text is never read out. + if (work.itemType === "reasoning") return "Thinking"; + const status = work.toolLifecycleStatus; + if (status === "failed" || status === "declined" || status === "stopped") return null; + const label = liveWorkEntryLabel(work, workspaceRoot, true).replace(/\s+/g, " ").trim(); + if (label === "") return null; + const spoken = withVerb(work, label); + return spoken.length > ACTIVITY_MAX_LENGTH ? `${spoken.slice(0, ACTIVITY_MAX_LENGTH)}…` : spoken; +} + +/** + * What a screen reader can be told about the latest turn beyond its status. + * It reads the thread's entries before "Tool calls in chat" hides any, so what + * is spoken follows the announcement setting alone. + */ +export function turnDetail( + entries: ReadonlyArray, + workspaceRoot: string | undefined, + knownTailId: string | null, +): TurnDetail { + const messages: TurnMessage[] = []; + // Runs and attempts the agent kept working in after the entry being looked at. + const continuedRunIds = new Set(); + const continuedAttemptIds = new Set(); + const markContinued = (entry: TimelineEntry, runId: RunId | null) => { + continuedRunIds.add(runId); + if (entry.attempt !== undefined) continuedAttemptIds.add(entry.attempt.id); + }; + let activity: string | null | undefined; + let fresh = true; + let index = entries.length - 1; + for (; index >= 0; index -= 1) { + const entry = entries[index]!; + if (timelineEntryStartsResponse(entry)) break; + if (entry.id === knownTailId) fresh = false; + if (entry.kind === "event") continue; + if (entry.kind === "work") { + const work = entry.entry; + if (work.sourceActivityKind === "context-compaction") { + activity ??= null; + continue; + } + // Notices, todo lists and checkpoints sit beside the turn's steps without being one. + if (work.tone !== "tool" && work.itemType !== "reasoning") continue; + markContinued(entry, work.runId ?? null); + // A request is spoken as the thread's status; once answered, the step it was for goes on. + if (work.itemType === "approval_request" || work.itemType === "user_input_request") continue; + if (activity === undefined) activity = stepLabel(work, workspaceRoot); + continue; + } + if (entry.kind === "message" && entry.message.role !== "assistant") continue; + // A reply, plan or rendered page is newer than any step before it. + activity ??= null; + const runId = timelineEntryRunId(entry); + if (entry.kind === "message") { + messages.push({ + id: entry.message.id, + text: entry.message.text, + finished: + !entry.message.streaming && + continuedRunIds.has(runId) && + (entry.attempt?.status !== "superseded" || + continuedAttemptIds.has(entry.attempt.id) || + completedBeforeSuperseded(entry)), + fresh, + }); + } + markContinued(entry, runId); + } + // Nothing is known to be new when the entry last seen is gone, or there was none. + let tailKnown = !fresh; + if (knownTailId !== null) { + for (; !tailKnown && index >= 0; index -= 1) tailKnown = entries[index]!.id === knownTailId; + } + return { + activity: activity ?? null, + messages: (tailKnown + ? messages + : messages.map((message) => ({ ...message, fresh: false })) + ).reverse(), + tailId: entries.at(-1)?.id ?? null, + }; +} + +export interface TurnDetailSnapshot extends TurnDetail { + readonly level: ScreenReaderAnnouncements; + readonly status: "working" | "approval" | "input" | "idle"; +} + +export interface TurnDetailMemory { + readonly activity: string | null; + /** Each message seen in the turn, and whether it was already finished then. */ + readonly messages: ReadonlyMap; + readonly tailId: string | null; +} + +/** The heading every agent message has in the timeline. */ +const MESSAGE_AUTHOR = "T3 Code"; + +/** + * Decides which of the turn's messages and steps a screen reader hears next. + * The first snapshot of a thread is a silent baseline, like its status. + */ +export function nextTurnDetailAnnouncement( + previous: TurnDetailMemory | null, + next: TurnDetailSnapshot, +): { + readonly memory: TurnDetailMemory; + readonly messages: ReadonlyArray; + readonly activity: string | null; +} { + const memory: TurnDetailMemory = { + // A step is spoken again after a pause for an approval or a question. + activity: next.status === "working" ? next.activity : null, + messages: new Map(next.messages.map((message) => [message.id, message.finished])), + tailId: next.tailId, + }; + // A turn that already ended is history, however late its entries arrive. + if (previous === null || next.level === "status" || next.status === "idle") { + return { memory, messages: [], activity: null }; + } + return { + memory, + messages: next.messages + .filter( + (message) => + message.finished && + previous.messages.get(message.id) !== true && + (message.fresh || previous.messages.has(message.id)), + ) + .map((message) => + message.text.length > MESSAGE_MAX_LENGTH + ? `${markdownPlainText(message.text.slice(0, MESSAGE_MAX_LENGTH))} More in the thread.` + : markdownPlainText(message.text), + ) + .filter((text) => text !== "") + .map((text) => `${MESSAGE_AUTHOR}: ${text}`), + activity: + next.level === "everything" && memory.activity !== previous.activity ? memory.activity : null, + }; +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index a37bf1581990..3dc9566e8981 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -22,6 +22,7 @@ import { type ResponseStreamingMode, type QuitConfirmationMode, SidebarProjectSortOrder, + ScreenReaderAnnouncements, ToolCallVisibility, } from "@t3tools/contracts/settings"; import { desktopUpdateChannelOf } from "@t3tools/shared/cliRelease"; @@ -539,6 +540,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.toolCallVisibility !== DEFAULT_UNIFIED_SETTINGS.toolCallVisibility ? ["Tool calls in chat"] : []), + ...(settings.screenReaderAnnouncements !== DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements + ? ["Screen reader announcements"] + : []), ...(settings.responseStreamingMode !== DEFAULT_UNIFIED_SETTINGS.responseStreamingMode ? ["Response streaming"] : []), @@ -654,6 +658,7 @@ export function useSettingsRestore(onRestored?: () => void) { sendShortcut: DEFAULT_UNIFIED_SETTINGS.sendShortcut, followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, toolCallVisibility: DEFAULT_UNIFIED_SETTINGS.toolCallVisibility, + screenReaderAnnouncements: DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements, environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, @@ -1208,6 +1213,7 @@ export function ChatSettingsPanel() { + ); @@ -1262,6 +1268,65 @@ function ToolCallVisibilityRow() { ); } +const SCREEN_READER_ANNOUNCEMENTS_LABELS: Record = { + status: "Status only", + messages: "Status and messages", + everything: "Everything", +}; + +const isScreenReaderAnnouncements = Schema.is(ScreenReaderAnnouncements); + +function ScreenReaderAnnouncementsRow() { + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + return ( + + updateSettings({ + screenReaderAnnouncements: DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements, + }) + } + /> + ) : null + } + control={ + + } + /> + ); +} + function DiffColorsSettingsRow() { const settings = useScopedSettings(); const updateSettings = useUpdateScopedSettings(); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index f7492035874d..4f61ba41c0d8 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -483,6 +483,14 @@ export const SETTINGS_SEARCH_ITEMS = [ "hide tool calls commands edits searches work log activity quiet chat zen final answers only", ], }, + { + id: "screen-reader-announcements", + title: "Screen reader announcements", + to: "/settings/chat", + searchTerms: [ + "accessibility a11y screen reader nvda jaws voiceover orca narrator speech announce read aloud messages activity steps", + ], + }, { id: "guest-links", title: "Guest links", diff --git a/docs/user/activity-log.md b/docs/user/activity-log.md index d4e6e7e32c94..a2a9278b8089 100644 --- a/docs/user/activity-log.md +++ b/docs/user/activity-log.md @@ -29,3 +29,15 @@ and the agent's last reply, which appears when the turn ends. If you steer while answering, the answer it finished before reading your steer stays too. On web and desktop, Find shows the in-between messages while it is open. Approvals, questions, and errors always show. The setting applies to this browser or device only. + +## Screen reader announcements + +On web and desktop, a screen reader hears the open thread's turn as it runs. **Screen reader +announcements** in **Settings → Chat** sets how much. **Status only** says when a turn starts, +needs your approval or input, and ends. **Status and messages** also reads each message the agent +writes and then keeps working after, once that message is complete. A very long message is cut +short. The reply that closes the turn is not read, so you can read it yourself when you hear +**Done**. **Everything** adds the step the agent is on, such as the command it is running. Steps +are spaced out, so a quick step can be skipped for a newer one. +The agent's reasoning text is never read. The setting follows the agent's real activity, whatever +**Tool calls in chat** hides, and applies to this browser or device only. diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index cd112d84bf9f..346213992e4b 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -346,6 +346,10 @@ export type EffortDisplay = typeof EffortDisplay.Type; export const ToolCallVisibility = Schema.Literals(["showAll", "hideSuccessful", "hideAll", "zen"]); export type ToolCallVisibility = typeof ToolCallVisibility.Type; +/** What the open thread reads to a screen reader: turn status, the agent's in-between messages too, or every step. */ +export const ScreenReaderAnnouncements = Schema.Literals(["status", "messages", "everything"]); +export type ScreenReaderAnnouncements = typeof ScreenReaderAnnouncements.Type; + export const ModelFavorite = Schema.Struct({ provider: ProviderInstanceId, model: TrimmedNonEmptyString, @@ -517,6 +521,9 @@ export const ClientSettingsSchema = Schema.Struct({ toolCallVisibility: ToolCallVisibility.pipe( Schema.withDecodingDefault(Effect.succeed("showAll" as const)), ), + screenReaderAnnouncements: ScreenReaderAnnouncements.pipe( + Schema.withDecodingDefault(Effect.succeed("status" as const)), + ), // Retired Labs toggle. Still read as the default for the Usage item in threadDetailsItems. threadDetailsUsageEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), // Sparse show/hide overrides for thread details card items. Missing ids use the client's @@ -2029,6 +2036,7 @@ export const ClientSettingsPatch = Schema.Struct({ boringSidebarEnabled: Schema.optionalKey(Schema.Boolean), boringSidebarMultilineRows: Schema.optionalKey(Schema.Boolean), toolCallVisibility: Schema.optionalKey(ToolCallVisibility), + screenReaderAnnouncements: Schema.optionalKey(ScreenReaderAnnouncements), threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), From a536ff7ac0c080190f098965d0a0d244caf5b211 Mon Sep 17 00:00:00 2001 From: Victor Date: Wed, 11 Nov 2026 02:08:48 -0600 Subject: [PATCH 034/436] fix(server): thread search finds phrases inside quotes and their comments (#22553) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- .../src/orchestration-v2/ProjectionStore.ts | 10 +- .../src/orchestration-v2/ThreadSearch.test.ts | 107 ++++++++++++++++++ .../src/orchestration-v2/ThreadSearch.ts | 14 ++- .../orchestration-v2/messageSearchIndex.ts | 77 +++++++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../081_ProjectionMessageSearchText.test.ts | 96 ++++++++++++++++ .../081_ProjectionMessageSearchText.ts | 44 +++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 8 files changed, 332 insertions(+), 20 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.test.ts create mode 100644 apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 89183b48a8ef..e0f6ba249f29 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -96,6 +96,7 @@ import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; +import { readableSearchText } from "./messageSearchIndex.ts"; import { isThreadHistoryUserTurn, isConversationHistoryItem, @@ -2598,7 +2599,8 @@ export const layer: Layer.Layer = streaming, created_at, updated_at, - payload_json + payload_json, + search_text ) VALUES ( ${event.payload.id}, @@ -2609,7 +2611,8 @@ export const layer: Layer.Layer = ${booleanInt(event.payload.streaming)}, ${createdAt}, ${updatedAt}, - ${payloadJson} + ${payloadJson}, + ${readableSearchText(event.payload.text)} ) ON CONFLICT(message_id) DO UPDATE SET @@ -2620,7 +2623,8 @@ export const layer: Layer.Layer = streaming = excluded.streaming, created_at = excluded.created_at, updated_at = excluded.updated_at, - payload_json = excluded.payload_json + payload_json = excluded.payload_json, + search_text = excluded.search_text `; break; } diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index e758280f9388..421e79f5a090 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + EnvironmentId, EventId, MessageId, ProjectId, @@ -18,9 +19,11 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as SqlClient from "effect/sql/SqlClient"; +import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { rebuildMessageSearch } from "./messageSearchIndex.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProjectStore from "./ProjectStore.ts"; import * as ThreadSearch from "./ThreadSearch.ts"; @@ -150,6 +153,20 @@ const message = ( }, }); +// The prefix and suffix are hidden selection context, not text the reader sees. +const quote = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("environment:local"), + threadId: ThreadId.make("thread:quoted"), + messageId: MessageId.make("quoted-answer"), + text: "A lighthouse guides ships safely through the darkness.", + comment: "what are you talking about", + start: 0, + end: 54, + prefix: "beacon01", + suffix: "harbor", +}); + it.effect.each([true, false])( "ThreadSearch excludes bootstrap text before the hit and candidate limits (indexed: %s)", (indexed) => @@ -349,6 +366,96 @@ it.layer(layerTest)("ThreadSearch", (it) => { }), ); + it.effect("matches the readable text of quotes and their comments", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const search = yield* ThreadSearch.ThreadSearch; + const project = ProjectId.make("project:search-citation"); + const threadId = ThreadId.make("thread:citation"); + yield* createProject(project); + yield* Effect.forEach( + [ + thread(threadId, project), + message(threadId, "citation", "user", `${quote} quiet silver lantern`), + ], + projections.apply, + { discard: true }, + ); + const snippets = (query: string) => + Effect.map(search.search({ query }), (result) => + result.matches + .filter((match) => match.threadId === threadId) + .map((match) => match.snippet), + ); + + const readable = + "A lighthouse guides ships safely through the darkness. Comment: what are you talking about quiet silver lantern"; + assert.deepEqual(yield* snippets("what are you talking about"), [ + `…${readable.slice(readable.indexOf("the darkness"))}`, + ]); + assert.deepEqual(yield* snippets("ships safely through"), [readable]); + assert.deepEqual(yield* snippets("beacon01"), []); + assert.deepEqual(yield* snippets("harbor"), []); + + yield* projections.apply(message(threadId, "citation", "user", "quiet silver lantern")); + assert.deepEqual(yield* snippets("what are you talking about"), []); + assert.deepEqual(yield* snippets("lantern"), ["quiet silver lantern"]); + }), + ); + + it.effect("finds accented, CJK, and apostrophe words of a quote through the index", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const search = yield* ThreadSearch.ThreadSearch; + const project = ProjectId.make("project:search-citation-index"); + const threadId = ThreadId.make("thread:citation-index"); + // The stored link percent-encodes these words; the index must hold them as they read. + const encodedQuote = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("environment:local"), + threadId: ThreadId.make("thread:quoted"), + messageId: MessageId.make("quoted-answer"), + text: "The kittiwake's résumé mentions 灯台の光 twice.", + comment: "naïve question в логах", + start: 0, + end: 44, + prefix: "", + suffix: "", + }); + yield* createProject(project); + yield* Effect.forEach( + [thread(threadId, project), message(threadId, "citation-index", "user", encodedQuote)], + projections.apply, + { discard: true }, + ); + const index = yield* sql` + SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search' + `; + assert.lengthOf(index, 1); + const threadIds = (query: string) => + search.search({ query }).pipe(Effect.map(({ matches }) => matches.map((m) => m.threadId))); + + for (const query of [ + "kittiwake's", + "kittiwake’s", + "résumé", + "灯台の光", + "naïve", + "логах в", + ]) { + assert.deepEqual(yield* threadIds(query), [threadId], query); + } + // `t3 doctor` rebuilds the index after VACUUM; quotes must still read. + yield* rebuildMessageSearch(sql); + assert.deepEqual(yield* threadIds("résumé"), [threadId]); + + yield* projections.apply(message(threadId, "citation-index", "user", "plain words")); + assert.deepEqual(yield* threadIds("résumé"), []); + assert.deepEqual(yield* threadIds("plain"), [threadId]); + }), + ); + it.effect("indexes a message when it finishes streaming and follows later edits", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ThreadSearch.ts b/apps/server/src/orchestration-v2/ThreadSearch.ts index 04f68ef64c34..d3c96a40ce2b 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.ts @@ -33,7 +33,11 @@ import { type ThreadSearchSubject, } from "@t3tools/shared/paletteSearch"; import { threadSearchPullRequests } from "@t3tools/shared/threadPullRequests"; -import { indexedMessageCondition, nonPlaceholderMessageCondition } from "./messageSearchIndex.ts"; +import { + indexedMessageCondition, + messageSearchText, + nonPlaceholderMessageCondition, +} from "./messageSearchIndex.ts"; import { loadOlderSettledThreadsPage } from "./ShellStream.ts"; // When the user last wrote in the thread aliased `threads`, as the clients @@ -203,7 +207,7 @@ export const messageHitsQuery = ( messages.thread_id AS "threadId", eligible.project_id AS "projectId", messages.role AS source, - json_extract(messages.payload_json, '$.text') AS text, + ${messageSearchText(sql)} AS text, messages.created_at AS "messageCreatedAt" FROM orchestration_v2_projection_messages AS messages INNER JOIN eligible ON eligible.thread_id = messages.thread_id @@ -220,7 +224,7 @@ export const messageHitsQuery = ( messages.thread_id AS "threadId", eligible.project_id AS "projectId", messages.role AS source, - json_extract(messages.payload_json, '$.text') AS text, + ${messageSearchText(sql)} AS text, messages.created_at AS "messageCreatedAt" FROM orchestration_v2_message_search INNER JOIN orchestration_v2_projection_messages AS messages @@ -241,13 +245,13 @@ export const messageHitsQuery = ( AND messages.message_id NOT LIKE 'async-answer:%' AND NOT EXISTS ( SELECT 1 FROM json_each(${substrings}) AS token - WHERE instr(lower(json_extract(messages.payload_json, '$.text')), token.value) = 0 + WHERE instr(lower(${messageSearchText(sql)}), token.value) = 0 ) AND NOT EXISTS ( SELECT 1 FROM json_each(${shortSpellings}) AS token WHERE NOT EXISTS ( SELECT 1 FROM json_each(token.value) AS spelling - WHERE instr(json_extract(messages.payload_json, '$.text'), spelling.value) > 0 + WHERE instr(${messageSearchText(sql)}, spelling.value) > 0 ) ) -- The index's own rowid, so FTS5 returns hits newest first and stops at diff --git a/apps/server/src/orchestration-v2/messageSearchIndex.ts b/apps/server/src/orchestration-v2/messageSearchIndex.ts index dbd3545e5906..87d7256b6809 100644 --- a/apps/server/src/orchestration-v2/messageSearchIndex.ts +++ b/apps/server/src/orchestration-v2/messageSearchIndex.ts @@ -1,3 +1,4 @@ +import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import * as Effect from "effect/Effect"; import type * as SqlClient from "effect/sql/SqlClient"; @@ -40,46 +41,83 @@ export const indexedMessageCondition = (sql: SqlClient.SqlClient, row = "message AND ${nonPlaceholderMessageCondition(sql, row)} `; +// Curly apostrophes straight, as search folds a query, since iOS keyboards +// type "’" and others type "'". +const foldApostrophes = (text: string) => `replace(replace(${text}, '’', ''''), '‘', '''')`; + +const readableText = (row: string) => + `COALESCE(${row}.search_text, json_extract(${row}.payload_json, '$.text'))`; + +/** + * What search_text holds for a message: its text as it reads, a quote's + * percent-encoded link replaced by its words and comment. NULL when that is + * the stored text, so most messages store nothing extra. + */ +export const readableSearchText = (text: string) => { + const readable = assistantCitationsToPlainText(text); + return readable === text ? null : readable; +}; + +/** A message's text as it reads, for thread search. */ +export const messageSearchText = (sql: SqlClient.SqlClient) => + sql.literal(readableText("messages")); + /** - * What the index stores for a message: its text with curly apostrophes - * straight, as search folds a query, since iOS keyboards type "’" and others - * type "'". Migration 69's triggers use it too. `payload` is the message's + * A message's stored text with apostrophes folded, what the index held before + * migration 81. Migration 69's backfill uses it. `payload` is the message's * JSON column. */ export const indexedMessageText = (sql: SqlClient.SqlClient, payload: string) => - sql.literal(`replace(replace(json_extract(${payload}, '$.text'), '’', ''''), '‘', '''')`); + sql.literal(foldApostrophes(`json_extract(${payload}, '$.text')`)); + +// What the index stores: a message's readable text with apostrophes folded. +// Migrations 69 and 74 create the triggers before migration 81 adds +// search_text, and `t3 doctor` can rebuild a database that has not migrated, +// so those fall back to the stored text. +const indexedText = Effect.fn("MessageSearchIndex.indexedText")(function* ( + sql: SqlClient.SqlClient, +) { + const column = yield* sql` + SELECT 1 FROM pragma_table_info('orchestration_v2_projection_messages') + WHERE name = 'search_text' + `; + return column.length > 0 + ? (row: string) => sql.literal(foldApostrophes(readableText(row))) + : (row: string) => indexedMessageText(sql, `${row}.payload_json`); +}); export const createMessageSearchTriggers = Effect.fn("MessageSearchIndex.createTriggers")( function* (sql: SqlClient.SqlClient) { + const text = yield* indexedText(sql); yield* sql` CREATE TRIGGER orchestration_v2_message_search_insert AFTER INSERT ON orchestration_v2_projection_messages WHEN ${indexedMessageCondition(sql, "new")} BEGIN INSERT INTO orchestration_v2_message_search (rowid, text) - SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")} + SELECT new.rowid, ${text("new")} WHERE json_extract(new.payload_json, '$.text') IS NOT NULL; END `; // Streaming deltas rewrite the row many times a second; skip them until the - // message settles. Upserts rewrite every column, so a finished message - // re-indexes only when what the index reads changed. Deleting a rowid the - // index never held is a no-op. + // message settles. Upserts rewrite every column, so re-index only when what + // the index stores changed; migration 81's backfill writes only search_text. + // Deleting a rowid the index never held is a no-op. yield* sql` CREATE TRIGGER orchestration_v2_message_search_update - AFTER UPDATE OF payload_json, streaming, role ON orchestration_v2_projection_messages + AFTER UPDATE ON orchestration_v2_projection_messages WHEN (old.streaming = 0 OR new.streaming = 0) AND ( old.streaming IS NOT new.streaming OR old.role IS NOT new.role - OR json_extract(old.payload_json, '$.text') IS NOT json_extract(new.payload_json, '$.text') + OR ${text("old")} IS NOT ${text("new")} OR json_extract(old.payload_json, '$.createdBy') IS NOT json_extract(new.payload_json, '$.createdBy') ) BEGIN DELETE FROM orchestration_v2_message_search WHERE rowid = old.rowid AND old.streaming = 0; INSERT INTO orchestration_v2_message_search (rowid, text) - SELECT new.rowid, ${indexedMessageText(sql, "new.payload_json")} + SELECT new.rowid, ${text("new")} WHERE ${indexedMessageCondition(sql, "new")} AND json_extract(new.payload_json, '$.text') IS NOT NULL; END @@ -95,6 +133,20 @@ export const createMessageSearchTriggers = Effect.fn("MessageSearchIndex.createT }, ); +/** Replaces the search triggers with their current definition, where the index exists. */ +export const recreateMessageSearchTriggers = Effect.fn("MessageSearchIndex.recreateTriggers")( + function* (sql: SqlClient.SqlClient) { + const index = yield* sql` + SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search' + `; + if (index.length === 0) return; + yield* sql`DROP TRIGGER orchestration_v2_message_search_insert`; + yield* sql`DROP TRIGGER orchestration_v2_message_search_update`; + yield* sql`DROP TRIGGER orchestration_v2_message_search_delete`; + yield* createMessageSearchTriggers(sql); + }, +); + /** * Refills the search index from the messages table. The index is keyed by * message rowid, so anything that may renumber or copy rows (VACUUM, a dev @@ -108,6 +160,7 @@ export const rebuildMessageSearch = Effect.fn("MessageSearchIndex.rebuild")(func SELECT 1 FROM sqlite_master WHERE name = 'orchestration_v2_message_search' `; if (index.length === 0) return; + const text = yield* indexedText(sql); // One transaction: an interrupt between clear and refill would leave an // empty index that nothing repairs, since search only checks the table exists. yield* sql.withTransaction( @@ -118,7 +171,7 @@ export const rebuildMessageSearch = Effect.fn("MessageSearchIndex.rebuild")(func `; yield* sql` INSERT INTO orchestration_v2_message_search (rowid, text) - SELECT messages.rowid, ${indexedMessageText(sql, "messages.payload_json")} + SELECT messages.rowid, ${text("messages")} FROM orchestration_v2_projection_messages AS messages WHERE ${indexedMessageCondition(sql)} AND json_extract(messages.payload_json, '$.text') IS NOT NULL diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 6a9c57e18cc4..500e986aef44 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -83,6 +83,7 @@ import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts"; import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts"; import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts"; import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts"; +import Migration0081 from "./Migrations/081_ProjectionMessageSearchText.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -166,6 +167,7 @@ const migrationEntries = [ [78, "DropOrchestrationEventCorrelationIndex", Migration0078], [79, "DelegatedRecoveryIndexes", Migration0079], [80, "ScheduledTaskThreadMode", Migration0080], + [81, "ProjectionMessageSearchText", Migration0081], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.test.ts b/apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.test.ts new file mode 100644 index 000000000000..84ca7f9de23a --- /dev/null +++ b/apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.test.ts @@ -0,0 +1,96 @@ +import { assert, it } from "@effect/vitest"; +import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts"; +import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations"; +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { runMigrations } from "../Migrations.ts"; + +const createdAt = "2026-10-01T00:00:00.000Z"; +const quote = serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("environment:local"), + threadId: ThreadId.make("thread:quoted"), + messageId: MessageId.make("quoted-answer"), + text: "A lighthouse guides ships safely through the darkness.", + comment: "what are you talking about", + start: 0, + end: 54, + prefix: "beacon01", + suffix: "harbor", +}); +const readable = + "A lighthouse guides ships safely through the darkness.\nComment: what are you talking about"; +const indexed = (sql: SqlClient.SqlClient, phrase: string) => + sql<{ readonly message_id: string }>` + SELECT messages.message_id + FROM orchestration_v2_message_search AS search + INNER JOIN orchestration_v2_projection_messages AS messages + ON messages.rowid = search.rowid + WHERE orchestration_v2_message_search MATCH ${phrase} + `.pipe(Effect.map((rows) => rows.map((row) => row.message_id))); + +it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))( + "081_ProjectionMessageSearchText", + (it) => { + it.effect("backfills readable text only for messages whose citations read differently", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations({ toMigrationInclusive: 80 }); + const insertMessage = (messageId: string, text: unknown) => sql` + INSERT INTO orchestration_v2_projection_messages ( + message_id, thread_id, role, streaming, created_at, updated_at, payload_json + ) VALUES ( + ${messageId}, 'thread:quote', 'user', 0, ${createdAt}, ${createdAt}, + ${JSON.stringify({ text })} + ) + `; + yield* insertMessage("quoted", `${quote} quiet silver lantern`); + yield* insertMessage("plain", "quiet silver lantern"); + yield* insertMessage("invalid", "[Assistant quote](t3-citation://v1/not-a-citation)"); + yield* insertMessage("unreadable", 20261001); + yield* insertMessage( + "accented", + serializeAssistantCitation({ + version: 1, + environmentId: EnvironmentId.make("environment:local"), + threadId: ThreadId.make("thread:quoted"), + messageId: MessageId.make("quoted-answer"), + text: "The kittiwake's résumé", + start: 0, + end: 22, + prefix: "", + suffix: "", + }), + ); + yield* Effect.forEach( + Array.from({ length: 501 }, (_, index) => `page-${String(index).padStart(3, "0")}`), + (messageId) => insertMessage(messageId, quote), + { discard: true }, + ); + + assert.deepEqual(yield* runMigrations({ toMigrationInclusive: 81 }), [ + [81, "ProjectionMessageSearchText"], + ]); + const rows = yield* sql<{ + readonly message_id: string; + readonly search_text: string | null; + }>`SELECT message_id, search_text FROM orchestration_v2_projection_messages`; + const searchText = new Map(rows.map((row) => [row.message_id, row.search_text])); + assert.equal(searchText.get("quoted"), `${readable} quiet silver lantern`); + assert.isNull(searchText.get("plain")); + assert.isNull(searchText.get("invalid")); + assert.isNull(searchText.get("unreadable")); + assert.equal(searchText.get("page-000"), readable); + assert.equal(searchText.get("page-500"), readable); + + // Messages indexed as stored are indexed again as they read. + assert.deepEqual(yield* indexed(sql, '"résumé"'), ["accented"]); + assert.deepEqual(yield* indexed(sql, `"kittiwake's"`), ["accented"]); + assert.deepEqual(yield* indexed(sql, '"beacon01"'), []); + assert.lengthOf(yield* indexed(sql, '"what are you talking about"'), 502); + }), + ); + }, +); diff --git a/apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.ts b/apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.ts new file mode 100644 index 000000000000..4bbcec4d6182 --- /dev/null +++ b/apps/server/src/persistence/Migrations/081_ProjectionMessageSearchText.ts @@ -0,0 +1,44 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { + readableSearchText, + recreateMessageSearchTriggers, +} from "../../orchestration-v2/messageSearchIndex.ts"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE orchestration_v2_projection_messages ADD COLUMN search_text TEXT`; + + // Migration 74's triggers index the stored text, where a quote's words are + // percent-encoded. Recreated now that search_text exists, they index it, and + // the backfill below re-indexes every message that reads differently. + yield* recreateMessageSearchTriggers(sql); + + // Only messages holding a citation link read differently. The raw check + // first skips parsing the JSON of every other message. + const pageSize = 500; + let afterMessageId = ""; + while (true) { + const rows = yield* sql<{ readonly message_id: string; readonly text: string }>` + SELECT message_id, json_extract(payload_json, '$.text') AS text + FROM orchestration_v2_projection_messages + WHERE message_id > ${afterMessageId} + AND payload_json LIKE '%t3-citation://%' + AND json_type(payload_json, '$.text') = 'text' + ORDER BY message_id + LIMIT ${pageSize} + `; + for (const row of rows) { + const searchText = readableSearchText(row.text); + if (searchText === null) continue; + yield* sql` + UPDATE orchestration_v2_projection_messages + SET search_text = ${searchText} + WHERE message_id = ${row.message_id} + `; + } + if (rows.length < pageSize) break; + afterMessageId = rows.at(-1)!.message_id; + } +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 84fa4ddb44c7..8acfd0cb6b9c 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -60,6 +60,7 @@ describe("V2 preview upgrade", () => { [78, "DropOrchestrationEventCorrelationIndex"], [79, "DelegatedRecoveryIndexes"], [80, "ScheduledTaskThreadMode"], + [81, "ProjectionMessageSearchText"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -163,6 +164,7 @@ describe("V2 preview upgrade", () => { [78, "DropOrchestrationEventCorrelationIndex"], [79, "DelegatedRecoveryIndexes"], [80, "ScheduledTaskThreadMode"], + [81, "ProjectionMessageSearchText"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); From f697d4db3e32c30a1ff16f9970ee4d69e9f608d5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 00:14:08 -0800 Subject: [PATCH 035/436] fix(web): local server cards in the browser empty state take pointer clicks (#34050) --- .../preview/PreviewView.browser.test.tsx | 65 ++++++++++++++++--- .../src/components/preview/PreviewView.tsx | 10 +-- 2 files changed, 60 insertions(+), 15 deletions(-) diff --git a/apps/web/src/components/preview/PreviewView.browser.test.tsx b/apps/web/src/components/preview/PreviewView.browser.test.tsx index a73f88be9fdf..1f1494fa2736 100644 --- a/apps/web/src/components/preview/PreviewView.browser.test.tsx +++ b/apps/web/src/components/preview/PreviewView.browser.test.tsx @@ -30,6 +30,7 @@ const mocks = vi.hoisted(() => ({ addImage: vi.fn(), pictureInPicture: false, showEmptyState: false, + idleServerTab: false, loading: false, nativeServerTab: false, serverEpoch: null as string | null, @@ -112,17 +113,29 @@ vi.mock(import("~/previewStateStore"), async (original) => ({ recentlySeenUrls: [], sessions: mocks.showEmptyState ? {} - : { - "tab-1": { - threadId: "thread-1", - tabId: "tab-1", - runtime: mocks.nativeServerTab ? "server" : "desktop", - navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" }, - canGoBack: false, - canGoForward: false, - updatedAt: "2026-07-13T00:00:00.000Z", + : mocks.idleServerTab + ? { + "tab-1": { + threadId: "thread-1", + tabId: "tab-1", + runtime: "server", + navStatus: { _tag: "Idle" }, + canGoBack: false, + canGoForward: false, + updatedAt: "2026-07-13T00:00:00.000Z", + }, + } + : { + "tab-1": { + threadId: "thread-1", + tabId: "tab-1", + runtime: mocks.nativeServerTab ? "server" : "desktop", + navStatus: { _tag: "Success", url: "http://example.com/", title: "Example" }, + canGoBack: false, + canGoForward: false, + updatedAt: "2026-07-13T00:00:00.000Z", + }, }, - }, })) as never, })); vi.mock(import("~/state/environments"), async (original) => ({ @@ -151,6 +164,13 @@ vi.mock(import("~/browser/previewRuntime"), async (original) => ({ })); vi.mock(import("~/browser/browserViewportActions"), { spy: true }); +// The real surface opens a preview stream to the server; only its box matters here. +vi.mock(import("~/browser/ServerBrowserSurface"), async (original) => ({ + ...(await original()), + ServerBrowserSurface: ((props: { className?: string }) => ( +
+ )) as never, +})); import { useComposerDraftStore } from "~/composerDraftStore"; import { useBrowserPointerStore } from "~/browser/browserPointerStore"; @@ -201,6 +221,7 @@ function setup() { mocks.pickElement.mockReset(); mocks.pictureInPicture = false; mocks.showEmptyState = false; + mocks.idleServerTab = false; mocks.loading = false; mocks.nativeServerTab = false; mocks.serverEpoch = null; @@ -287,6 +308,30 @@ describe("PreviewView", () => { expect(mocks.addImage).not.toHaveBeenCalled(); }); + it("lets the pointer reach a local server card above an idle server-rendered tab", async () => { + setup(); + mocks.idleServerTab = true; + mocks.servers = [ + { + host: "localhost", + port: 8081, + url: "http://localhost:8081/", + requestedUrl: "http://localhost:8081/", + processName: "python3", + pid: 4242, + terminal: null, + source: "scanner", + }, + ]; + await using _screen = await render({view()}); + const card = page.getByRole("button", { name: /localhost:8081/ }); + await expect.element(card).toBeVisible(); + + const rect = card.element().getBoundingClientRect(); + const hit = document.elementFromPoint(rect.x + rect.width / 2, rect.y + rect.height / 2); + expect(card.element().contains(hit)).toBe(true); + }); + it("focuses and selects the address from forwarded desktop actions only while visible", async () => { setup(); using stack = new DisposableStack(); diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 253a4fc14e56..9225e61afeaf 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -991,7 +991,10 @@ export function PreviewView({
) : null}
showPreviewPopup(threadRef, popupTabId, "panel")} // Stays connected under the empty state so a URL picked there reaches the page. - className={cn( - "absolute inset-0 h-full w-full", - (showEmptyState || isUnreachable) && "invisible", - )} + className="absolute inset-0 h-full w-full" />
From fc5edd347b99459e09b9e394d4239fcdc63dbb83 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 11 Nov 2026 00:24:28 -0800 Subject: [PATCH 036/436] fix(server): worktrees cut from a non-default base no longer show the base's PR (#22861) Co-authored-by: Claude Opus 5.5 Co-authored-by: Julius Marminge --- apps/server/src/git/GitManager.test.ts | 40 ++++++++++++++++++++++++++ apps/server/src/git/GitManager.ts | 17 +++++------ 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 72b3504807c9..1eebcdeb4f93 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -2630,6 +2630,46 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect( + "status does not inherit a release PR from a worktree's non-default base upstream", + () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["push", "origin", "main:dev"]); + yield* runGit(repoDir, ["fetch", "origin"]); + yield* runGit(repoDir, ["remote", "set-head", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/from-dev", "origin/dev"]); + yield* runGit(repoDir, ["config", "branch.feature/from-dev.t3-merge-base", "dev"]); + + const { manager, providerCalls } = yield* makeManager({ + providerScenario: { + prListByHeadSelector: { + dev: [ + { + number: 49, + title: "Release dev to main", + url: "https://github.com/pingdotgg/codething-mvp/pull/49", + baseRefName: "main", + headRefName: "dev", + state: "merged", + updatedAt: "2026-08-20T10:00:00Z", + }, + ], + }, + }, + }); + + const status = yield* manager.status({ cwd: repoDir }); + expect(status.refName).toBe("feature/from-dev"); + expect(status.pr).toBeNull(); + expect(listedSelectors(providerCalls).includes("dev")).toBe(false); + }), + ); + it.effect("status finds a PR pushed under the branch's own name despite a default upstream", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index db0d3c91ad19..c8f107ee7060 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -1787,7 +1787,7 @@ export const make = Effect.gen(function* () { return remoteUrl === null ? null : remoteName; }); - // worktree add can set origin/main as upstream; this base is not the branch's published PR head. + // worktree add can set the branch's base as upstream; that is not its published PR head. const resolveLookupHeadContext = Effect.fn("resolveLookupHeadContext")(function* ( cwd: string, details: { @@ -1809,15 +1809,16 @@ export const make = Effect.gen(function* () { }; } } - const upstreamHeadIsDefault = + if (headContext.headBranch === details.branch || headContext.isCrossRepository) { + return { headContext, lookup: true }; + } + const upstreamHeadIsBase = headContext.headBranch === details.defaultBranch || (details.defaultBranch === null && - (headContext.headBranch === "main" || headContext.headBranch === "master")); - if ( - headContext.headBranch === details.branch || - !upstreamHeadIsDefault || - headContext.isCrossRepository - ) { + (headContext.headBranch === "main" || headContext.headBranch === "master")) || + headContext.headBranch === + (yield* gitCore.readBranchBase(cwd, details.branch).pipe(Effect.orElseSucceed(() => null))); + if (!upstreamHeadIsBase) { return { headContext, lookup: true }; } const remoteName = yield* findRemoteTrackingRemote( From 6e21f8146149b2b35c3f301986ed2a2dfc177113 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 00:29:41 -0800 Subject: [PATCH 037/436] fix(desktop): wait for the local server to exit when quitting (#22996) Co-authored-by: Claude Opus 5.5 --- .../src/backend/DesktopBackendManager.test.ts | 15 +- .../src/backend/DesktopBackendManager.ts | 26 ++- .../src/backend/DesktopBackendPool.test.ts | 187 +++++++++++++++--- 3 files changed, 184 insertions(+), 44 deletions(-) diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.ts index 2741daa1ddd0..3126d12a2e93 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.test.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts @@ -421,7 +421,7 @@ describe("DesktopBackendManager", () => { ), ); - it.effect("starts the configured backend and closes the scoped process on stop", () => + it.effect("stops the scoped process with output still pending", () => Effect.scoped( Effect.gen(function* () { let startCount = 0; @@ -458,6 +458,7 @@ describe("DesktopBackendManager", () => { yield* Scope.addFinalizer(scope, close); return makeProcess({ + stdout: Stream.never, exitCode: Deferred.await(closed).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))), kill: () => close, }); @@ -721,14 +722,12 @@ describe("DesktopBackendManager", () => { ), ); - it.effect("the quit stop deadline waits for a backend that only exits at the force kill", () => + it.effect("the quit stop keeps waiting for a backend that outlasts its deadline", () => Effect.scoped( Effect.gen(function* () { const spawned = yield* Deferred.make(); const teardownStarted = yield* Deferred.make(); const teardownFinished = yield* Deferred.make(); - // The real spawner sends SIGTERM, waits the grace, then SIGKILLs. A backend that - // ignores SIGTERM therefore finishes tearing down just after the grace. const instance = yield* makeTestInstance({ spawnerLayer: Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, @@ -739,7 +738,7 @@ describe("DesktopBackendManager", () => { yield* Scope.addFinalizer( scope, Deferred.succeed(teardownStarted, undefined).pipe( - Effect.andThen(Effect.sleep(Duration.seconds(6))), + Effect.andThen(Effect.sleep(Duration.seconds(10))), Effect.andThen(Deferred.succeed(teardownFinished, undefined)), Effect.asVoid, ), @@ -764,11 +763,11 @@ describe("DesktopBackendManager", () => { .pipe(Effect.andThen(Deferred.succeed(quitDone, undefined)), Effect.forkChild); yield* Deferred.await(teardownStarted); - // Past the SIGTERM grace but before the force kill lands: quit must still be waiting. - yield* TestClock.adjust(Duration.millis(5_500)); + // Past the quit deadline, quit must still wait for the backend to exit. + yield* TestClock.adjust(Duration.seconds(9)); assert.isFalse(yield* Deferred.isDone(quitDone)); - yield* TestClock.adjust(Duration.millis(500)); + yield* TestClock.adjust(Duration.seconds(1)); yield* Fiber.join(quitFiber); assert.isTrue(yield* Deferred.isDone(teardownFinished)); }).pipe(Effect.provide(TestClock.layer())), diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.ts index 98de41e24715..d24b2f52f295 100644 --- a/apps/desktop/src/backend/DesktopBackendManager.ts +++ b/apps/desktop/src/backend/DesktopBackendManager.ts @@ -240,6 +240,7 @@ export interface DesktopBackendInstance { readonly id: BackendInstanceId; readonly label: Effect.Effect; readonly start: Effect.Effect; + /** Timeout controls the warning; stop still waits for process teardown and exit. */ readonly stop: (options?: { readonly timeout?: Duration.Duration }) => Effect.Effect; readonly currentConfig: Effect.Effect>; readonly snapshot: Effect.Effect; @@ -307,7 +308,7 @@ const closeRun = ( run: ActiveBackendRun, parentScope: Scope.Scope, options?: { readonly timeout?: Duration.Duration }, -): Effect.Effect => { +) => { const waitForFiber = Option.match(run.fiber, { onNone: () => Effect.void, onSome: (fiber) => Fiber.await(fiber).pipe(Effect.asVoid), @@ -319,12 +320,24 @@ const closeRun = ( const timeout = options?.timeout; if (!timeout) { - return close.pipe(Effect.as(true)); + return close; } - return Effect.forkIn(close, parentScope).pipe( + return Effect.forkIn(close, parentScope, { startImmediately: true }).pipe( Effect.flatMap((closeFiber) => - Fiber.await(closeFiber).pipe(Effect.timeoutOption(timeout), Effect.map(Option.isSome)), + Fiber.await(closeFiber).pipe( + Effect.timeoutOption(timeout), + Effect.tap((completed) => + Option.isNone(completed) + ? logBackendProcessWarning("backend shutdown exceeded timeout; waiting for exit", { + timeoutMs: Duration.toMillis(timeout), + }) + : Effect.void, + ), + // Parent-scope interruption still finishes release; do not cancel sibling stops. + Effect.andThen(Fiber.await(closeFiber)), + Effect.asVoid, + ), ), ); }; @@ -1099,10 +1112,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* ( onNone: () => Effect.void, // The enclosing operation owns the span for this inline handler. onSome: Effect.fnUntraced(function* (run) { - const closed = yield* closeRun(run, parentScope, options); - if (!closed) { - return; - } + yield* closeRun(run, parentScope, options); const cleanup = yield* mutex.withPermits(1)( SubscriptionRef.modify( state, diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.ts index 2b2dd841ab53..b4c7827ce1ae 100644 --- a/apps/desktop/src/backend/DesktopBackendPool.test.ts +++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts @@ -1,11 +1,17 @@ import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; +import * as TestClock from "effect/testing/TestClock"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; -import { HttpClient } from "effect/http"; +import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as DesktopObservability from "../app/DesktopObservability.ts"; @@ -21,18 +27,105 @@ import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts"; import * as DesktopBackendPool from "./DesktopBackendPool.ts"; import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts"; -function layerPool(labelRef: Ref.Ref): Layer.Layer { +// Models the spawner's release for a backend that ignores SIGTERM, without OS signals. +const makeFakeBackendProcess = Effect.fn("test.makeFakeBackendProcess")(function* () { + const started = yield* Deferred.make(); + const exited = yield* Deferred.make(); + const signals = yield* Queue.unbounded<"SIGTERM" | "SIGKILL">(); + let running = false; + const killWait = Duration.seconds(1); + const exit = Effect.sync(() => { + running = false; + }).pipe(Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0))), Effect.asVoid); + const layer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if (command._tag !== "StandardCommand") { + return yield* Effect.die("Expected a standard backend command"); + } + const terminateGrace = Duration.fromInputUnsafe(command.options.forceKillAfter ?? 0); + running = true; + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + yield* Queue.offer(signals, "SIGTERM"); + yield* Effect.sleep(terminateGrace); + yield* Queue.offer(signals, "SIGKILL"); + yield* Effect.sleep(killWait); + yield* exit; + }), + ); + yield* Deferred.succeed(started, undefined); + return ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + exitCode: Deferred.await(exited), + isRunning: Effect.sync(() => running), + kill: () => exit, + unref: Effect.succeed(Effect.void), + }); + }), + ), + ); + return { + layer, + started: Deferred.await(started), + signals, + isRunning: Effect.sync(() => running), + killWait, + }; +}); + +const runningConfig = { + executablePath: "/electron", + args: [], + entryPath: "/server/bin.mjs", + cwd: "/server", + env: {}, + bootstrap: { + mode: "desktop", + noBrowser: true, + port: 3774, + t3Home: "/tmp/t3", + host: "127.0.0.1", + desktopBootstrapToken: "token", + tailscaleServeEnabled: false, + tailscaleServePort: 443, + }, + bootstrapDelivery: "fd3", + extendEnv: true, + httpBaseUrl: new URL("http://127.0.0.1:3774"), + captureOutput: false, + preflightFailure: Option.none(), +} satisfies DesktopBackendStartConfig; + +function layerPool( + labelRef: Ref.Ref, + backend?: Effect.Success>, +): Layer.Layer { return DesktopBackendPool.layer.pipe( Layer.provideMerge( Layer.mergeAll( - FileSystem.layerNoop({}), - Layer.succeed( - ChildProcessSpawner.ChildProcessSpawner, - ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")), - ), + FileSystem.layerNoop({ exists: () => Effect.succeed(true) }), + backend?.layer ?? + Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")), + ), Layer.succeed( HttpClient.HttpClient, - HttpClient.make(() => Effect.die("unexpected HTTP request")), + HttpClient.make((request) => + backend === undefined + ? Effect.die("unexpected HTTP request") + : Effect.succeed( + HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })), + ), + ), ), Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, { forInstance: () => @@ -90,6 +183,62 @@ function layerPool(labelRef: Ref.Ref): Layer.Layer { + it.effect("unregister during pool quit does not interrupt sibling stops", () => + Effect.scoped( + Effect.gen(function* () { + const backend = yield* makeFakeBackendProcess(); + yield* Effect.gen(function* () { + const pool = yield* DesktopBackendPool.DesktopBackendPool; + const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu"); + const ready = yield* Deferred.make(); + const siblingStarted = yield* Deferred.make(); + const finishSibling = yield* Deferred.make(); + let siblingCompleted = false; + const instance = yield* pool.register({ + id, + label: Effect.succeed("WSL (Ubuntu)"), + configResolve: Effect.succeed(runningConfig), + onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid), + }); + yield* instance.start; + yield* backend.started; + yield* Deferred.await(ready); + const quitFiber = yield* Effect.all( + [ + instance.stop({ timeout: Duration.seconds(5) }), + Deferred.succeed(siblingStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishSibling)), + Effect.andThen( + Effect.sync(() => { + siblingCompleted = true; + }), + ), + ), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.forkChild); + yield* Deferred.await(siblingStarted); + assert.equal(yield* Queue.take(backend.signals), "SIGTERM"); + const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild); + yield* TestClock.adjust(Duration.seconds(5)); + assert.equal(yield* Queue.take(backend.signals), "SIGKILL"); + assert.isUndefined(quitFiber.pollUnsafe()); + assert.isUndefined(unregisterFiber.pollUnsafe()); + assert.isTrue(yield* backend.isRunning); + yield* TestClock.adjust(backend.killWait); + yield* Fiber.join(unregisterFiber); + yield* Deferred.succeed(finishSibling, undefined); + yield* Fiber.join(quitFiber); + + assert.isTrue(siblingCompleted); + assert.isFalse(yield* backend.isRunning); + assert.isTrue(Option.isNone((yield* instance.snapshot).activePid)); + assert.isTrue(Option.isNone(yield* pool.get(id))); + }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), backend))); + }), + ), + ); + it.effect("unregister stops the registered instance", () => Effect.scoped( Effect.gen(function* () { @@ -99,27 +248,9 @@ describe("DesktopBackendPool", () => { id, label: Effect.succeed("WSL (Ubuntu)"), configResolve: Effect.succeed({ - executablePath: "/electron", - args: [], - entryPath: "/server/bin.mjs", - cwd: "/server", - env: {}, - bootstrap: { - mode: "desktop", - noBrowser: true, - port: 3774, - t3Home: "/tmp/t3", - host: "127.0.0.1", - desktopBootstrapToken: "token", - tailscaleServeEnabled: false, - tailscaleServePort: 443, - }, - bootstrapDelivery: "fd3", - extendEnv: true, - httpBaseUrl: new URL("http://127.0.0.1:3774"), - captureOutput: false, + ...runningConfig, preflightFailure: Option.some({ reason: "WSL starting", fatal: false }), - } satisfies DesktopBackendStartConfig), + }), }); yield* instance.start; assert.equal((yield* instance.snapshot).restartScheduled, true); From c50dd8e12d694110d7344707668b85b01583875f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 00:40:00 -0800 Subject: [PATCH 038/436] fix(server): agent continuations preserve the working timer start (#22947) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 65 +++++- .../src/orchestration-v2/runtimeLayer.test.ts | 212 ++++++++++++++++++ 2 files changed, 265 insertions(+), 12 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 07c1a544798b..feeafd2d408f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -508,23 +508,41 @@ function nextRunOrdinal(projection: Pick Math.max(max, run.ordinal), 0) + 1; } -/** Stamp at wake start; queued prompts lack start times and delegated results jump the queue. */ +/** + * Stamp at wake start; queued prompts lack start times and delegated results jump the queue. + * Auto-drained agent messages continue active work; explicit queue starts reset it. + */ function wakeWorkStartedAt( - runs: ReadonlyArray, - trigger: { + projection: Pick, + trigger: Pick< + OrchestrationV2ConversationMessage, + "createdBy" | "creationSource" | "senderThreadId" + > & { readonly notification?: unknown; readonly delegatedCompletion?: unknown; readonly restartContinuationOfRunId?: RunId | undefined; }, + delivery: "immediate" | "automatic-queue" | "explicit-queue" = "immediate", ): Pick { if ( trigger.notification === undefined && trigger.delegatedCompletion === undefined && - trigger.restartContinuationOfRunId === undefined + trigger.restartContinuationOfRunId === undefined && + !( + trigger.createdBy === "agent" && + trigger.creationSource === "mcp" && + trigger.senderThreadId !== undefined && + (delivery === "automatic-queue" || + (delivery === "immediate" && + projection.subagents.some( + (subagent) => + subagent.origin === "app_owned" && subagent.childThreadId === trigger.senderThreadId, + ))) + ) ) { return {}; } - const previous = runs + const previous = projection.runs .flatMap((run) => (run.startedAt === null ? [] : [{ run, startedAt: run.startedAt }])) .toSorted( (left, right) => @@ -2372,6 +2390,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), updatedAt: now, }; + // Resume can clear the hold before the stopped run ends; its Stop marker still makes the drain explicit. + const endedRunId = options?.endedRunId; + const queueDelivery = + endedRunId === undefined || + queuedRun.queueHeld === true || + (yield* projectionStore + .getThreadRecords(threadId, ["turnItems"], { + turnItemTypes: ["run_interrupt_request"], + turnItemRunIds: [endedRunId], + }) + .pipe( + Effect.map(({ turnItems }) => turnItems.length > 0), + Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })), + )) + ? "explicit-queue" + : "automatic-queue"; const startingRun: OrchestrationV2Run = { ...queuedRun, providerThreadId: queuedProviderThread.id, @@ -2380,11 +2414,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuePosition: null, startedAt: null, contextHandoffId: activeHandoff?.id ?? null, - ...wakeWorkStartedAt(projection.runs, { - notification: queuedMessage.notification, - delegatedCompletion: queuedMessage.delegatedCompletion, - restartContinuationOfRunId: queuedRun.restartContinuationOfRunId, - }), + ...wakeWorkStartedAt( + projection, + { + createdBy: queuedMessage.createdBy, + creationSource: queuedMessage.creationSource, + senderThreadId: queuedMessage.senderThreadId, + notification: queuedMessage.notification, + delegatedCompletion: queuedMessage.delegatedCompletion, + restartContinuationOfRunId: queuedRun.restartContinuationOfRunId, + }, + queueDelivery, + ), }; const userTurnItem: OrchestrationV2TurnItem = { ...(legacyQueuedTurnItem ?? { @@ -6969,7 +7010,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? { workspacePreparation: dispatchMode.workspaceStrategy } : {}), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), - ...wakeWorkStartedAt(projection.runs, command), + ...wakeWorkStartedAt(projection, command), ...(freshContext ? { freshContext: true } : {}), }; const attempt: OrchestrationV2RunAttempt = { @@ -7755,7 +7796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? {} : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }), ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }), - ...wakeWorkStartedAt(projection.runs, command), + ...wakeWorkStartedAt(projection, command), }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 25ccef8c1108..61dcab69c0ca 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -5512,6 +5512,218 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each([ + { origin: "agent" as const, delivery: "queued" as const }, + { origin: "agent" as const, delivery: "after-completion" as const }, + { origin: "agent" as const, delivery: "held-resume" as const }, + { origin: "agent" as const, delivery: "resume-before-stop-ends" as const }, + { origin: "child" as const, delivery: "after-completion" as const }, + { origin: "user" as const, delivery: "queued" as const }, + ])( + "preserves queued agent and child updates but resets fresh requests (%j)", + ({ origin, delivery }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make(`work-clock-${origin}-${delivery}`); + const originalMessageId = MessageId.make(`${threadId}-original`); + const followUpMessageId = MessageId.make(`${threadId}-follow-up`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}-create`), + threadId, + projectId: ProjectId.make(`${threadId}-project`), + title: "Agent message work clock", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}-original`), + threadId, + messageId: originalMessageId, + text: "Original user work", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const dispatchFollowUp = orchestrator.dispatch({ + type: "message.dispatch", + createdBy: origin === "user" ? "user" : "agent", + creationSource: origin === "user" ? "web" : "mcp", + ...(origin === "user" ? {} : { senderThreadId: ThreadId.make("sending-agent") }), + commandId: CommandId.make(`${threadId}-follow-up`), + threadId, + messageId: followUpMessageId, + text: "Follow-up work", + attachments: [], + modelSelection, + dispatchMode: { + type: delivery === "after-completion" ? "start_immediately" : "queue_after_active", + }, + }); + const held = delivery === "held-resume" || delivery === "resume-before-stop-ends"; + const drainsOnEnd = delivery === "queued" || delivery === "resume-before-stop-ends"; + if (delivery === "queued" || held) yield* dispatchFollowUp; + const startedRunIds = yield* Queue.unbounded(); + const afterSequence = yield* orchestrator.getThreadEventSequence(threadId); + yield* eventSink.stream({ threadId, afterSequence }).pipe( + Stream.runForEach((stored) => + stored.event.type === "run.updated" && stored.event.payload.status === "starting" + ? Queue.offer(startedRunIds, stored.event.payload.id) + : Effect.void, + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const original = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === originalMessageId, + ); + assert.isDefined(original); + if (origin === "child") { + assert.isNotNull(original.rootNodeId); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-child`), + type: "subagent.updated", + threadId, + runId: original.id, + occurredAt: original.requestedAt, + payload: { + id: NodeId.make(`${threadId}-child`), + threadId, + runId: original.id, + parentNodeId: original.rootNodeId, + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId: original.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make("sending-agent"), + nativeTaskRef: null, + prompt: "Delegated work", + title: null, + model: null, + status: "completed", + result: "Done", + startedAt: original.requestedAt, + completedAt: original.requestedAt, + updatedAt: original.requestedAt, + }, + }, + ], + }); + } + if (held) { + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === followUpMessageId, + ); + assert.isDefined(queued); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-hold`), + type: "run.updated", + threadId, + occurredAt: original.requestedAt, + payload: { ...queued, queueHeld: true }, + }, + { + id: EventId.make(`${threadId}-interrupt-request`), + type: "turn-item.updated", + threadId, + runId: original.id, + occurredAt: original.requestedAt, + payload: { + id: TurnItemId.make(`${threadId}-interrupt-request`), + type: "run_interrupt_request", + threadId, + runId: original.id, + nodeId: original.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 90, + status: "completed", + title: "Interrupt requested", + startedAt: original.requestedAt, + completedAt: original.requestedAt, + updatedAt: original.requestedAt, + message: "Stopped by user", + }, + }, + ], + }); + } + if (delivery === "resume-before-stop-ends") { + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}-resume`), + threadId, + }); + } + const originalStart = DateTime.makeUnsafe("2026-10-21T14:20:17.457Z"); + const completedAt = DateTime.makeUnsafe("2026-10-21T14:23:53.509Z"); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}-completed`), + type: "run.updated", + threadId, + runId: original.id, + ...(original.rootNodeId === null ? {} : { nodeId: original.rootNodeId }), + providerInstanceId: original.providerInstanceId, + occurredAt: completedAt, + payload: { + ...original, + status: held ? "interrupted" : "completed", + startedAt: originalStart, + completedAt, + }, + }, + ], + }); + if (delivery === "held-resume") { + yield* TestClock.adjust("3 hours"); + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === followUpMessageId, + ); + assert.isDefined(queued); + assert.equal(queued.status, "queued"); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}-resume`), + threadId, + }); + } else if (delivery === "after-completion") yield* dispatchFollowUp; + const startedRunId = drainsOnEnd ? yield* Queue.take(startedRunIds) : null; + const followUp = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === followUpMessageId, + ); + assert.isDefined(followUp); + if (drainsOnEnd) assert.equal(startedRunId, followUp.id); + assert.equal(followUp.status, "starting"); + if (origin === "child" || (origin === "agent" && delivery === "queued")) { + assert.isDefined(followUp.workStartedAt); + assert.equal( + DateTime.toEpochMillis(followUp.workStartedAt), + DateTime.toEpochMillis(originalStart), + ); + } else { + assert.isUndefined(followUp.workStartedAt); + } + }), + ); + it.effect.each(["usage_limit", "provider_error"] as const)( "handles a queued message after a %s failure", (failureClass) => From 8c9af5418a3344e7a2063c12be18cafd1a79ad60 Mon Sep 17 00:00:00 2001 From: CursedApple <36764254+Serendeep@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:45:20 +0100 Subject: [PATCH 039/436] fix(web): disable the git actions menu when nothing in it is usable (#31972) Co-authored-by: Julius Marminge --- .../GitActionsControl.logic.test.ts | 24 +++++++++++++ .../src/components/GitActionsControl.logic.ts | 13 +++++++ apps/web/src/components/GitActionsControl.tsx | 34 ++++++++++++++----- 3 files changed, 62 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.logic.test.ts b/apps/web/src/components/GitActionsControl.logic.test.ts index 43e10293741b..543aaadb20b5 100644 --- a/apps/web/src/components/GitActionsControl.logic.test.ts +++ b/apps/web/src/components/GitActionsControl.logic.test.ts @@ -4,6 +4,7 @@ import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import { assert, describe, it } from "vite-plus/test"; import { buildMenuItems, + hasUsableGitMenuContent, requiresDefaultBranchConfirmation, resolveChangesTotals, resolveDefaultBranchActionDialogCopy, @@ -77,6 +78,29 @@ describe("when: ref is clean, up to date, and has no open PR", () => { false, ); }); + + it("offers the actions menu only when something in it is usable", () => { + const hasContent = ( + gitStatus: VcsStatusResult, + overrides: Partial[0]> = {}, + ) => + hasUsableGitMenuContent({ + menuItems: buildMenuItems(gitStatus, false, gitStatus.hasPrimaryRemote), + canWriteSourceControl: true, + canPublishRepository: false, + hasNotice: false, + ...overrides, + }); + const clean = status(); + const dirty = status({ hasWorkingTreeChanges: true }); + + assert.isFalse(hasContent(clean)); + assert.isTrue(hasContent(dirty)); + assert.isTrue(hasContent(status({ aheadCount: 1 }))); + assert.isFalse(hasContent(dirty, { canWriteSourceControl: false })); + assert.isTrue(hasContent(status({ hasPrimaryRemote: false }), { canPublishRepository: true })); + assert.isTrue(hasContent(clean, { hasNotice: true })); + }); }); describe("when: on default ref without open PR", () => { diff --git a/apps/web/src/components/GitActionsControl.logic.ts b/apps/web/src/components/GitActionsControl.logic.ts index 5effb44c79a8..c5814842eb04 100644 --- a/apps/web/src/components/GitActionsControl.logic.ts +++ b/apps/web/src/components/GitActionsControl.logic.ts @@ -174,6 +174,19 @@ export function buildMenuItems( ]; } +export function hasUsableGitMenuContent(input: { + readonly menuItems: readonly GitActionMenuItem[]; + readonly canWriteSourceControl: boolean; + readonly canPublishRepository: boolean; + readonly hasNotice: boolean; +}): boolean { + return ( + input.canPublishRepository || + input.hasNotice || + (input.canWriteSourceControl && input.menuItems.some((item) => !item.disabled)) + ); +} + export function resolveQuickAction( gitStatus: VcsStatusResult | null, isBusy: boolean, diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index c927aa302c6e..4e236f0b58c1 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -46,6 +46,7 @@ import { buildMenuItems, formatGitActionElapsed, GIT_ACTION_SUCCESS_VISIBLE_MS, + hasUsableGitMenuContent, type GitActionProgressPresentation, type GitActionIconName, type GitActionMenuItem, @@ -1395,6 +1396,23 @@ export default function GitActionsControl({ const canPublishRepository = canWriteSourceControl && isRepo && gitStatusForActions !== null && !hasPrimaryRemote; + const isDetachedHead = gitStatusForActions?.refName === null; + const isCleanAndBehind = + gitStatusForActions !== null && + gitStatusForActions.refName !== null && + !gitStatusForActions.hasWorkingTreeChanges && + gitStatusForActions.behindCount > 0 && + gitStatusForActions.aheadCount === 0; + const hasGitMenuContent = hasUsableGitMenuContent({ + menuItems: gitActionMenuItems, + canWriteSourceControl, + canPublishRepository, + hasNotice: isDetachedHead || isCleanAndBehind || Boolean(gitStatusError), + }); + + // A disabled menu cannot refresh on open, and terminal edits or commits publish no status. + const refreshStatusForEmptyMenu = () => + requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd); const initializeGit = () => { void (async () => { @@ -1466,19 +1484,15 @@ export default function GitActionsControl({ Publish repository... ) : null} - {gitStatusForActions?.refName === null && ( + {isDetachedHead && (

Detached HEAD: create and check out a branch to enable push and{" "} {changeRequestTerminology.singular} actions.

)} - {gitStatusForActions && - gitStatusForActions.refName !== null && - !gitStatusForActions.hasWorkingTreeChanges && - gitStatusForActions.behindCount > 0 && - gitStatusForActions.aheadCount === 0 && ( -

Behind upstream. Pull/rebase first.

- )} + {isCleanAndBehind && ( +

Behind upstream. Pull/rebase first.

+ )} {gitStatusError &&

{gitStatusError}

} ); @@ -1506,6 +1520,8 @@ export default function GitActionsControl({ role="group" aria-label="Git actions" ref={panelAnchorRef} + onPointerEnter={hasGitMenuContent ? undefined : refreshStatusForEmptyMenu} + onFocus={hasGitMenuContent ? undefined : refreshStatusForEmptyMenu} className={cn( "shrink-0", THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS, @@ -1613,7 +1629,7 @@ export default function GitActionsControl({ panel /> } - disabled={isGitActionRunning} + disabled={isGitActionRunning || !hasGitMenuContent} >