From 7c050441d9dc682cd882af335e762ed52fa61f44 Mon Sep 17 00:00:00 2001 From: BelKed <66956532+BelKed@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:42:36 +0100 Subject: [PATCH 001/140] refactor(web): share the browser dialog card --- apps/web/src/browser/BrowserDialogCard.tsx | 53 +++++++++++++++++ apps/web/src/browser/ServerBrowserSurface.tsx | 57 +++---------------- 2 files changed, 62 insertions(+), 48 deletions(-) create mode 100644 apps/web/src/browser/BrowserDialogCard.tsx diff --git a/apps/web/src/browser/BrowserDialogCard.tsx b/apps/web/src/browser/BrowserDialogCard.tsx new file mode 100644 index 0000000000000..288a3ca7a30d0 --- /dev/null +++ b/apps/web/src/browser/BrowserDialogCard.tsx @@ -0,0 +1,53 @@ +import { useState } from "react"; + +import { Button } from "~/components/ui/button"; +import { Input } from "~/components/ui/input"; + +export function BrowserDialogCard({ + dialog, + canAnswer, + onAnswer, +}: { + readonly dialog: { + readonly type: string; + readonly message: string; + readonly defaultValue: string; + }; + readonly canAnswer: boolean; + readonly onAnswer: (accept: boolean, promptText?: string) => void; +}) { + const [promptText, setPromptText] = useState(dialog.defaultValue); + return ( +
+

{dialog.message}

+ {canAnswer ? ( + <> + {dialog.type === "prompt" ? ( + setPromptText(event.target.value)} + /> + ) : null} +
+ + +
+ + ) : ( +

Take control to respond.

+ )} +
+ ); +} diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsx index a881650f69bcf..6d87bc393be11 100644 --- a/apps/web/src/browser/ServerBrowserSurface.tsx +++ b/apps/web/src/browser/ServerBrowserSurface.tsx @@ -33,10 +33,10 @@ import { useState, } from "react"; +import { BrowserDialogCard } from "./BrowserDialogCard"; import { AgentCursorMark } from "~/components/preview/AgentBrowserCursor"; import { CommandBlock } from "~/components/CommandBlock"; import { Button } from "~/components/ui/button"; -import { Input } from "~/components/ui/input"; import { toastManager } from "~/components/ui/toast"; import { cn } from "~/lib/utils"; import { refreshPreviewStreamAccess, usePreviewStreamAccess } from "~/state/previewStream"; @@ -179,7 +179,6 @@ export function ServerBrowserSurface(props: { const hasFrameRef = useRef(false); const controlRef = useRef(null); const [control, setControl] = useState(null); - const [promptText, setPromptText] = useState(""); const [fileChooser, setFileChooser] = useState(null); const [agentCursor, setAgentCursor] = useState(null); const fileInputRef = useRef(null); @@ -411,11 +410,6 @@ export function ServerBrowserSurface(props: { controlRef.current = next; setControl(next); controlChanged(next); - if ( - next.dialog?.message !== previous?.dialog?.message || - next.dialog?.defaultValue !== previous?.dialog?.defaultValue - ) - setPromptText(next.dialog?.defaultValue ?? ""); if (next.controller !== "you") { clearInput(); } else if (previous?.controller !== "you") { @@ -856,47 +850,14 @@ export function ServerBrowserSurface(props: { ) : null} {control?.dialog ? ( -
-

{control.dialog.message}

- {control.controller === "you" ? ( - <> - {control.dialog.type === "prompt" ? ( - setPromptText(event.target.value)} - /> - ) : null} -
- - -
- - ) : ( -

Take control to respond.

- )} -
+ + send({ type: "dialog", accept, ...(promptText === undefined ? {} : { promptText }) }) + } + /> ) : null} {visible && hostSetup ? ( From 5b2f2e76cae66f7392773a915ed6bf731efcabdb Mon Sep 17 00:00:00 2001 From: BelKed <66956532+BelKed@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:43:15 +0100 Subject: [PATCH 002/140] fix(desktop): page dialogs in Browser tabs stay in their tab --- apps/desktop/src/ipc/channels.ts | 1 + apps/desktop/src/ipc/methods/preview.ts | 11 +++ apps/desktop/src/preload.ts | 6 ++ apps/desktop/src/preview/Manager.test.ts | 93 +++++++++++++++++++- apps/desktop/src/preview/Manager.ts | 66 +++++++++++++- apps/desktop/src/preview/PageDialogs.test.ts | 79 +++++++++++++++++ apps/desktop/src/preview/PageDialogs.ts | 70 +++++++++++++++ packages/contracts/src/ipc.ts | 15 ++++ 8 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 apps/desktop/src/preview/PageDialogs.test.ts create mode 100644 apps/desktop/src/preview/PageDialogs.ts diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index b7bb5e579572f..43a00bf85d802 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -98,6 +98,7 @@ export const PREVIEW_SET_ZOOM_FACTOR_CHANNEL = "desktop:preview-set-zoom-factor" export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload"; export const PREVIEW_SET_COLOR_SCHEME_CHANNEL = "desktop:preview-set-color-scheme"; export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted"; +export const PREVIEW_ANSWER_DIALOG_CHANNEL = "desktop:preview-answer-dialog"; export const PREVIEW_FIND_IN_PAGE_CHANNEL = "desktop:preview-find-in-page"; export const PREVIEW_STOP_FIND_IN_PAGE_CHANNEL = "desktop:preview-stop-find-in-page"; export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index cc810fee072ad..0385af6dacdb9 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -11,6 +11,7 @@ import { DesktopPreviewRecordingSaveInputSchema, DesktopPreviewRegisterWebviewInputSchema, DesktopPreviewScreenshotArtifactSchema, + DesktopPreviewAnswerDialogInputSchema, DesktopPreviewSetAudioMutedInputSchema, DesktopPreviewSetShownInputSchema, DesktopPreviewSetColorSchemeInputSchema, @@ -225,6 +226,15 @@ const setAudioMuted = DesktopIpc.makeIpcMethod({ yield* manager.setAudioMuted(tabId, audioMuted); }), }); +const answerDialog = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_ANSWER_DIALOG_CHANNEL, + payload: DesktopPreviewAnswerDialogInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.answerDialog")(function* ({ tabId, accept, promptText }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.answerDialog(tabId, accept, promptText); + }), +}); const setShown = DesktopIpc.makeIpcMethod({ channel: IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, payload: DesktopPreviewSetShownInputSchema, @@ -487,6 +497,7 @@ export const methods = [ setColorScheme, setZoomFactor, setAudioMuted, + answerDialog, setShown, openDevTools, clearCookies, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index e0ac5f2161051..6002f8599dabf 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -403,6 +403,12 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.PREVIEW_SET_COLOR_SCHEME_CHANNEL, { tabId, colorScheme }), setAudioMuted: (tabId, audioMuted) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_AUDIO_MUTED_CHANNEL, { tabId, audioMuted }), + answerDialog: (tabId, accept, promptText) => + ipcRenderer.invoke(IpcChannels.PREVIEW_ANSWER_DIALOG_CHANNEL, { + tabId, + accept, + ...(promptText === undefined ? {} : { promptText }), + }), findInPage: (tabId, text, { forward, newSession }) => ipcRenderer.invoke(IpcChannels.PREVIEW_FIND_IN_PAGE_CHANNEL, { tabId, diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 1fdb7b286ba1a..bbb0ef073078f 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -338,6 +338,7 @@ const makeTestPreviewWebContents = ( navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -501,6 +502,7 @@ const makeFaviconWebContents = (options?: { focusedFrame: {} as object | null, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], executeJavaScriptInIsolatedWorld, debugger: { isAttached: () => false, @@ -1250,6 +1252,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -1357,6 +1360,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], get debugger() { if (destroyed) throw new Error("Object has been destroyed"); return wcDebugger; @@ -1629,6 +1633,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => attach.mock.calls.length > detach.mock.calls.length + chromiumDetaches, attach, @@ -1709,12 +1714,19 @@ describe("PreviewManager", () => { const makeAudioWebContents = (id: number) => { const listeners = new Map void>(); + let debuggerMessage: ((...args: ReadonlyArray) => void) | undefined; const setAudioMuted = vi.fn(); let audible = false; let audibleAfterFirstRead = false; let audibleReads = 0; return { setAudioMuted, + emit: (event: string, ...args: ReadonlyArray) => { + (listeners.get(event) as ((...args: ReadonlyArray) => void) | undefined)?.( + ...args, + ); + }, + emitDebuggerMessage: (method: string) => debuggerMessage?.({}, method, {}, ""), emitAudioState: (next: boolean) => { audible = next; listeners.get("audio-state-changed")?.({ audible: next } as never); @@ -1746,16 +1758,22 @@ describe("PreviewManager", () => { off: vi.fn((event: string) => { listeners.delete(event); }), + once: vi.fn((event: string, listener: (...args: never[]) => void) => { + listeners.set(event, listener); + }), ipc: { on: vi.fn(), off: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), sendCommand: vi.fn(async () => undefined), - on: vi.fn(), + on: vi.fn((event: string, listener: (...args: ReadonlyArray) => void) => { + if (event === "message") debuggerMessage = listener; + }), off: vi.fn(), }, } as never, @@ -1784,6 +1802,77 @@ describe("PreviewManager", () => { ), ); + effectIt.effect( + "holds a page dialog on its tab until it is answered or the guest goes away", + () => + withManager((manager) => + Effect.gen(function* () { + const guest = makeAudioWebContents(42); + fromId.mockReturnValue(guest.wc); + const states: PreviewManager.PreviewTabState[] = []; + const answer = vi.fn(); + const dialogInfo = { + dialogType: "confirm", + messageText: "Delete it?", + defaultPromptText: "", + }; + + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + states.push(state); + }), + ); + yield* manager.createTab("tab_dialog"); + yield* manager.registerWebview("tab_dialog", 42); + yield* Effect.yieldNow; + + guest.emit("-run-dialog", dialogInfo, answer); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toEqual({ + type: "confirm", + message: "Delete it?", + defaultValue: "", + }); + expect(answer).not.toHaveBeenCalled(); + + yield* manager.answerDialog("tab_dialog", true, undefined); + yield* Effect.yieldNow; + expect(answer).toHaveBeenCalledExactlyOnceWith(true, ""); + expect(states.at(-1)?.dialog).toBeUndefined(); + + const answeredByAgent = vi.fn(); + guest.emit("-run-dialog", dialogInfo, answeredByAgent); + yield* Effect.yieldNow; + guest.emitDebuggerMessage("Page.javascriptDialogClosed"); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeUndefined(); + yield* manager.answerDialog("tab_dialog", true, undefined); + expect(answeredByAgent).not.toHaveBeenCalled(); + + guest.emit("-run-dialog", dialogInfo, vi.fn()); + yield* Effect.yieldNow; + const replacement = makeAudioWebContents(43); + fromId.mockReturnValue(replacement.wc); + yield* manager.registerWebview("tab_dialog", 43); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeUndefined(); + + const doomed = makeAudioWebContents(44); + fromId.mockReturnValue(doomed.wc); + yield* manager.createTab("tab_dialog_destroyed"); + yield* manager.prepareWebview(doomed.wc); + yield* manager.registerWebview("tab_dialog_destroyed", 44); + yield* Effect.yieldNow; + doomed.emit("-run-dialog", dialogInfo, vi.fn()); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeDefined(); + doomed.emit("destroyed"); + yield* Effect.yieldNow; + expect(states.at(-1)?.dialog).toBeUndefined(); + }), + ), + ); + effectIt.effect("ignores audio state from a replaced guest", () => withManager((manager) => Effect.gen(function* () { @@ -2699,6 +2788,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -3301,6 +3391,7 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), + listeners: () => [], debugger: { isAttached: () => false, attach: vi.fn(), diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 8fe4cf1c992af..a2c9077849886 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -11,6 +11,7 @@ import type { DesktopPreviewAnnotationVoiceConfig, DesktopPreviewAnnotationVoiceState, DesktopPreviewColorScheme, + DesktopPreviewDialog, DesktopPreviewFavicon, DesktopPreviewFindResultEvent, DesktopPreviewOpenLinkEvent, @@ -89,6 +90,7 @@ import { START_PICK_CHANNEL, THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; +import { holdPageDialogs, type PageDialogHold } from "./PageDialogs.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS, type RecordingInputOptions } from "./RecordingInput.ts"; @@ -118,6 +120,7 @@ export interface PreviewTabState { audible: boolean; controller: "human" | "agent" | "none"; capturing: boolean; + dialog?: DesktopPreviewDialog; favicon?: DesktopPreviewFavicon; serverTab?: { readonly threadId: string; readonly tabId: string }; updatedAt: string; @@ -614,6 +617,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const tabLifecycleGenerations = new Map(); // A guest can fail its first load before registerWebview installs its tab listeners. const guestLoadFailures = new Map(); + const dialogHolds = new Map(); const attempt = (errorContext: PreviewOperationContext, evaluate: () => A) => Effect.try({ @@ -960,6 +964,33 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value); }); + const syncTabDialog = Effect.fn("PreviewManager.syncTabDialog")(function* ( + tabId: string, + wc: Electron.WebContents, + dialog: DesktopPreviewDialog | null, + ) { + const updatedAt = yield* currentIso; + const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => { + const current = tabs.get(tabId); + if (!current || current.webContentsId !== wc.id) { + return [Option.none(), tabs] as const; + } + const { dialog: _dialog, ...withoutDialog } = current; + const state: PreviewTabState = { + ...withoutDialog, + ...(dialog ? { dialog } : {}), + updatedAt, + }; + return [ + Option.some(state), + replaceMap(tabs, (copy) => { + copy.set(tabId, state); + }), + ] as const; + }); + if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value); + }); + const requireWebContents = Effect.fn("PreviewManager.requireWebContents")(function* ( tabId: string, ) { @@ -1102,6 +1133,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } }); const onMessage: BrowserControlSession["onMessage"] = (_event, method) => { + if (method === "Page.javascriptDialogClosed") dialogHolds.get(wc.id)?.closed(); runFork(handleDebuggerMessage(method)); }; const control: BrowserControlSession = { @@ -1198,6 +1230,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const scope = yield* Scope.fork(parentScope, "sequential"); const attachmentId = Symbol(); let detachPasskeys = () => {}; + let dialogHold: PageDialogHold | undefined; let documentId = 0; let nextRequestId = 0; let activeCapture: { @@ -1654,6 +1687,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); wc.ipc.off(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys(); + if (dialogHolds.get(wc.id) === dialogHold) dialogHolds.delete(wc.id); + dialogHold?.release(); }).pipe(Effect.ignore), ); const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () { @@ -1670,6 +1705,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.on("did-fail-load", failed as never); wc.on("audio-state-changed", audioStateChanged); wc.on("found-in-page", foundInPage as never); + dialogHold = holdPageDialogs(wc, (dialog) => runFork(syncTabDialog(tabId, wc, dialog))); + dialogHolds.set(wc.id, dialogHold); wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput); wc.ipc.on(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); @@ -1964,7 +2001,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function } const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null; const failure = guestLoadFailures.get(webContentsId); - const { favicon: _favicon, ...currentWithoutFavicon } = current; + const { favicon: _favicon, dialog: _dialog, ...currentWithoutFavicon } = current; const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId, @@ -2054,6 +2091,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.once("destroyed", () => { guestLoadFailures.delete(webContentsId); + dialogHolds.get(webContentsId)?.closed(); runFork(hideDestroyedGuest(webContentsId)); runFork(detachControlSession(webContentsId)); }); @@ -2114,6 +2152,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function audible: current?.audible ?? false, controller: current?.controller ?? "none", capturing: current?.capturing ?? false, + ...(current?.dialog ? { dialog: current.dialog } : {}), ...(current?.favicon ? { favicon: current.favicon } : {}), ...(current?.serverTab ? { serverTab: current.serverTab } : {}), updatedAt, @@ -2157,7 +2196,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (current?.webContentsId !== webContentsId) { return [Option.none(), tabs] as const; } - const { favicon: _favicon, ...currentWithoutFavicon } = current; + const { favicon: _favicon, dialog: _dialog, ...currentWithoutFavicon } = current; const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null }; return [ Option.some(next), @@ -2672,6 +2711,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); + const answerDialog = Effect.fn("PreviewManager.answerDialog")(function* ( + tabId: string, + accept: boolean, + promptText: string | undefined, + ) { + const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); + if (!tab) { + return yield* new PreviewTabNotFoundError({ tabId }); + } + const webContentsId = tab.webContentsId; + if (webContentsId === null) return; + yield* attempt({ operation: "answerDialog", tabId, webContentsId }, () => + dialogHolds.get(webContentsId)?.answer(accept, promptText), + ); + }); + const captureScreenshot = Effect.fn("PreviewManager.captureScreenshot")(function* ( tabId: string, ) { @@ -3715,6 +3770,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setAnnotationTheme, setAnnotationSendEnabled, setAudioMuted, + answerDialog, setShown, setColorScheme, setMainWindow, @@ -3931,6 +3987,11 @@ export class PreviewManager extends Context.Service< tabId: string, audioMuted: boolean, ) => Effect.Effect; + readonly answerDialog: ( + tabId: string, + accept: boolean, + promptText: string | undefined, + ) => Effect.Effect; readonly setShown: (tabId: string, shown: boolean) => Effect.Effect; readonly openDevTools: (tabId: string) => Effect.Effect; readonly clearCookies: ( @@ -4093,6 +4154,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { setColorScheme: operations.setColorScheme, setZoomFactor: operations.setZoomFactor, setAudioMuted: operations.setAudioMuted, + answerDialog: operations.answerDialog, setShown: operations.setShown, openDevTools: operations.openDevTools, clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) { diff --git a/apps/desktop/src/preview/PageDialogs.test.ts b/apps/desktop/src/preview/PageDialogs.test.ts new file mode 100644 index 0000000000000..88f9bf31f53d4 --- /dev/null +++ b/apps/desktop/src/preview/PageDialogs.test.ts @@ -0,0 +1,79 @@ +import * as NodeEvents from "node:events"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { holdPageDialogs } from "./PageDialogs.ts"; + +const info = { dialogType: "confirm", messageText: "Delete it?", defaultPromptText: "" }; + +function setup() { + const contents = new NodeEvents.EventEmitter(); + const native = vi.fn(); + contents.on("-run-dialog", native); + const changed = vi.fn(); + const hold = holdPageDialogs(contents, changed); + const callback = vi.fn(); + return { contents, native, changed, hold, callback }; +} + +describe("holdPageDialogs", () => { + it("keeps a page dialog pending instead of showing the native box", () => { + const { contents, native, changed, callback } = setup(); + + contents.emit("-run-dialog", info, callback); + + expect(native).not.toHaveBeenCalled(); + expect(callback).not.toHaveBeenCalled(); + expect(changed).toHaveBeenLastCalledWith({ + type: "confirm", + message: "Delete it?", + defaultValue: "", + }); + }); + + it("answers the page once and clears the dialog", () => { + const { contents, changed, hold, callback } = setup(); + contents.emit("-run-dialog", { ...info, dialogType: "prompt" }, callback); + + expect(hold.answer(true, "yes")).toBe(true); + expect(hold.answer(false)).toBe(false); + + expect(callback).toHaveBeenCalledOnce(); + expect(callback).toHaveBeenCalledWith(true, "yes"); + expect(changed).toHaveBeenLastCalledWith(null); + + const first = vi.fn(); + contents.emit("-run-dialog", info, first); + contents.emit("-run-dialog", info, callback); + expect(first).toHaveBeenCalledExactlyOnceWith(false, ""); + }); + + it("drops a dialog that CDP or a navigation already closed without answering twice", () => { + const { contents, changed, hold, callback } = setup(); + + contents.emit("-run-dialog", info, callback); + hold.closed(); + expect(changed).toHaveBeenLastCalledWith(null); + expect(hold.answer(true)).toBe(false); + + contents.emit("-run-dialog", info, callback); + contents.emit("-cancel-dialogs"); + expect(changed).toHaveBeenLastCalledWith(null); + expect(hold.answer(true)).toBe(false); + expect(callback).not.toHaveBeenCalled(); + }); + + it("dismisses a pending dialog and hands the native handler back on release", () => { + const { contents, native, changed, hold, callback } = setup(); + contents.emit("-run-dialog", info, callback); + callback.mockImplementation(() => { + throw new Error("callback already used"); + }); + + hold.release(); + + expect(callback).toHaveBeenCalledWith(false, ""); + expect(changed).toHaveBeenLastCalledWith(null); + contents.emit("-run-dialog", info, vi.fn()); + expect(native).toHaveBeenCalledOnce(); + }); +}); diff --git a/apps/desktop/src/preview/PageDialogs.ts b/apps/desktop/src/preview/PageDialogs.ts new file mode 100644 index 0000000000000..08c7a86331676 --- /dev/null +++ b/apps/desktop/src/preview/PageDialogs.ts @@ -0,0 +1,70 @@ +import type { DesktopPreviewDialog } from "@t3tools/contracts"; + +type DialogCallback = (accept: boolean, userInput: string) => void; + +interface RunDialogInfo { + readonly dialogType: string; + readonly messageText: string; + readonly defaultPromptText: string; +} + +export interface PageDialogHold { + /** Answers the pending dialog; false when none is pending. */ + readonly answer: (accept: boolean, promptText?: string) => boolean; + /** Forgets the pending dialog after something else, such as CDP, closed it. */ + readonly closed: () => void; + readonly release: () => void; +} + +// Electron shows page dialogs as a native app-modal box from the `-run-dialog` event and never +// closes it when CDP answers. Replacing that listener keeps the dialog pending for the tab's UI. +export function holdPageDialogs( + contents: NodeJS.EventEmitter, + changed: (dialog: DesktopPreviewDialog | null) => void, +): PageDialogHold { + const native = contents.listeners("-run-dialog") as Array<(...args: unknown[]) => void>; + let pending: DialogCallback | null = null; + const clear = () => { + if (pending === null) return; + pending = null; + changed(null); + }; + const deliver = (callback: DialogCallback, accept: boolean, userInput: string) => { + try { + callback(accept, userInput); + return true; + } catch { + return false; + } + }; + const run = (info: RunDialogInfo, callback: DialogCallback) => { + const previous = pending; + if (previous !== null) deliver(previous, false, ""); + pending = callback; + changed({ + type: info.dialogType, + message: info.messageText, + defaultValue: info.defaultPromptText, + }); + }; + for (const listener of native) contents.off("-run-dialog", listener); + contents.on("-run-dialog", run); + contents.on("-cancel-dialogs", clear); + return { + answer: (accept, promptText) => { + const callback = pending; + if (callback === null) return false; + clear(); + return deliver(callback, accept, promptText ?? ""); + }, + closed: clear, + release: () => { + const callback = pending; + clear(); + if (callback !== null) deliver(callback, false, ""); + contents.off("-run-dialog", run); + contents.off("-cancel-dialogs", clear); + for (const listener of native) contents.on("-run-dialog", listener); + }, + }; +} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 8f5258596c5f5..6c2eaaa1a35e3 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -602,6 +602,12 @@ export interface DesktopPreviewFavicon { capturedAt: number; } +export interface DesktopPreviewDialog { + type: string; + message: string; + defaultValue: string; +} + export interface DesktopPreviewTabState { tabId: string; webContentsId: number | null; @@ -617,6 +623,8 @@ export interface DesktopPreviewTabState { controller: "human" | "agent" | "none"; /** A screenshot or stream of the guest is pending, so the client keeps it painting while hidden. */ capturing: boolean; + /** A page dialog waiting for an answer; the guest stays blocked until the client or an agent answers. */ + dialog?: DesktopPreviewDialog; favicon?: DesktopPreviewFavicon; updatedAt: string; } @@ -1016,6 +1024,12 @@ export const DesktopPreviewSetAudioMutedInputSchema = Schema.Struct({ audioMuted: Schema.Boolean, }); +export const DesktopPreviewAnswerDialogInputSchema = Schema.Struct({ + tabId: DesktopPreviewTabIdSchema, + accept: Schema.Boolean, + promptText: Schema.optional(Schema.String), +}); + export const DesktopPreviewSetShownInputSchema = Schema.Struct({ tabId: DesktopPreviewTabIdSchema, shown: Schema.Boolean, @@ -1279,6 +1293,7 @@ export interface DesktopPreviewBridge { hardReload: (tabId: string) => Promise; setColorScheme: (tabId: string, colorScheme: DesktopPreviewColorScheme) => Promise; setAudioMuted: (tabId: string, audioMuted: boolean) => Promise; + answerDialog: (tabId: string, accept: boolean, promptText?: string) => Promise; findInPage: ( tabId: string, text: string, From aaffcbe31107345ecc1ce92a0ccc16b683157c23 Mon Sep 17 00:00:00 2001 From: BelKed <66956532+BelKed@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:44:01 +0100 Subject: [PATCH 003/140] fix(web): answer page dialogs in the desktop Browser panel --- apps/web/src/components/preview/PreviewView.tsx | 13 +++++++++++++ apps/web/src/components/preview/usePreviewBridge.ts | 1 + apps/web/src/previewStateStore.test.ts | 6 +++++- apps/web/src/previewStateStore.ts | 5 +++++ 4 files changed, 24 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 02d856d78ca61..82b7dfb1fd038 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -82,6 +82,7 @@ import { isBrowserSettingsReadError } from "~/browser/openFileInPreview"; import { PreviewFileNotShown, PreviewUnreachable } from "./PreviewUnreachable"; import { revealInFileExplorerLabel } from "./fileExplorerLabel"; import { Badge } from "~/components/ui/badge"; +import { BrowserDialogCard } from "~/browser/BrowserDialogCard"; import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot"; import { alternatePreviewRuntime, useRendersServerTabNatively } from "~/browser/previewRuntime"; import { ServerBrowserSurface, type ServerBrowserHandle } from "~/browser/ServerBrowserSurface"; @@ -1128,6 +1129,18 @@ export function PreviewView({ onOpenUrl={(next) => void handleOpenServerUrl(next)} /> ) : null} + {desktopOverlay?.dialog && runtimeTabId ? ( + + void previewBridge + ?.answerDialog(runtimeTabId, accept, promptText) + .catch(() => undefined) + } + /> + ) : null} {snapshot && desktopOverlay ? ( ) : null} diff --git a/apps/web/src/components/preview/usePreviewBridge.ts b/apps/web/src/components/preview/usePreviewBridge.ts index 294e93147a9c8..38c01e4f40234 100644 --- a/apps/web/src/components/preview/usePreviewBridge.ts +++ b/apps/web/src/components/preview/usePreviewBridge.ts @@ -155,6 +155,7 @@ export function projectDesktopState(state: DesktopPreviewTabState): DesktopPrevi audioMuted: state.audioMuted, audible: state.audible, controller: state.controller, + ...(state.dialog ? { dialog: state.dialog } : {}), favicon: state.favicon && originOf(state.favicon.pageUrl) === navOrigin ? state.favicon : null, }; } diff --git a/apps/web/src/previewStateStore.test.ts b/apps/web/src/previewStateStore.test.ts index 6554dde5f1c25..d72139d374373 100644 --- a/apps/web/src/previewStateStore.test.ts +++ b/apps/web/src/previewStateStore.test.ts @@ -208,9 +208,13 @@ describe("previewStateStore (single-tab)", () => { ...loaded, navStatus: { ...loaded.navStatus, url: "https://example.com/next" }, }); + const dialog = { type: "confirm", message: "Delete it?", defaultValue: "" }; + applyPreviewDesktopState(ref, snapshot.tabId, { ...loaded, dialog }); + applyPreviewDesktopState(ref, snapshot.tabId, { ...loaded, dialog: { ...dialog } }); + applyPreviewDesktopState(ref, snapshot.tabId, loaded); unsubscribe(); - expect(updateCount).toBe(3); + expect(updateCount).toBe(5); }); it("retains multiple tabs and switches active desktop state", () => { diff --git a/apps/web/src/previewStateStore.ts b/apps/web/src/previewStateStore.ts index 6e190e8069ee5..9d1ece685b45d 100644 --- a/apps/web/src/previewStateStore.ts +++ b/apps/web/src/previewStateStore.ts @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { type DesktopPreviewColorScheme, + type DesktopPreviewDialog, type DesktopPreviewFavicon, type PreviewEvent, type PreviewListResult, @@ -25,6 +26,7 @@ export interface DesktopPreviewOverlay { audioMuted: boolean; audible: boolean; controller: "human" | "agent" | "none"; + dialog?: DesktopPreviewDialog; favicon: DesktopPreviewFavicon | null; } @@ -410,6 +412,9 @@ function isPreviewStateEqual( previous.audioMuted === next.audioMuted && previous.audible === next.audible && previous.controller === next.controller && + previous.dialog?.type === next.dialog?.type && + previous.dialog?.message === next.dialog?.message && + previous.dialog?.defaultValue === next.dialog?.defaultValue && previous.favicon?.dataUrl === next.favicon?.dataUrl && previous.favicon?.pageUrl === next.favicon?.pageUrl && previous.favicon?.capturedAt === next.favicon?.capturedAt) From 52074e92585c07ebbf9b21143431f88784705466 Mon Sep 17 00:00:00 2001 From: grey-tsosie <45133231+grey-tsosie@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:48:21 -0800 Subject: [PATCH 004/140] fix(server): stop leaving Codex plan items running after their run (#22617) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Adapters/CodexAdapterV2.ts | 2 ++ .../testkit/fixtures/todo_list/codex_output.ts | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 1589b7d1ea46f..8683c33f05a1f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -4836,6 +4836,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( context, nativeItemId: `turn-plan:${payload.turnId}`, status: "active", + // Each update is a complete snapshot; nothing later completes the item. + completed: true, ...(explanation === undefined ? {} : { explanation }), steps, }); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts index 3b1ff8379f7e4..8fb2b42ce346b 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/codex_output.ts @@ -36,4 +36,12 @@ export function assertTodoListOutput( todoLists.at(-1)?.steps.map((step) => step.status), ["completed", "completed", "completed"], ); + // A completed run must not leave its plan snapshot items running. + assert.deepEqual( + projection.turnItems + .filter((item) => item.type === "todo_list") + .map((item) => item.status) + .filter((status) => status !== "completed"), + [], + ); } From 6fae3c9303315835943327434335a1f5be03295a Mon Sep 17 00:00:00 2001 From: Antony <97451137+TonybynMp4@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:49:32 +0100 Subject: [PATCH 005/140] perf(gitlab): MR watches check a one-query fingerprint before full reads (#34638) Co-authored-by: Julius Marminge --- .../PullRequestWatchReactor.ts | 6 +- .../src/orchestration-v2/runtimeLayer.test.ts | 103 ++++++++++ .../src/server/PullRequestProvider.ts | 2 + .../src/server/GitLabPullRequestCli.ts | 23 +++ .../src/server/GitLabPullRequestProvider.ts | 5 + .../src/server/gitLabMergeRequestJson.test.ts | 103 ++++++++++ .../src/server/gitLabMergeRequestJson.ts | 179 +++++++++++++++++- 7 files changed, 410 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index 46ea6a2f3fcad..4f67f5cb25b2f 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -186,7 +186,11 @@ function planRead( !last.remarksComplete || now - last.at >= FINGERPRINT_REREAD_MS; return { - detail: activity || checksDue || last.status !== fingerprint.status || last.inFlight, + detail: + activity || + checksDue || + last.status !== fingerprint.status || + (last.inFlight && fingerprint.coversDetail !== true), activity, }; } diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 08397c580519d..96add5d1fc48a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -5262,6 +5262,109 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each([true, false])( + "rereads pending checks only on a fingerprint change when it covers them (covers: %s)", + (coversDetail) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make(`runtime-pull-request-watch-covers-${coversDetail}`); + const projectId = ProjectId.make(`pr-watch-covers-project-${coversDetail}`); + yield* seedProject({ + projectId, + title: "Watch pending checks", + workspaceRoot: "/workspace/watch-covers", + defaultModelSelection: null, + createdAt: "2026-10-01T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`pr-watch-covers-create-${coversDetail}`), + threadId, + projectId, + title: "Watch pending checks", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const key = { host: "gitlab.com", repository: "acme/web", number: 15 }; + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`pr-watch-covers-start-${coversDetail}`), + threadId, + ...key, + watching: true, + link: { url: "https://gitlab.com/acme/web/-/merge_requests/15", source: "agent" }, + }); + + let reads = 0; + let status = "running"; + const host = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(PullRequestService.PullRequestService)({ + watchFingerprint: () => Effect.sync(() => ({ status, remarks: "none", coversDetail })), + invalidate: () => Effect.void, + detail: (input) => + Effect.sync(() => { + // Watches left by earlier cases in this layer are swept too. + if (input.projectId === projectId) reads++; + return { + ...watchedPullRequestDetail({ + projectId, + number: 15, + at: "2026-10-02T12:00:00.000Z", + }), + headSha: "6074dd48ff", + checks: [ + { + name: "lint", + status: "pending", + description: null, + url: null, + required: true, + }, + ], + }; + }), + activity: () => + Effect.succeed({ + comments: [], + commentCount: 0, + commentsTruncated: false, + reviewThreads: [], + commits: [], + }), + }), + ); + const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host)); + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sweep = reactor.sweep.pipe(Effect.andThen(worker.drain())); + + yield* sweep; + yield* TestClock.adjust("2 minutes"); + yield* sweep; + assert.equal(reads, coversDetail ? 1 : 2); + + status = "passed"; + yield* TestClock.adjust("2 minutes"); + yield* sweep; + assert.equal(reads, coversDetail ? 2 : 3); + + yield* orchestrator.dispatch({ + type: "thread.pull-request.watch", + commandId: CommandId.make(`pr-watch-covers-end-${coversDetail}`), + threadId, + ...key, + watching: false, + }); + yield* worker.drain(); + }), + ); + // regression: #21155 watching a pull request again repeated news the thread already got it.effect("watching a dismissed stack layer again keeps what its last watch told", () => Effect.gen(function* () { diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index ac71ea56530e2..8ea9eaae216b4 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -75,6 +75,8 @@ export class PullRequestProviderError extends Schema.TaggedError Effect.Effect; + readonly getMergeRequestWatchFingerprint: (input: { + readonly cwd: string; + readonly host?: string | undefined; + readonly repository: string; + readonly number: number; + }) => Effect.Effect; + readonly listNotes: (input: { readonly cwd: string; readonly host?: string | undefined; @@ -2306,6 +2316,19 @@ export const make = Effect.gen(function* () { }), ), + getMergeRequestWatchFingerprint: Effect.fn( + "GitLabPullRequestCli.getMergeRequestWatchFingerprint", + )((input) => + graphqlRead({ + cwd: input.cwd, + host: input.host, + operation: "getMergeRequestWatchFingerprint", + query: MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY, + variables: { fullPath: input.repository, iid: String(input.number) }, + decode: decodeMergeRequestWatchFingerprintJson, + }), + ), + listNotes: Effect.fn("GitLabPullRequestCli.listNotes")(function (input) { return notesPage({ ...input, page: 1, collected: [] }); }), diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts index df9210fb24124..1341205793bfd 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestProvider.ts @@ -380,6 +380,11 @@ export const make = Effect.gen(function* () { })), ), + getChangeRequestWatchFingerprint: (input) => + cli + .getMergeRequestWatchFingerprint(input) + .pipe(Effect.mapError(fail("getChangeRequestWatchFingerprint"))), + getChangeRequestActivity: (input) => Effect.all( [ diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts index 181b73a44b730..f66302d5b43b4 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts @@ -13,6 +13,7 @@ import { decodeMergeRequestListJson, decodeMergeRequestFileStatsJson, decodeMergeRequestStatsJson, + decodeMergeRequestWatchFingerprintJson, decodeReferenceCandidatesJson, decodeNotesJson, decodeOwnAwardIdJson, @@ -1232,3 +1233,105 @@ describe("decodeMergeMessagesJson", () => { expect(Result.isFailure(decoded)).toBe(true); }); }); + +describe("decodeMergeRequestWatchFingerprintJson", () => { + const pipeline = (status: string, downstream: string, failed = 0, moreBridges = false) => ({ + id: "gid://gitlab/Ci::Pipeline/9", + status, + succeeded: { count: 3 }, + failed: { count: failed }, + stopped: { count: 0 }, + jobs: { + pageInfo: { hasNextPage: moreBridges }, + nodes: [ + { + name: "deploy", + status, + downstreamPipeline: { id: "gid://gitlab/Ci::Pipeline/10", status: downstream }, + }, + ], + }, + }); + const edit = (at: string, resolved = false) => ({ + lastEditedAt: at, + lastEditedBy: { username: "reviewer" }, + resolved, + }); + const read = (overrides: Record) => + expectSuccess( + decodeMergeRequestWatchFingerprintJson( + JSON.stringify({ + data: { + project: { + mergeRequest: { + state: "opened", + mergeStatusEnum: "CAN_BE_MERGED", + conflicts: false, + diffHeadSha: "a".repeat(40), + userPermissions: { updateMergeRequest: true }, + headPipeline: pipeline("RUNNING", "RUNNING"), + userNotesCount: 2, + notes: { + nodes: [ + edit("2026-07-02T00:00:00Z"), + { lastEditedAt: null, lastEditedBy: null, resolved: null }, + edit("2026-07-01T00:00:00Z"), + ], + }, + ...overrides, + }, + }, + }, + }), + ), + ); + + // A remarks change makes the watch reread every comment, so pipeline progress must not touch it. + it("moves pipeline progress into status and comment edits into remarks", () => { + const base = read({}); + const passed = read({ headPipeline: pipeline("SUCCESS", "RUNNING") }); + const downstreamPassed = read({ headPipeline: pipeline("SUCCESS", "SUCCESS") }); + const jobFailed = read({ headPipeline: pipeline("RUNNING", "RUNNING", 1) }); + const edited = read({ notes: { nodes: [edit("2026-07-03T00:00:00Z")] } }); + // Resolving a thread restamps its notes without an edit, so it must not reread comments. + const resolved = read({ + notes: { nodes: [edit("2026-07-02T00:00:00Z"), edit("2026-07-03T00:00:00Z", true)] }, + }); + + expect(base?.remarks).toBe("2 2026-07-02T00:00:00Z"); + expect(passed?.status).not.toBe(base?.status); + expect(downstreamPassed?.status).not.toBe(passed?.status); + expect(jobFailed?.status).not.toBe(base?.status); + expect(passed?.remarks).toBe(base?.remarks); + expect(edited?.status).toBe(base?.status); + expect(edited?.remarks).not.toBe(base?.remarks); + expect(resolved?.remarks).toBe(base?.remarks); + expect(read({ userNotesCount: 3 })?.remarks).not.toBe(base?.remarks); + }); + + // Only the REST read asks GitLab to recheck mergeability, and only for viewers who can update. + it("covers the detail read once merge status has settled or no read could settle it", () => { + expect(read({})?.coversDetail).toBe(true); + // A capped job count or a second bridge page can hide a job settling. + expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 1001) })?.coversDetail).toBe(false); + expect(read({ headPipeline: pipeline("RUNNING", "RUNNING", 0, true) })?.coversDetail).toBe( + false, + ); + expect(read({ mergeStatusEnum: "UNCHECKED" })?.coversDetail).toBe(false); + expect(read({ mergeStatusEnum: "CHECKING", conflicts: true })?.coversDetail).toBe(true); + expect( + read({ mergeStatusEnum: "UNCHECKED", userPermissions: { updateMergeRequest: false } }) + ?.coversDetail, + ).toBe(true); + }); + + it("answers null when GitLab returned no merge request", () => { + expect( + expectSuccess( + decodeMergeRequestWatchFingerprintJson( + JSON.stringify({ data: { project: { mergeRequest: null } } }), + ), + ), + ).toBeNull(); + }); +}); diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 44b87436d63bd..685f920f07650 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -25,6 +25,7 @@ import type { import { TrimmedNonEmptyString } from "@t3tools/contracts"; import { quoteGitPatchPath } from "@t3tools/shared/gitPatchPath"; import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import type { ProviderChangeRequestWatchFingerprint } from "@t3tools/source-control-core/server/PullRequestProvider"; /** Unknown pipeline or merge status values must not fail the whole payload. */ const RawUserSchema = Schema.Struct({ @@ -1214,6 +1215,25 @@ function toReactions( ); } +/** + * Resolving a thread moves lastEditedAt on every note in it; only lastEditedBy marks a text + * edit, and a resolved note's stamp may be the resolve rather than that edit. + */ +function textEditedAt( + note: { + readonly lastEditedAt?: string | null | undefined; + readonly lastEditedBy?: { readonly username?: string | null | undefined } | null | undefined; + readonly resolved?: boolean | null | undefined; + } | null, +): string | null { + const editedAt = trimmed(note?.lastEditedAt); + return editedAt !== null && + trimmed(note?.lastEditedBy?.username) !== null && + note?.resolved !== true + ? editedAt + : null; +} + function noteIdOf(gid: string | null | undefined): string | null { const id = trimmed(gid)?.split("/").at(-1); return id !== undefined && /^\d+$/.test(id) ? id : null; @@ -1247,16 +1267,8 @@ export function decodeAwardEmojiJson( if (id === null) continue; const reactions = toReactions(node?.awardEmoji, viewer); if (reactions.length > 0) reactionsByNoteId.set(id, reactions); - // Resolving a thread moves lastEditedAt on every note in it; only lastEditedBy marks a - // text edit, and a resolved note's stamp may be the resolve rather than that edit. - const editedAt = trimmed(node?.lastEditedAt); - if ( - editedAt !== null && - trimmed(node?.lastEditedBy?.username) !== null && - node?.resolved !== true - ) { - editedAtByNoteId.set(id, editedAt); - } + const editedAt = textEditedAt(node); + if (editedAt !== null) editedAtByNoteId.set(id, editedAt); } const pageInfo = mergeRequest?.notes?.pageInfo; return Result.succeed({ @@ -2041,3 +2053,150 @@ export function decodeMergeRequestFileStatsJson(raw: string): Result.Result< const fileCount = mergeRequest?.diffStatsSummary?.fileCount; return Result.succeed({ files, truncated: fileCount === undefined || files.length < fileCount }); } + +/** + * One cheap read that tells a watch whether anything it reports on changed. Edits to comments + * older than the newest 100 are missed here and left to the watch's periodic full reread. + * Finished job counts move whenever one job settles while its pipeline still runs, and bridge + * jobs are read because their downstream pipelines are checks of their own. + */ +export const MERGE_REQUEST_WATCH_FINGERPRINT_GRAPHQL_QUERY = `query($fullPath: ID!, $iid: String!) { + project(fullPath: $fullPath) { + mergeRequest(iid: $iid) { + state mergeStatusEnum conflicts diffHeadSha + userPermissions { updateMergeRequest } + headPipeline { + id status + succeeded: jobs(retried: false, statuses: [SUCCESS]) { count } + failed: jobs(retried: false, statuses: [FAILED]) { count } + stopped: jobs(retried: false, statuses: [CANCELED, SKIPPED]) { count } + jobs(jobKind: BRIDGE, retried: false, first: 100) { + pageInfo { hasNextPage } + nodes { name status downstreamPipeline { id status } } + } + } + userNotesCount + notes(filter: ONLY_COMMENTS, last: 100) { + nodes { lastEditedAt lastEditedBy { username } resolved } + } + } + } +}`; + +const PipelineIdentitySchema = Schema.Struct({ id: Schema.String, status: Schema.String }); +const JobCountSchema = Schema.NullOr(Schema.Struct({ count: Schema.Int })); +// GitLab's connection `count` stops at its default limit and answers `limit + 1` above it. +const JOB_COUNT_LIMIT = 1000; + +const decodeMergeRequestWatchFingerprint = decodeJsonResult( + Schema.Struct({ + data: Schema.Struct({ + project: Schema.NullOr( + Schema.Struct({ + mergeRequest: Schema.NullOr( + Schema.Struct({ + state: Schema.String, + mergeStatusEnum: Schema.NullOr(Schema.String), + conflicts: Schema.Boolean, + diffHeadSha: Schema.NullOr(Schema.String), + userPermissions: Schema.Struct({ updateMergeRequest: Schema.Boolean }), + headPipeline: Schema.NullOr( + Schema.Struct({ + ...PipelineIdentitySchema.fields, + succeeded: JobCountSchema, + failed: JobCountSchema, + stopped: JobCountSchema, + jobs: Schema.NullOr( + Schema.Struct({ + pageInfo: Schema.Struct({ hasNextPage: Schema.Boolean }), + nodes: Schema.Array( + Schema.NullOr( + Schema.Struct({ + name: Schema.NullOr(Schema.String), + status: Schema.NullOr(Schema.String), + downstreamPipeline: Schema.NullOr(PipelineIdentitySchema), + }), + ), + ), + }), + ), + }), + ), + userNotesCount: Schema.NullOr(Schema.Int), + notes: Schema.Struct({ + nodes: Schema.Array( + Schema.NullOr( + Schema.Struct({ + lastEditedAt: Schema.NullOr(Schema.String), + lastEditedBy: Schema.NullOr( + Schema.Struct({ username: Schema.NullOr(Schema.String) }), + ), + resolved: Schema.NullOr(Schema.Boolean), + }), + ), + ), + }), + }), + ), + }), + ), + }), + }), +); + +/** Null when GitLab returned no merge request, so the watch falls back to full reads. */ +export function decodeMergeRequestWatchFingerprintJson( + raw: string, +): Result.Result { + const decoded = decodeMergeRequestWatchFingerprint(raw); + if (!Result.isSuccess(decoded)) { + return Result.fail(decoded.failure); + } + const mr = decoded.success.data.project?.mergeRequest; + if (mr == null) return Result.succeed(null); + const newestEdit = mr.notes.nodes.reduce((newest, note) => { + const editedAt = textEditedAt(note); + return editedAt !== null && editedAt > newest ? editedAt : newest; + }, ""); + const pipeline = mr.headPipeline; + const jobCounts = [pipeline?.succeeded, pipeline?.failed, pipeline?.stopped].map( + (jobs) => jobs?.count ?? null, + ); + // Past a capped count or the first bridge page, a job can settle without moving the status. + const seesEveryJob = + pipeline?.jobs?.pageInfo.hasNextPage !== true && + jobCounts.every((count) => count === null || count <= JOB_COUNT_LIMIT); + const bridges = (pipeline?.jobs?.nodes ?? []) + .flatMap((job) => + job === null + ? [] + : [ + [job.name, job.status, job.downstreamPipeline?.id, job.downstreamPipeline?.status] + .map((part) => part ?? "") + .join(":"), + ], + ) + .toSorted() + .join(","); + return Result.succeed({ + status: [ + mr.state, + mr.mergeStatusEnum ?? "", + mr.conflicts, + mr.diffHeadSha ?? "", + pipeline?.id ?? "", + pipeline?.status ?? "", + jobCounts.map((count) => count ?? "").join("/"), + bridges, + ].join(" "), + remarks: [mr.userNotesCount ?? "", newestEdit].join(" "), + // GraphQL never asks GitLab to recheck mergeability. The REST detail read does, but only for + // viewers who can update the merge request, so only they keep detail reads going until it settles. + coversDetail: + seesEveryJob && + (mr.conflicts || + !mr.userPermissions.updateMergeRequest || + mr.mergeStatusEnum === "CAN_BE_MERGED" || + mr.mergeStatusEnum === "CANNOT_BE_MERGED"), + }); +} From 20ee041354e0417e12914239964cca2833da824f Mon Sep 17 00:00:00 2001 From: Byntham <135178921+Byntham@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:51:32 -0800 Subject: [PATCH 006/140] fix(web): font picker scrolls to every font in short windows (#22795) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- apps/web/src/components/settings/FontFamilyPicker.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/settings/FontFamilyPicker.tsx b/apps/web/src/components/settings/FontFamilyPicker.tsx index 5958550ce9e0a..b9f0638c93d5d 100644 --- a/apps/web/src/components/settings/FontFamilyPicker.tsx +++ b/apps/web/src/components/settings/FontFamilyPicker.tsx @@ -199,8 +199,9 @@ export function FontFamilyPicker({ />
No fonts found. -
- + {/* Short windows cap the popup; every level down to the list must shrink or rows are clipped unreachably. */} +
+ ref={scrollRef} data={items} @@ -216,6 +217,7 @@ export function FontFamilyPicker({ onScroll={handleMetricsChange} onLayout={handleMetricsChange} onReady={handleMetricsChange} + className="min-h-0" style={{ height: listHeight }} /> From b9a68e0f57c05e9eca0d7573dfbbd08e1cd6af52 Mon Sep 17 00:00:00 2001 From: Pavel Kroupa <63880977+Tabonx@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:55:23 +0100 Subject: [PATCH 007/140] fix(source-control): repository paths match however their names are percent-encoded (#36929) Co-authored-by: Julius Marminge --- .../src/project/RepositoryIdentityResolver.ts | 7 ++-- packages/shared/src/git.test.ts | 3 ++ packages/shared/src/git.ts | 24 ++++++++++++-- .../src/shared/definition.test.ts | 33 +++++++++++++++++++ .../src/shared/definition.ts | 5 +-- .../src/shared/definition.ts | 24 ++++++++++---- .../src/shared/threadPullRequests.ts | 4 ++- .../src/shared/definition.ts | 4 ++- 8 files changed, 88 insertions(+), 16 deletions(-) diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 4bb4e024ae151..826529e704b23 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -1,7 +1,7 @@ import type { RepositoryIdentity, SourceControlProviderError } from "@t3tools/contracts"; import { parseGitRemoteHost } from "@t3tools/source-control-core/shared/definition"; import { repositoryPathFromRemoteUrl } from "@t3tools/source-control-core/server/SourceControlProvider"; -import { normalizeGitRemoteUrl } from "@t3tools/shared/git"; +import { canonicalRepositoryPath, normalizeGitRemoteUrl } from "@t3tools/shared/git"; import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; @@ -126,8 +126,9 @@ function repositoryPathOf(canonicalKey: string, remoteUrl: string): string { if (displayPath === null) return canonicalPath; // A host that names repositories literally keeps the `.git` the display path drops. return ( - [displayPath, `${displayPath}.git`].find((path) => path.toLowerCase() === canonicalPath) ?? - canonicalPath + [displayPath, `${displayPath}.git`].find( + (path) => canonicalRepositoryPath(path) === canonicalRepositoryPath(canonicalPath), + ) ?? canonicalPath ); } diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index 78f98cda1e726..e9502307ce43a 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -33,6 +33,9 @@ describe("normalizeGitRemoteUrl", () => { expect(normalizeGitRemoteUrl("https://github.com/T3Tools/T3Code.git#section")).toBe( "github.com/t3tools/t3code", ); + expect(normalizeGitRemoteUrl("https://code.example.test/team/%C3%84pp.git")).toBe( + normalizeGitRemoteUrl("git@code.example.test:team/Äpp.git"), + ); expect(normalizeGitRemoteUrl("ssh://git@code.example.test/owner/repo.git.git")).toBe( normalizeGitRemoteUrl("git@code.example.test:owner/repo.git.git"), ); diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 477130187037c..c304143ca26fa 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -124,6 +124,23 @@ export function isTemporaryWorktreeBranch(refName: string): boolean { const stripGitSuffix = (path: string) => path.replace(/\.git$/i, ""); +function canonicalPathSegment(segment: string): string { + try { + // Lowercase before encoding: lowercasing the escape `%C3%84` never reaches the `Ä` it names. + return encodeURIComponent(decodeURIComponent(segment).toLowerCase()).toLowerCase(); + } catch { + return segment.toLowerCase(); + } +} + +/** + * A repository path in one lower-case spelling. Remotes, browsers and agents escape a name + * differently (`a%20(b)`, `a%20%28b%29`, `a (b)`), and keys built from them are compared as text. + */ +export function canonicalRepositoryPath(path: string): string { + return path.split("/").map(canonicalPathSegment).join("/"); +} + function lowerCaseRemote(value: string, dropSuffix = stripGitSuffix): string { return dropSuffix(value.trim().replace(/\/+$/g, "")).toLowerCase(); } @@ -148,7 +165,7 @@ export function parseGitRemoteRepository( .split("/") .filter((segment) => segment.length > 0); if (url.hostname && repositorySegments.length > 1) { - return { host: url.hostname, path: repositorySegments.join("/") }; + return { host: url.hostname, path: canonicalRepositoryPath(repositorySegments.join("/")) }; } } catch { return null; @@ -164,10 +181,11 @@ export function parseGitRemoteRepository( const scpHost = scpStyleHostAndPath?.[1]; const scpPath = scpStyleHostAndPath?.[2]; if (!scpHost || !scpPath) return null; - if (!scpHost.startsWith("[")) return { host: scpHost, path: scpPath }; + const path = canonicalRepositoryPath(scpPath); + if (!scpHost.startsWith("[")) return { host: scpHost, path }; try { // Spell an IPv6 host as the URL branch does, so `[::1]:a/b` and `ssh://[::1]/a/b` share a key. - return { host: new URL(`ssh://${scpHost}`).hostname, path: scpPath }; + return { host: new URL(`ssh://${scpHost}`).hostname, path }; } catch { return null; } diff --git a/packages/source-control-azure-devops/src/shared/definition.test.ts b/packages/source-control-azure-devops/src/shared/definition.test.ts index c373d6cb30df7..ed7744f434ee0 100644 --- a/packages/source-control-azure-devops/src/shared/definition.test.ts +++ b/packages/source-control-azure-devops/src/shared/definition.test.ts @@ -157,6 +157,39 @@ describe("Azure DevOps repository keys", () => { ).toBe(false); }); + it("matches a repository however its name is percent-encoded", () => { + const remoteUrl = "https://example@dev.azure.com/example/Sample%20(Beta)/_git/Sample%20(Beta)"; + const canonicalKey = registry.repositoryKeyFromRemote(remoteUrl); + const identity: ChangeRequestProjectIdentity = { + canonicalKey, + locator: { source: "git-remote", remoteName: "origin", remoteUrl }, + }; + for (const url of [ + "https://dev.azure.com/example/Sample%20%28Beta%29/_git/Sample%20%28Beta%29/pullrequest/7", + "https://dev.azure.com/example/Sample (Beta)/_git/Sample (Beta)/pullrequest/7", + ]) { + const link = parse(url)!; + expect(link.repository, url).toBe("example/sample%20(beta)/_git/sample%20(beta)"); + expect(definition.isChangeRequestInRepository(identity, link), url).toBe(true); + expect( + definition.isChangeRequestInRepository( + { + ...identity, + canonicalKey: "dev.azure.com/example/sample%20%28beta%29/_git/sample%20%28beta%29", + }, + link, + ), + url, + ).toBe(true); + } + // Links stored before keys had one spelling still resolve to their project. + expect( + registry.canonicalRepositoryKey( + "dev.azure.com/example/sample%20%28beta%29/_git/sample%20%28beta%29", + ), + ).toBe(canonicalKey); + }); + it("still drops .git from other hosts' repository keys", () => { expect(registry.repositoryKeyFromRemote("git@github.com:acme/tool.git")).toBe( "github.com/acme/tool", diff --git a/packages/source-control-azure-devops/src/shared/definition.ts b/packages/source-control-azure-devops/src/shared/definition.ts index 83cd2d317da12..c894be875ca23 100644 --- a/packages/source-control-azure-devops/src/shared/definition.ts +++ b/packages/source-control-azure-devops/src/shared/definition.ts @@ -1,4 +1,5 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; +import { canonicalRepositoryPath } from "@t3tools/shared/git"; import { buildCommitUrl, changeRequestUrlBelow, @@ -156,8 +157,8 @@ export const definition = defineSourceControl({ canonicalRepositoryKey, isChangeRequestInRepository: (identity, link) => { if (!isChangeRequestAuthorityOfProject(identity, link)) return false; - const projectKey = identity.canonicalKey.toLowerCase(); - const linkKey = `${link.host}/${link.repository}`.toLowerCase(); + const projectKey = canonicalRepositoryPath(identity.canonicalKey); + const linkKey = canonicalRepositoryPath(`${link.host}/${link.repository}`); return ( (canonicalRepositoryKey(projectKey) ?? projectKey) === (canonicalRepositoryKey(linkKey) ?? linkKey) diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index 00e1e045f0b79..167d89a67f878 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -9,7 +9,11 @@ import { TrimmedNonEmptyString, TrimmedString, } from "@t3tools/contracts"; -import { normalizeGitRemoteUrl, parseGitRemoteRepository } from "@t3tools/shared/git"; +import { + canonicalRepositoryPath, + normalizeGitRemoteUrl, + parseGitRemoteRepository, +} from "@t3tools/shared/git"; import { userlessScpRemoteHost } from "@t3tools/shared/sourceControl"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -379,7 +383,7 @@ export function parseCommitPath(url: URL, route: RegExp): CommitLink | null { return repository && sha && FULL_COMMIT_SHA.test(sha) ? { host: url.hostname.toLowerCase(), - repository: repository.toLowerCase(), + repository: canonicalRepositoryPath(repository), sha: sha.toLowerCase(), ...(url.port ? { authority: url.host.toLowerCase() } : {}), } @@ -417,7 +421,7 @@ export function parseChangeRequestPath(url: URL, route: RegExp): ParsedChangeReq return repository && Number.isSafeInteger(number) && number > 0 ? { host: url.hostname.toLowerCase(), - repository: repository.toLowerCase(), + repository: canonicalRepositoryPath(repository), number, repositoryUrl: `${url.origin}/${repository}`, } @@ -513,7 +517,7 @@ export function isChangeRequestInProjectRepository( const repository = projectRepositoryPath(identity); return ( repository !== null && - repository.toLowerCase() === link.repository.toLowerCase() && + canonicalRepositoryPath(repository) === canonicalRepositoryPath(link.repository) && isChangeRequestOnProjectHost(projectHost, identity, link) ); } @@ -704,7 +708,15 @@ export function makeSourceControlDefinitionRegistry( } const claimOrder = inOrder(definitions, options?.claimChangeRequestUrlsFirst); const recognitionOrder = inOrder(definitions, options?.recognizeRemotesIn); - const repositoryKeyOwner = (key: string) => { + // Keys persisted before paths had one spelling still compare equal. + const canonicalKeyPath = (key: string) => { + const slash = key.indexOf("/"); + return slash < 0 + ? key + : `${key.slice(0, slash)}/${canonicalRepositoryPath(key.slice(slash + 1))}`; + }; + const repositoryKeyOwner = (written: string) => { + const key = canonicalKeyPath(written); for (const definition of definitions) { const canonical = definition.canonicalRepositoryKey?.(key); if (canonical != null) return { definition, canonical }; @@ -811,7 +823,7 @@ export function makeSourceControlDefinitionRegistry( } return key; }, - canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? key, + canonicalRepositoryKey: (key) => repositoryKeyOwner(key)?.canonical ?? canonicalKeyPath(key), findByRepositoryKey: (key) => repositoryKeyOwner(key)?.definition, repositorySelector: (identity) => identity?.provider === undefined diff --git a/packages/source-control-core/src/shared/threadPullRequests.ts b/packages/source-control-core/src/shared/threadPullRequests.ts index bed52f5ecb841..c485bf24d759d 100644 --- a/packages/source-control-core/src/shared/threadPullRequests.ts +++ b/packages/source-control-core/src/shared/threadPullRequests.ts @@ -4,6 +4,7 @@ import type { ThreadPullRequestKey, ThreadPullRequestLink, } from "@t3tools/contracts"; +import { canonicalRepositoryPath } from "@t3tools/shared/git"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { SourceControlDefinitionRegistry } from "./definition.ts"; @@ -73,7 +74,8 @@ export function makeThreadPullRequests( const parsed = key.url === undefined ? null : parse(key.url); const authority = key.authority ?? - (parsed?.repository === key.repository.trim().toLowerCase() && parsed.number === key.number + (parsed?.repository === canonicalRepositoryPath(key.repository.trim()) && + parsed.number === key.number ? parsed.authority : undefined); const canonical = registry.canonicalRepositoryKey( diff --git a/packages/source-control-forgejo/src/shared/definition.ts b/packages/source-control-forgejo/src/shared/definition.ts index 9946512233cec..0cee42cdf8132 100644 --- a/packages/source-control-forgejo/src/shared/definition.ts +++ b/packages/source-control-forgejo/src/shared/definition.ts @@ -1,4 +1,5 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; +import { canonicalRepositoryPath } from "@t3tools/shared/git"; import { buildCommitUrl, changeRequestUrlBelow, @@ -130,7 +131,8 @@ export const definition = defineSourceControl({ return isChangeRequestInProjectRepository(changeRequestHost(identity), identity, link); return ( web.host.toLowerCase() === (link.authority ?? link.host).toLowerCase() && - web.pathname.replace(/^\/+|\/+$/g, "").toLowerCase() === link.repository.toLowerCase() + canonicalRepositoryPath(web.pathname.replace(/^\/+|\/+$/g, "")) === + canonicalRepositoryPath(link.repository) ); }, // A server mounted below a path serves only repositories under that mount. From 5393882fb805a7331f48cebf6278d58975504551 Mon Sep 17 00:00:00 2001 From: maria Date: Sat, 14 Nov 2026 21:55:35 +0000 Subject: [PATCH 008/140] fix(mcp): return delegated task handles before client timeouts (#15622) Co-authored-by: Julius Marminge --- .../src/mcp/OrchestratorMcpService.test.ts | 145 ++++++++++++++++++ apps/server/src/mcp/OrchestratorMcpService.ts | 16 +- .../Adapters/ClaudeAdapterV2.ts | 2 +- .../Adapters/CodexAdapterV2.ts | 2 +- apps/server/src/peer/PeerForwarding.test.ts | 19 +-- apps/server/src/peer/PeerForwarding.ts | 57 +++---- .../src/provider/agentContextBudget.json | 2 +- packages/contracts/src/orchestratorMcp.ts | 2 +- 8 files changed, 181 insertions(+), 64 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index f6567dba53f2c..816a0dcb981d2 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -1636,6 +1636,151 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect.each([ + { name: "default", timeoutMs: undefined, budgetMs: 30_000 }, + { name: "capped", timeoutMs: 3_600_000, budgetMs: 45_000 }, + { name: "shorter requested", timeoutMs: 500, budgetMs: 500 }, + ])("returns task and thread handles at the $name wait budget", (scenario) => + Effect.gen(function* () { + const subscribed = yield* Deferred.make(); + const returned = yield* Deferred.make(); + const dispatched = yield* Ref.make>([]); + const threadWaitBudgets = yield* Ref.make>([]); + const task = { + id: taskId, + threadId: parentThreadId, + runId: parentRunId, + parentNodeId, + origin: "app_owned", + providerInstanceId: codexInstanceId, + driver: "codex", + childThreadId, + model: "gpt-5.4", + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + assertProviderInstanceEnabled: () => Effect.void, + isProviderInstanceEnabledForProject: () => Effect.succeed(true), + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId ? parentProjection([task]) : childProjection, + ), + getThreadEventSequence: () => Effect.succeed(0), + delegatedTaskResultPending: () => Effect.succeed(false), + streamStoredEventsFrom: () => + Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.never), + ), + waitForThread: (input) => + Ref.update(threadWaitBudgets, (budgets) => [...budgets, input.timeoutMs]).pipe( + Effect.as({ threadId: parentThreadId, run: null, timedOut: true }), + ), + dispatch: (command) => + Ref.update(dispatched, (commands) => [...commands, command]).pipe( + Effect.as({ + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task } }], + } as never), + ), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const budget = scenario.timeoutMs === undefined ? {} : { timeoutMs: scenario.timeoutMs }; + const waiting = yield* service + .delegateTask(scope, { task: "Review the change.", mode: "wait", ...budget }) + .pipe( + Effect.tap(() => Deferred.succeed(returned, undefined)), + Effect.forkChild, + ); + yield* Deferred.await(subscribed); + yield* TestClock.adjust(Duration.millis(scenario.budgetMs - 1)); + assert.isFalse(yield* Deferred.isDone(returned)); + yield* TestClock.adjust(Duration.millis(1)); + const result = yield* Fiber.join(waiting); + assert.include(result, { taskId, childThreadId, status: "running", waitTimedOut: true }); + assert.include((yield* Ref.get(dispatched)).at(-1), { + type: "delegated_task.wake-policy", + completionWake: "always", + }); + + yield* service.waitForThread(scope, { threadId: parentThreadId, ...budget }); + assert.deepEqual(yield* Ref.get(threadWaitBudgets), [scenario.budgetMs]); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + + it.effect.each([ + { name: "ten-minute default", timeoutMs: undefined, budgetMs: 600_000 }, + { name: "one-hour maximum", timeoutMs: 3_600_000, budgetMs: 3_600_000 }, + ])("keeps a secret request pending for its $name", (scenario) => + Effect.gen(function* () { + const pending = yield* Deferred.make(); + const returned = yield* Deferred.make(); + const statuses = yield* Ref.make>([]); + const dependencies = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.succeed({ ...parentProjection([]), turnItems: [] }), + dispatch: (command) => { + if (command.type !== "secret_request.record") return Effect.die("Unexpected command"); + return Ref.update(statuses, (values) => [...values, command.secretStatus]).pipe( + Effect.andThen(Deferred.succeed(pending, undefined)), + Effect.as({} as never), + ); + }, + }), + ServerSettings.layerTest(), + providerRegistryLayer([]), + adapterRegistryLayer([]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const waiting = yield* service + .requestSecret(scope, { + label: "Token", + reason: "Connect the account.", + ...(scenario.timeoutMs === undefined ? {} : { timeoutMs: scenario.timeoutMs }), + }) + .pipe( + Effect.tap(() => Deferred.succeed(returned, undefined)), + Effect.forkChild, + ); + yield* Deferred.await(pending); + yield* TestClock.adjust(Duration.millis(scenario.budgetMs - 1)); + assert.isFalse(yield* Deferred.isDone(returned)); + assert.deepEqual(yield* Ref.get(statuses), ["pending"]); + yield* TestClock.adjust(Duration.millis(1)); + assert.include(yield* Fiber.join(waiting), { status: "timed_out" }); + assert.deepEqual(yield* Ref.get(statuses), ["pending", "cancelled"]); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + it.effect( "advertises orchestration capability from registered adapters rather than a driver allowlist", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 406ac408cf1be..8ce090fff3394 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -137,10 +137,11 @@ import * as SecretRequests from "../secrets/SecretRequests.ts"; import * as PeerForwarding from "../peer/PeerForwarding.ts"; import * as RemoteDelegation from "../peer/RemoteDelegation.ts"; -const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000; -// Nothing is written while a task wait blocks, and Node fetch drops a silent call at 300 s. -const DEFAULT_TASK_WAIT_TIMEOUT_MS = 4 * 60 * 1_000; -const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000; +// Return recoverable handles before common MCP client timeouts expire. +const DEFAULT_WAIT_TIMEOUT_MS = 30_000; +const MAX_WAIT_TIMEOUT_MS = 45_000; +const DEFAULT_SECRET_REQUEST_TIMEOUT_MS = 10 * 60 * 1_000; +const MAX_SECRET_REQUEST_TIMEOUT_MS = 60 * 60 * 1_000; const TASK_WAKE_EVENTS = [ { thread: "parent", eventType: "subagent.updated" }, { thread: "child", eventType: "run.updated" }, @@ -1829,7 +1830,7 @@ const make = Effect.gen(function* () { ): Effect.fn.Return { const timeoutMs = Math.min( MAX_WAIT_TIMEOUT_MS, - Math.max(1, requestedTimeoutMs ?? DEFAULT_TASK_WAIT_TIMEOUT_MS), + Math.max(1, requestedTimeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), ); const upgradeWake = threadManagement .dispatch({ @@ -2428,7 +2429,10 @@ const make = Effect.gen(function* () { }).pipe( Effect.timeoutOption( Duration.millis( - Math.min(input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS, MAX_WAIT_TIMEOUT_MS), + Math.min( + input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS, + MAX_SECRET_REQUEST_TIMEOUT_MS, + ), ), ), Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index e0659b0167f57..7590a2c950bc7 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2402,7 +2402,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__send_to_user", ]; -// T3 waits can block for an hour; exceed Claude's default 60 s timeout. +// request_secret can wait an hour; exceed Claude's default 60 s timeout. export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000; // allowedTools pre-approves calls; tools controls availability. Pre-approve T3 tools for headless modes, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 8683c33f05a1f..c340645bb9f52 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1440,7 +1440,7 @@ export const CODEX_THREAD_CONFIG = { "features.concurrent_reasoning_summaries": true, } as const; -// T3 waits can block for an hour; keep Codex's MCP timeout above that. +// request_secret can wait an hour; keep Codex's MCP timeout above that. const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; // Holds T3 tools Codex must call directly, never from Code Mode. Calls arrive as // `t3-code-direct.`; t3McpToolPresentation.ts must keep resolving that form. diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 84fe35c6f21f8..baae43ed7f768 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -133,12 +133,8 @@ const boxThreads = (seen: Ref.Ref, linkSession: Ref.Ref) => { stops: [...current.stops, `delegated-tasks.stop ${input.threadId}`], })), waitForThread: (input) => - Ref.updateAndGet(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe( - Effect.map(({ waits }) => ({ - threadId: input.threadId, - run: run(waits.length < 3 ? "running" : "completed"), - timedOut: waits.length < 3, - })), + Ref.update(seen, (current) => ({ ...current, waits: [...current.waits, input] })).pipe( + Effect.as({ threadId: input.threadId, run: run("completed"), timedOut: false }), ), }); }; @@ -476,15 +472,8 @@ it.effect("keeps a forwarded wait short and its retries scoped to the caller", ( status: "completed", timedOut: false, }); - // Three pieces of at most 50 s each, the later ones pinned to the run - // the first one found. - expect( - (yield* Ref.get(seen)).waits.map(({ timeoutMs, runId }) => [timeoutMs, runId]), - ).toEqual([ - [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, undefined], - [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun], - [PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun], - ]); + // One capped piece, so the caller's MCP request returns before its client times out. + expect((yield* Ref.get(seen)).waits.map(({ timeoutMs }) => timeoutMs)).toEqual([45_000]); const send = (caller: string, clientRequestId: string) => a.call(caller, "t3_thread_send", { diff --git a/apps/server/src/peer/PeerForwarding.ts b/apps/server/src/peer/PeerForwarding.ts index e10d851f76913..f6fdb40beede0 100644 --- a/apps/server/src/peer/PeerForwarding.ts +++ b/apps/server/src/peer/PeerForwarding.ts @@ -25,14 +25,9 @@ import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.t import * as PeerLinks from "./PeerLinks.ts"; import * as PeerMcpClient from "./PeerMcpClient.ts"; -/** - * A peer's `/mcp` holds a wait open for its whole timeout without sending - * anything, and T3 Connect's edge drops a request idle for about 100 s, so a - * forwarded wait goes out in pieces no longer than this. - */ -export const FORWARDED_WAIT_CHUNK_MS = 50_000; -const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000; -const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000; +// Match local waits: return before MCP client timeouts and T3 Connect's ~100 s idle drop. +const DEFAULT_WAIT_TIMEOUT_MS = 30_000; +const MAX_WAIT_TIMEOUT_MS = 45_000; type Scope = McpInvocationContext.McpInvocationScope; @@ -67,7 +62,7 @@ export class PeerForwarding extends Context.Service< environmentId: EnvironmentId, input: OrchestratorMcpThreadInterruptInput, ) => Effect.Effect; - /** `t3_thread_wait` there, in pieces short enough to survive any route. */ + /** `t3_thread_wait` there, bounded like a local wait. */ readonly waitForThread: ( scope: Scope, environmentId: EnvironmentId, @@ -188,37 +183,21 @@ const make = Effect.gen(function* () { input, ); - const waitForThread: PeerForwarding["Service"]["waitForThread"] = Effect.fn( - "PeerForwarding.waitForThread", - )(function* (scope, environmentId, input) { - let remaining = Math.min( - MAX_WAIT_TIMEOUT_MS, - Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + const waitForThread: PeerForwarding["Service"]["waitForThread"] = (scope, environmentId, input) => + forward( + scope, + "t3_thread_wait", + OrchestratorMcpThreadWaitInput, + OrchestratorMcpThreadWaitResult, + environmentId, + { + ...input, + timeoutMs: Math.min( + MAX_WAIT_TIMEOUT_MS, + Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), + ), + }, ); - let runId = input.runId; - while (true) { - const chunk = Math.min(remaining, FORWARDED_WAIT_CHUNK_MS); - const result = yield* forward( - scope, - "t3_thread_wait", - OrchestratorMcpThreadWaitInput, - OrchestratorMcpThreadWaitResult, - environmentId, - { - threadId: input.threadId, - ...(runId === undefined ? {} : { runId }), - timeoutMs: chunk, - ...(input.untilDelegatedWorkSettled === undefined - ? {} - : { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }), - }, - ); - remaining -= chunk; - if (!result.timedOut || remaining <= 0) return result; - // Later pieces wait for the run the first one picked, not a newer one. - runId = result.runId ?? undefined; - } - }); // While the beta is off, agents start nothing over links. Tasks already running there keep // following through readThread, waitForThread and interruptThread, so they still finish. diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 7ceed7057c195..1d3d3a9179c0b 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5930, "codexAdditionalContextBytes": 7324, - "mcpToolListJsonBytes": 49791 + "mcpToolListJsonBytes": 49790 } diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 19163466972bb..02865671333eb 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -185,7 +185,7 @@ export const OrchestratorMcpDelegateTaskInput = Schema.Struct({ }), ), timeoutMs: Schema.optional(Schema.Finite).annotate({ - description: "Mode 'wait' only. Default 4 min. A timeout does not cancel the child.", + description: "Mode 'wait' only. At most 45 s. A timeout does not cancel the child.", }), clientRequestId: Schema.optional(OrchestratorMcpClientRequestId), runtimeMode: Schema.optional( From 7873016460071936fbf2b23d3896f4cfa756fa25 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sat, 14 Nov 2026 15:57:53 -0600 Subject: [PATCH 009/140] fix(web): allow tooltip text to wrap naturally (#36948) --- apps/web/src/components/ui/popover.tsx | 2 +- apps/web/src/components/ui/tooltip.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ui/popover.tsx b/apps/web/src/components/ui/popover.tsx index ecbf7a6667062..005654db7bdd7 100644 --- a/apps/web/src/components/ui/popover.tsx +++ b/apps/web/src/components/ui/popover.tsx @@ -97,7 +97,7 @@ function PopoverPopup({ // Electron drag hit-testing ignores z-index; popups over a drag region would swallow hover. "[-webkit-app-region:no-drag]", tooltipStyle && - "w-fit text-balance rounded-md text-xs shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]", + "w-fit rounded-md text-xs shadow-md/5 before:rounded-[calc(var(--radius-md)-1px)]", !tooltipStyle && variant !== "panel" && "shadow-[0_16px_40px_-18px_rgb(0_0_0/55%)] dark:shadow-[0_18px_44px_-18px_rgb(0_0_0/80%)]", diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 614943364b1e1..577aa48da87fa 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -140,7 +140,7 @@ function TooltipPopup({ Date: Sun, 15 Nov 2026 03:30:49 +0530 Subject: [PATCH 010/140] fix(preview): unload desktop pages before removing their tabs (#35135) Co-authored-by: Julius Marminge --- apps/server/src/preview/Manager.ts | 32 +++- apps/server/src/preview/ServerBrowser.test.ts | 169 +++++++++++++++--- apps/server/src/preview/ServerBrowser.ts | 73 ++++++-- .../preview/closePreviewSession.test.ts | 45 ++++- .../components/preview/closePreviewSession.ts | 17 +- ...useRightPanelSurfaceClose.browser.test.tsx | 5 + 6 files changed, 299 insertions(+), 42 deletions(-) diff --git a/apps/server/src/preview/Manager.ts b/apps/server/src/preview/Manager.ts index 0899866f80b64..e18e1686c0427 100644 --- a/apps/server/src/preview/Manager.ts +++ b/apps/server/src/preview/Manager.ts @@ -60,6 +60,10 @@ export class PreviewManager extends Context.Service< input: PreviewAdjustInput, ) => Effect.Effect; readonly close: (input: PreviewCloseInput) => Effect.Effect; + /** Runs before closed events publish, while clients still own their page surfaces. */ + readonly registerBeforeClose: ( + handler: (snapshots: ReadonlyArray) => Effect.Effect, + ) => Effect.Effect; readonly list: (input: PreviewListInput) => Effect.Effect; readonly events: Stream.Stream; readonly subscribeEvents: Effect.Effect, never, Scope.Scope>; @@ -128,6 +132,14 @@ export const make = Effect.gen(function* PreviewManagerMake() { const stateRef = yield* SynchronizedRef.make(initialState); const eventsPubSub = yield* PubSub.unbounded(); const events: Stream.Stream = Stream.fromPubSub(eventsPubSub); + const beforeClose = new Set< + (snapshots: ReadonlyArray) => Effect.Effect + >(); + const registerBeforeClose: PreviewManager["Service"]["registerBeforeClose"] = (handler) => + Effect.acquireRelease( + Effect.sync(() => beforeClose.add(handler)), + () => Effect.sync(() => beforeClose.delete(handler)), + ).pipe(Effect.asVoid); /** Publish inside the lock to preserve state-transition order. */ const mutateExistingSession = ( @@ -395,19 +407,26 @@ export const make = Effect.gen(function* PreviewManagerMake() { const close: PreviewManager["Service"]["close"] = Effect.fn("PreviewManager.close")( function* (input) { + // Unload runs outside the state lock; tabs opened meanwhile belong to a later close. + const current = yield* SynchronizedRef.get(stateRef); + const targets = input.tabId + ? [current.sessions.get(compositeKey(input.threadId, input.tabId))].filter( + (entry): entry is PreviewSessionState => entry !== undefined, + ) + : sessionsForThread(current, input.threadId); + yield* Effect.forEach( + [...beforeClose], + (handler) => handler(targets.map((target) => target.snapshot)), + { discard: true }, + ); const createdAt = yield* currentIsoTimestamp; yield* SynchronizedRef.modifyEffect(stateRef, (state) => { const eventsToEmit: PreviewEvent[] = []; const sessions = new Map(state.sessions); - const targets = input.tabId - ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter( - (entry): entry is PreviewSessionState => entry !== undefined, - ) - : sessionsForThread(state, input.threadId); let revision = state.revision; for (const target of targets) { + if (!sessions.delete(compositeKey(target.threadId, target.tabId))) continue; revision += 1; - sessions.delete(compositeKey(target.threadId, target.tabId)); eventsToEmit.push({ type: "closed", threadId: target.threadId, @@ -484,6 +503,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { resize, adjust, close, + registerBeforeClose, list, events, subscribeEvents: PubSub.subscribe(eventsPubSub), diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 27cc365ae6688..8087a25e6e559 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -74,6 +74,8 @@ vi.mock("./ServerBrowserContexts.ts", () => ({ context.page.viewportSize.mockReturnValue(null); const browser = { close: vi.fn(async () => {}) }; desktopConnections.push({ endpoint, context, browser }); + desktopConnectionStarted?.resolve(); + await desktopConnectionGate?.promise; return { browser, page: context.page as unknown as Page }; } async close() { @@ -401,6 +403,8 @@ let pageSetupFailure: Error | null = null; let initialNavigation: (() => Promise) | null = null; let desktopRendersNext = false; let desktopPageUrl = "about:blank"; +let desktopConnectionGate: PromiseWithResolvers | null = null; +let desktopConnectionStarted: PromiseWithResolvers | null = null; /** Replaces the answer to the desktop page's size reads. */ let desktopSizeAnswer: (() => Promise>) | null = null; const desktopDetaches = new NodeEvents.EventEmitter(); @@ -593,6 +597,8 @@ beforeEach(() => { desktopAttachesLate = false; desktopAttachWaiting = Promise.withResolvers(); desktopPageUrl = "about:blank"; + desktopConnectionGate = null; + desktopConnectionStarted = null; desktopSizeAnswer = null; desktopDetachReady = Promise.withResolvers(); desktopReleased = Promise.withResolvers(); @@ -1833,46 +1839,111 @@ it.effect("closing a tab force-closes a page that never finishes unloading", () ).pipe(Effect.provide(layer)), ); -it.effect("closing a desktop tab waits for its page to unload before the desktop removes it", () => +it.effect("closing a desktop tab during setup unloads its page before disconnecting", () => Effect.scoped( Effect.gen(function* () { const { broker } = yield* ready; const manager = yield* Manager.PreviewManager; desktopRendersNext = true; - const opened = yield* broker.invoke({ - scope, - operation: "open", - input: { reuseExistingTab: false, open: false }, - }); - const tabId = PreviewTabId.make(opened.tabId!); + const gate = (desktopConnectionGate = Promise.withResolvers()); + const started = (desktopConnectionStarted = Promise.withResolvers()); + yield* Effect.addFinalizer(() => Effect.sync(() => gate.resolve())); + const opening = yield* broker + .invoke({ + scope, + operation: "open", + input: { reuseExistingTab: false, open: false }, + }) + .pipe(Effect.result, Effect.forkScoped); + yield* Effect.promise(() => started.promise); const { context, browser } = desktopConnections[0]!; const page = context.page; - // The desktop removes the webview once the session closes, dropping an unload in progress. - const events = yield* manager.subscribeEvents; - const sessionClosed = Promise.withResolvers(); - yield* Effect.gen(function* () { - while ((yield* PubSub.take(events)).type !== "closed"); - page.removed = true; - sessionClosed.resolve(); - }).pipe(Effect.forkScoped); page.beforeUnload = "listen"; page.unloadGate = Promise.withResolvers(); - const closing = yield* broker - .invoke({ scope, tabId, operation: "close", input: {} }) - .pipe(Effect.forkScoped); - // The page finishes unloading once the server listens for it, or too late if it never does. + const { sessions } = yield* manager.list({ threadId: testThread.threadId }); + const session = sessions.find((candidate) => !candidate.headless)!; + const closing = yield* manager + .close({ threadId: testThread.threadId, tabId: session.tabId }) + .pipe(Effect.forkScoped({ startImmediately: true })); + expect(page.isClosed()).toBe(false); + gate.resolve(); yield* Effect.promise(() => - Promise.race([page.pagehideWatched.promise, sessionClosed.promise]), + Promise.race([page.pagehideWatched.promise, desktopReleased.promise]), + ); + expect((yield* manager.list({ threadId: testThread.threadId })).sessions).toEqual( + expect.arrayContaining([expect.objectContaining({ tabId: session.tabId })]), ); - expect(browser.close).not.toHaveBeenCalled(); page.unloadGate.resolve(); yield* Fiber.join(closing); + expect(yield* Fiber.join(opening)).toMatchObject({ _tag: "Failure" }); + yield* Effect.promise(() => desktopReleased.promise); expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]); - expect(browser.close).toHaveBeenCalledTimes(1); + expect(page.isClosed()).toBe(true); + expect(browser.close).toHaveBeenCalled(); }), ).pipe(Effect.provide(layer)), ); +it.effect.each(["agent", "client", "all", "concurrent"] as const)( + "closing a desktop tab waits for unload before removal (%s)", + (source) => + Effect.scoped( + Effect.gen(function* () { + const { broker } = yield* ready; + const manager = yield* Manager.PreviewManager; + desktopRendersNext = true; + const opened = yield* broker.invoke({ + scope, + operation: "open", + input: { reuseExistingTab: false, open: false }, + }); + const tabId = PreviewTabId.make(opened.tabId!); + const { context, browser } = desktopConnections[0]!; + const page = context.page; + // The desktop removes the webview once the session closes, dropping an unload in progress. + const events = yield* manager.subscribeEvents; + const sessionClosed = Promise.withResolvers(); + yield* Effect.gen(function* () { + while ((yield* PubSub.take(events)).type !== "closed"); + page.removed = true; + sessionClosed.resolve(); + }).pipe(Effect.forkScoped); + page.beforeUnload = "listen"; + page.unloadGate = Promise.withResolvers(); + const close = () => manager.close({ threadId: testThread.threadId, tabId }); + const closing = yield* ( + source === "agent" + ? broker.invoke({ scope, tabId, operation: "close", input: {} }) + : source === "all" + ? manager.close({ threadId: testThread.threadId }) + : source === "concurrent" + ? Effect.all([close(), close()], { concurrency: "unbounded", discard: true }) + : close() + ).pipe(Effect.forkScoped); + // The page finishes unloading once the server listens for it, or too late if it never does. + yield* Effect.promise(() => + Promise.race([page.pagehideWatched.promise, sessionClosed.promise]), + ); + expect(browser.close).not.toHaveBeenCalled(); + const openedDuringClose = + source === "all" + ? yield* manager.open({ threadId: testThread.threadId, runtime: "server" }) + : undefined; + page.unloadGate.resolve(); + yield* Fiber.join(closing); + yield* Effect.promise(() => desktopReleased.promise); + expect(page.unloadEvents).toEqual(["beforeunload", "pagehide", "visibilitychange"]); + expect(browser.close).toHaveBeenCalledTimes(1); + if (openedDuringClose) { + const remaining = yield* manager.list({ threadId: testThread.threadId }); + expect(remaining.sessions.map((session) => session.tabId)).toContain( + openedDuringClose.tabId, + ); + } + }), + ).pipe(Effect.provide(layer)), +); + it.effect("closing a tab with an unsaved-changes guard still closes it", () => Effect.scoped( Effect.gen(function* () { @@ -3768,6 +3839,7 @@ it.effect("a full server takes back the slot of the longest idle agent tab nobod expect(releasedDesktopTabs).toEqual([]); shownDesktopTabs.clear(); shownDesktopTabs.add(opened[1]!); + desktopConnections[2]!.context.page.beforeUnload = "listen"; const events = yield* manager.subscribeEvents; const releases = yield* Queue.unbounded(); const recordRelease = (tabId: string) => Queue.offerUnsafe(releases, tabId); @@ -3778,6 +3850,11 @@ it.effect("a full server takes back the slot of the longest idle agent tab nobod const fresh = yield* open("agent-new"); expect(fresh.tabId).toBeDefined(); expect(yield* Queue.take(releases)).toBe(opened[2]); + expect(desktopConnections[2]!.context.page.unloadEvents).toEqual([ + "beforeunload", + "pagehide", + "visibilitychange", + ]); yield* Stream.fromSubscription(events).pipe( Stream.filter((event) => event.type === "closed" && event.tabId === opened[2]), Stream.runHead, @@ -3787,6 +3864,54 @@ it.effect("a full server takes back the slot of the longest idle agent tab nobod expect(sessions.map((session) => session.tabId).toSorted()).toEqual( [...opened.filter((tabId) => tabId !== opened[2]), fresh.tabId!].toSorted(), ); + + // A second open must reclaim a different tab while the first page is unloading. + const closingPage = desktopConnections[3]!.context.page; + closingPage.beforeUnload = "listen"; + closingPage.unloadGate = Promise.withResolvers(); + const closeRequests = yield* Queue.unbounded(); + const close = manager.close; + const closeSpy = vi + .spyOn(manager, "close") + .mockImplementation((input) => + Queue.offer(closeRequests, undefined).pipe(Effect.andThen(close(input))), + ); + yield* Effect.addFinalizer(() => Effect.sync(() => closeSpy.mockRestore())); + const firstOpen = yield* open("agent-concurrent").pipe(Effect.forkScoped); + yield* Queue.take(closeRequests); + yield* Effect.promise(() => closingPage.pagehideWatched.promise); + const secondOpen = yield* open("agent-concurrent").pipe(Effect.forkScoped); + yield* Queue.take(closeRequests); + closingPage.unloadGate.resolve(); + const concurrent = yield* Effect.all([Fiber.join(firstOpen), Fiber.join(secondOpen)]); + expect(concurrent.every((status) => status.available)).toBe(true); + const remaining = (yield* manager.list({ threadId: scope.thread.threadId })).sessions; + expect(remaining).toHaveLength(32); + const closedBeforeReturn = yield* Deferred.make(); + const finishClose = yield* Deferred.make(); + let heldClose = false; + closeSpy.mockImplementation((input) => { + const hold = !heldClose; + heldClose = true; + return close(input).pipe( + Effect.andThen( + hold + ? Deferred.succeed(closedBeforeReturn, undefined).pipe( + Effect.andThen(Deferred.await(finishClose)), + ) + : Effect.void, + ), + ); + }); + const reclaimingOpen = yield* open("agent-reclaiming").pipe(Effect.forkScoped); + yield* Deferred.await(closedBeforeReturn); + const takingFreedSlot = yield* open("agent-taking-free-slot"); + expect(takingFreedSlot.available).toBe(true); + yield* Deferred.succeed(finishClose, undefined); + expect((yield* Fiber.join(reclaimingOpen)).available).toBe(true); + expect((yield* manager.list({ threadId: scope.thread.threadId })).sessions).toHaveLength(32); + expect(remaining.some((session) => session.tabId === opened[3])).toBe(false); + expect(remaining.some((session) => session.tabId === opened[4])).toBe(false); }), ).pipe(Effect.provide(layer)), ); diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 7aa74a9d172b7..dce77ed2c3a4b 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -969,6 +969,36 @@ const make = Effect.gen(function* () { clearTimeout(timeout); }; + const unloadingTabs = new WeakMap>(); + yield* manager.registerBeforeClose((snapshots) => + Effect.promise(async () => { + await Promise.all( + snapshots.map((snapshot) => { + const key = tabKey(snapshot.threadId, snapshot.tabId); + const tab = tabs.get(key); + if (!tab) { + const opening = pendingTabs.get(key); + if (!opening) return; + closedPendingTabs.add(key); + if (!opening.promise) return; + const settled = Promise.withResolvers(); + const timeout = setTimeout(settled.resolve, PAGE_CLOSE_GRACE_MS); + void opening.promise.finally(settled.resolve).catch(constVoid); + return settled.promise.finally(() => clearTimeout(timeout)); + } + void tab.control.close().catch(constVoid); + if (!tab.desktop || tab.dialog !== null) return; + const pending = unloadingTabs.get(tab); + if (pending) return pending; + tab.closing = true; + const unloading = unloadDesktopPage(tab.page); + unloadingTabs.set(tab, unloading); + return unloading; + }), + ); + }), + ); + const dropTab = (tab: ServerTab, closeSession: boolean, reopening = false) => { const key = tabKey(tab.threadId, tab.tabId); if (tabs.get(key) !== tab) return; @@ -1317,6 +1347,10 @@ const make = Effect.gen(function* () { page.on("popup", (popup) => void adoptPopup(tab, popup)); const key = tabKey(tab.threadId, tab.tabId); if (closedPendingTabs.delete(key)) { + if (desktop) { + tab.closing = true; + await unloadDesktopPage(page).catch(constVoid); + } await control.close().catch(constVoid); throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId }); } @@ -1747,20 +1781,35 @@ const make = Effect.gen(function* () { const isVisible = (tab: ServerTab) => tab.viewers.size > 0 || (tab.desktop !== null && desktopChannel.isShown(tab)); + const reclaimingTabs = new Set(); const idleAgentTabs = () => { const cutoff = Date.now() - AGENT_TAB_IDLE_MS; return [...tabs.values()].filter( - (tab) => tab.control.agentId !== null && !isVisible(tab) && tab.usedAt < cutoff, + (tab) => + tab.control.agentId !== null && + !reclaimingTabs.has(tab) && + !isVisible(tab) && + tab.usedAt < cutoff, ); }; // The desktop app renders every server tab, so idle desktop agent tabs would otherwise // hold the server's budget forever. Hidden ones give up their slots, longest idle first, // only when an agent needs one and has room for it. - const freeIdleAgentSlot = (agentSessionId: string) => { + const freeIdleAgentSlot = async (agentSessionId: string) => { if (!serverAtTabLimit() || agentAtTabLimit(agentSessionId)) return; const longestIdle = idleAgentTabs().sort((left, right) => left.usedAt - right.usedAt)[0]; - if (longestIdle) dropTab(longestIdle, true); + if (longestIdle) { + reclaimingTabs.add(longestIdle); + try { + await runPromise( + manager.close({ threadId: longestIdle.threadId, tabId: longestIdle.tabId }), + ); + dropTab(longestIdle, false); + } finally { + reclaimingTabs.delete(longestIdle); + } + } }; // A Playwright launch must settle before its capacity can be released. @@ -1771,10 +1820,17 @@ const make = Effect.gen(function* () { let key: string = NodeCrypto.randomUUID(); const reservation = { agentId: input.automationOwner ?? null }; return yield* Effect.acquireUseRelease( - Effect.try({ - try: () => { + Effect.tryPromise({ + try: async () => { if (input.automationOwner !== undefined) { - if (options.reclaimIdleSlot) freeIdleAgentSlot(input.automationOwner); + while ( + options.reclaimIdleSlot && + serverAtTabLimit() && + !agentAtTabLimit(input.automationOwner) && + idleAgentTabs().length > 0 + ) { + await freeIdleAgentSlot(input.automationOwner); + } assertTabCapacity(input.automationOwner); } pendingTabs.set(key, reservation); @@ -2654,11 +2710,6 @@ const make = Effect.gen(function* () { message: "A human controls this tab.", reason: "humanControl", }); - void tab.control.close().catch(constVoid); - if (tab.desktop && tab.dialog === null) { - tab.closing = true; - await unloadDesktopPage(tab.page); - } await runPromise(manager.close({ threadId: tab.threadId, tabId: tab.tabId })); dropTab(tab, false); return {}; diff --git a/apps/web/src/components/preview/closePreviewSession.test.ts b/apps/web/src/components/preview/closePreviewSession.test.ts index c763c1949460f..508cc69066149 100644 --- a/apps/web/src/components/preview/closePreviewSession.test.ts +++ b/apps/web/src/components/preview/closePreviewSession.test.ts @@ -1,9 +1,10 @@ import type { + EnvironmentId, PreviewCloseInput, PreviewSessionSnapshot, ScopedThreadRef, } from "@t3tools/contracts"; -import { AsyncResult } from "effect/reactivity"; +import { Atom, AsyncResult } from "effect/reactivity"; import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { @@ -13,9 +14,20 @@ import { } from "~/previewStateStore"; import { useClosedViewStore } from "~/closedViewStore"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment"; import { closePreviewSession } from "./closePreviewSession"; +vi.mock("~/env", async (importOriginal) => ({ + ...(await importOriginal()), + isElectron: true, +})); +vi.mock("~/state/primaryEnvironment", async (importOriginal) => ({ + ...(await importOriginal()), + primaryEnvironmentIdAtom: Atom.make(null), +})); + const threadRef = { environmentId: "local" as ScopedThreadRef["environmentId"], threadId: "thread-1" as ScopedThreadRef["threadId"], @@ -34,8 +46,16 @@ const snapshot: PreviewSessionSnapshot = { updatedAt: "2026-06-18T19:00:00.000Z", }; +const setPrimaryEnvironment = (environmentId: EnvironmentId | null) => { + if (!Atom.isWritable(primaryEnvironmentIdAtom)) { + throw new Error("primaryEnvironmentIdAtom is not writable"); + } + appAtomRegistry.set(primaryEnvironmentIdAtom, environmentId); +}; + beforeEach(() => { resetPreviewStateForTests(); + setPrimaryEnvironment(null); useClosedViewStore.setState({ entries: [] }); }); @@ -69,4 +89,27 @@ describe("closePreviewSession", () => { ]); expect(closePreview).toHaveBeenCalledWith({ threadId: "thread-1", tabId: "tab-1" }); }); + + it("keeps a tab this desktop renders mounted until the server has closed it", async () => { + setPrimaryEnvironment(threadRef.environmentId); + const desktopSnapshot = { ...snapshot, runtime: "server" as const }; + applyPreviewServerSnapshot(threadRef, desktopSnapshot); + let finishClose: (() => void) | undefined; + const closing = closePreviewSession({ + closePreview: () => + new Promise>>((resolve) => { + finishClose = () => resolve(AsyncResult.success(undefined)); + }), + snapshot: desktopSnapshot, + tabId: desktopSnapshot.tabId, + threadRef, + }); + + expect(readThreadPreviewState(threadRef).sessions).toEqual({ "tab-1": desktopSnapshot }); + finishClose?.(); + await closing; + expect(readThreadPreviewState(threadRef).sessions).toEqual({}); + applyPreviewServerSnapshot(threadRef, desktopSnapshot); + expect(readThreadPreviewState(threadRef).sessions).toEqual({}); + }); }); diff --git a/apps/web/src/components/preview/closePreviewSession.ts b/apps/web/src/components/preview/closePreviewSession.ts index 0e23a5449e1f4..b7c8e3f77a1d9 100644 --- a/apps/web/src/components/preview/closePreviewSession.ts +++ b/apps/web/src/components/preview/closePreviewSession.ts @@ -6,8 +6,11 @@ import type { ScopedThreadRef, } from "@t3tools/contracts"; +import { rendersServerTabNatively } from "~/browser/previewRuntime"; import { useClosedViewStore } from "~/closedViewStore"; import { beginPreviewSessionClose, cancelPreviewSessionClose } from "~/previewStateStore"; +import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment"; interface ClosePreviewSessionInput { readonly closePreview: (input: { @@ -22,14 +25,24 @@ interface ClosePreviewSessionInput { export async function closePreviewSession( input: ClosePreviewSessionInput, ): Promise> { - beginPreviewSessionClose(input.threadRef, input.tabId); + // Unmounting a webview destroys its page, so a tab this window renders stays mounted until the + // server has unloaded it. + const keepMounted = rendersServerTabNatively( + input.threadRef.environmentId, + appAtomRegistry.get(primaryEnvironmentIdAtom), + input.snapshot, + ); + if (!keepMounted) beginPreviewSessionClose(input.threadRef, input.tabId); const result = await input.closePreview({ environmentId: input.threadRef.environmentId, input: { threadId: input.threadRef.threadId, tabId: input.tabId }, }); if (result._tag === "Failure") { cancelPreviewSessionClose(input.threadRef, input.snapshot, input.tabId); - } else if (input.snapshot) { + return result; + } + if (keepMounted) beginPreviewSessionClose(input.threadRef, input.tabId); + if (input.snapshot) { useClosedViewStore.getState().remember({ kind: "browser", threadRef: input.threadRef, diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx index 9b1299aee1dea..8513f18f35ac2 100644 --- a/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx +++ b/apps/web/src/hooks/useRightPanelSurfaceClose.browser.test.tsx @@ -24,6 +24,11 @@ vi.mock("../previewStateStore", () => ({ beginPreviewSessionClose: () => {}, cancelPreviewSessionClose: () => {}, })); +vi.mock("../browser/previewRuntime", () => ({ rendersServerTabNatively: () => false })); +vi.mock("../state/primaryEnvironment", async () => { + const { Atom } = await import("effect/reactivity"); + return { primaryEnvironmentIdAtom: Atom.make(null) }; +}); vi.mock("../state/session", () => ({ useEnvironmentScope: (id: string) => fixture.allowed.has(id), readEnvironmentScope: (id: string) => fixture.allowed.has(id), From 0f79b4027a472b96fa9e72b5ee149567c992e177 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sat, 14 Nov 2026 16:03:56 -0600 Subject: [PATCH 011/140] fix(web): remove redundant status info icon (#36947) --- .../components/chat/ThreadActivityBanners.tsx | 16 ++++++++++++---- apps/web/src/components/chat/ThreadNow.tsx | 14 ++------------ 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index 5e3444f7a13aa..ff4ee1ef7078e 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -30,6 +30,7 @@ import { tickTextContent } from "~/lib/tickTextContent"; import { BackgroundWorkDetails } from "./BackgroundWorkDetails"; import { Button, InlineButton } from "../ui/button"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import type { ComposerBannerStackItem } from "./ComposerBannerStack"; import type { ThreadNowItem } from "./ThreadNow"; @@ -98,10 +99,17 @@ export function goalNowItem(input: { return { id: `goal:${input.threadId}`, icon: , - title: - presentation.usage === null - ? presentation.title - : `${presentation.title} · ${presentation.usage}`, + title: ( + + }> + {presentation.title} + {presentation.usage === null ? null : ` · ${presentation.usage}`} + + +

{presentation.objective}

+
+
+ ), description: presentation.objective, // Clear stops goal work; Resume would stop unrelated work, so it waits. actions: ( diff --git a/apps/web/src/components/chat/ThreadNow.tsx b/apps/web/src/components/chat/ThreadNow.tsx index 3e6374ec8c94f..960eb819c478b 100644 --- a/apps/web/src/components/chat/ThreadNow.tsx +++ b/apps/web/src/components/chat/ThreadNow.tsx @@ -3,7 +3,6 @@ import type { ReactNode } from "react"; import { threadSyncLabel, type ThreadSyncPhase } from "../../threadSync"; import { cn } from "~/lib/utils"; -import { NoticeText } from "./ComposerBannerStack"; /** A line of thread state for the end of the timeline. */ export interface ThreadNowItem { @@ -17,8 +16,6 @@ export interface ThreadNowItem { /** Matches ThreadStatusLine, so every line at the end of the timeline reads as one family. */ const lineClassName = cn( "mx-auto flex w-full min-w-0 max-w-(--chat-content-max-width) items-center gap-1.5 px-1 pb-2 text-xs text-muted-foreground [&_svg]:size-3.5 [&_svg]:shrink-0", - // A details button must not make its line taller than the others. - "[&_[data-slot=popover-trigger]]:-my-1.5", // Inline actions keep their text size but get a finger-sized hit area on touch. "pointer-coarse:[&_[data-slot=inline-button]]:relative pointer-coarse:[&_[data-slot=inline-button]]:after:absolute pointer-coarse:[&_[data-slot=inline-button]]:after:-inset-x-1.5 pointer-coarse:[&_[data-slot=inline-button]]:after:-inset-y-3.5", "transition-opacity duration-150 ease-out starting:opacity-0 motion-reduce:transition-none", @@ -42,14 +39,7 @@ function ThreadNowLine({ {item.icon} - {/* Title and detail read as one line that gives way before the actions, so Stop stays - reachable; when it is cut, its details button shows all of it. */} - + {item.title} {item.description ? ( <> @@ -59,7 +49,7 @@ function ThreadNowLine({ ) : null} - + {item.actions ? ( {item.actions} ) : null} From ff17cd307fca939329e5f2e35eb8b0f250ac644c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 14:06:41 -0800 Subject: [PATCH 012/140] fix(desktop): agent snapshots keep full detail in narrow and mini previews (#36944) --- apps/desktop/src/ipc/channels.ts | 1 + apps/desktop/src/ipc/methods/preview.ts | 11 ++ apps/desktop/src/preload.ts | 2 + .../src/preview/DesktopBrowserHost.test.ts | 110 ++++++++++++------ .../desktop/src/preview/DesktopBrowserHost.ts | 53 ++++++++- apps/desktop/src/preview/Manager.test.ts | 2 + apps/desktop/src/preview/Manager.ts | 17 ++- apps/web/src/browser/HostedBrowserWebview.tsx | 102 ++++++++++------ .../src/browser/browserViewportLayout.test.ts | 17 +++ apps/web/src/browser/browserViewportLayout.ts | 16 +++ packages/contracts/src/ipc.ts | 7 ++ 11 files changed, 256 insertions(+), 82 deletions(-) diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index b7bb5e579572f..4de0a23af35b3 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -101,6 +101,7 @@ export const PREVIEW_SET_AUDIO_MUTED_CHANNEL = "desktop:preview-set-audio-muted" export const PREVIEW_FIND_IN_PAGE_CHANNEL = "desktop:preview-find-in-page"; export const PREVIEW_STOP_FIND_IN_PAGE_CHANNEL = "desktop:preview-stop-find-in-page"; export const PREVIEW_SET_SHOWN_CHANNEL = "desktop:preview-set-shown"; +export const PREVIEW_SET_CAPTURE_DRAWN_CHANNEL = "desktop:preview-set-capture-drawn"; export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools"; export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies"; export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index cc810fee072ad..757e1e463f538 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -13,6 +13,7 @@ import { DesktopPreviewScreenshotArtifactSchema, DesktopPreviewSetAudioMutedInputSchema, DesktopPreviewSetShownInputSchema, + DesktopPreviewSetCaptureDrawnInputSchema, DesktopPreviewSetColorSchemeInputSchema, DesktopPreviewSetZoomFactorInputSchema, BrowserImportResult, @@ -234,6 +235,15 @@ const setShown = DesktopIpc.makeIpcMethod({ yield* manager.setShown(tabId, shown); }), }); +const setCaptureDrawn = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, + payload: DesktopPreviewSetCaptureDrawnInputSchema, + result: Schema.Void, + handler: Effect.fn("desktop.ipc.preview.setCaptureDrawn")(function* ({ tabId, drawn }) { + const manager = yield* PreviewManager.PreviewManager; + yield* manager.setCaptureDrawn(tabId, drawn); + }), +}); const openDevTools = tabMethod( IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, "desktop.ipc.preview.openDevTools", @@ -488,6 +498,7 @@ export const methods = [ setZoomFactor, setAudioMuted, setShown, + setCaptureDrawn, openDevTools, clearCookies, clearCache, diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index e0ac5f2161051..f0f9648173dc8 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -414,6 +414,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_FIND_IN_PAGE_CHANNEL, { tabId }), setShown: (tabId, shown) => ipcRenderer.invoke(IpcChannels.PREVIEW_SET_SHOWN_CHANNEL, { tabId, shown }), + setCaptureDrawn: (tabId, drawn) => + ipcRenderer.invoke(IpcChannels.PREVIEW_SET_CAPTURE_DRAWN_CHANNEL, { tabId, drawn }), openDevTools: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }), listBrowserImportSources: () => ipcRenderer.invoke(IpcChannels.PREVIEW_IMPORT_SOURCES_CHANNEL), diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index cf6c7736f81d3..8e96129293fc8 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -26,6 +26,11 @@ const decodeCdpMessage = Schema.decodeUnknownSync( ), ); const key = { threadId: "thread-1", tabId: "tab-1" }; + +/** A host whose client already draws `key` at full detail, so its screenshots go out at once. */ +const makeDrawnHost = Effect.tap(DesktopBrowserHost.make, (host) => + Effect.sync(() => host.setCaptureDrawn(key, true)), +); /** Sends a page command whose id the fake debugger records as it receives it. */ const command = ( host: DesktopBrowserHost.DesktopBrowserHost["Service"], @@ -172,7 +177,7 @@ const watchPainting = (host: DesktopBrowserHost.DesktopBrowserHost["Service"]) = describe("DesktopBrowserHost", () => { it.effect("announces tabs already attached to a backend that starts later", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; host.attach(key, makeDebuggee().tab); expect(yield* takeEvents(host, 1)).toEqual([{ type: "attached", ...key }]); @@ -182,7 +187,7 @@ describe("DesktopBrowserHost", () => { it.effect("announces a guest still loading its first page only once that page is up", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const loading = makeDebuggee({ loading: true }); const other = { ...key, tabId: "tab-2" }; const reader = yield* takeEvents(host, 3).pipe(Effect.forkScoped); @@ -205,7 +210,7 @@ describe("DesktopBrowserHost", () => { "keeps a loading guest unannounced across a replaced navigation and a new backend", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const loading = makeDebuggee({ loading: true }); const other = { ...key, tabId: "tab-2" }; host.attach(key, loading.tab); @@ -227,7 +232,7 @@ describe("DesktopBrowserHost", () => { "announces a first page that never comes up, but never a tab closed or destroyed first", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const closed = { ...key, tabId: "tab-2" }; const destroyed = { ...key, tabId: "tab-3" }; const destroyedGuest = makeDebuggee({ loading: true }); @@ -247,7 +252,7 @@ describe("DesktopBrowserHost", () => { it.effect("re-sends shown to a backend that starts later and when a tab attaches again", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; host.attach(key, makeDebuggee().tab); host.setShown(key, true); const reader = yield* takeEvents(host, 5).pipe(Effect.forkScoped); @@ -268,7 +273,7 @@ describe("DesktopBrowserHost", () => { it.effect("replays an explicit hidden report before announcing another tab", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const other = { ...key, tabId: "tab-2" }; host.setShown(key, false); host.attach(key, makeDebuggee().tab); @@ -285,7 +290,7 @@ describe("DesktopBrowserHost", () => { it.effect("drops replies from a relay the server released", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const reader = yield* takeEvents(host, 2).pipe(Effect.forkScoped); @@ -313,7 +318,7 @@ describe("DesktopBrowserHost", () => { it.effect("sends a page one screenshot at a time", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -330,9 +335,38 @@ describe("DesktopBrowserHost", () => { }), ); + it.effect( + "sends a screenshot once the client draws the guest at full detail, or soon after", + () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + + yield* command(host, 1, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([]); + host.setCaptureDrawn(key, true); + yield* settle; + expect(debuggee.sent).toEqual([1]); + debuggee.releaseFirst(); + expect(yield* Queue.take(replies)).toBe(1); + + // A client that never draws, such as a hidden window, only delays the capture. + host.setCaptureDrawn(key, false); + yield* command(host, 2, "Page.captureScreenshot"); + yield* settle; + expect(debuggee.sent).toEqual([1]); + yield* TestClock.adjust("1 second"); + yield* settle; + expect(debuggee.sent).toEqual([1, 2]); + }).pipe(Effect.scoped), + ); + it.effect("stops waiting on a screenshot the page navigated away from", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -357,7 +391,7 @@ describe("DesktopBrowserHost", () => { it.effect("drops screenshots a released relay left waiting", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -377,7 +411,7 @@ describe("DesktopBrowserHost", () => { it.effect("emulates focus while the server drives a guest, then lets a hidden one throttle", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -408,7 +442,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused while a command it is running is still pending", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -429,7 +463,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle once Chromium can no longer answer its pending command", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -451,7 +485,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused for the screenshot a navigation lets start", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -467,7 +501,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot a navigation superseded while focus was changing", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ deferFocus: true }); host.attach(key, debuggee.tab); @@ -484,7 +518,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused when its turn starts after the agent's first command", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const turn = (active: boolean) => @@ -506,7 +540,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle through a turn that only sent it housekeeping", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); yield* host.handleCommandLine( @@ -535,7 +569,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest the agent used focused through its turn's pauses", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const turn = (active: boolean) => @@ -563,7 +597,7 @@ describe("DesktopBrowserHost", () => { "ends a command's hold with the turn that sent it, even if Chromium never answers", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); yield* host.handleCommandLine( @@ -584,7 +618,7 @@ describe("DesktopBrowserHost", () => { it.effect("ends the agent's own session's holds with its turn, but not a viewer's stream", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -617,7 +651,7 @@ describe("DesktopBrowserHost", () => { it.effect("paints for a screenshot queued behind one its viewer abandoned mid-capture", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -655,7 +689,7 @@ describe("DesktopBrowserHost", () => { it.effect("stops painting for a queued screenshot once its session detaches", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -694,7 +728,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot whose session detached while focus was changing", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ deferFocus: true }); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -718,7 +752,7 @@ describe("DesktopBrowserHost", () => { it.effect("holds no focus for a screenshot still queued when the agent's turn ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -748,7 +782,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle when Chromium refuses a viewer's screencast", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ refuse: (method) => method === "Page.startScreencast" }); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -769,7 +803,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle after a person's input through a viewer that then closed", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -798,7 +832,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a page's screencast when a child session's screencast is refused", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee({ refuse: (method, sessionId) => method === "Page.startScreencast" && sessionId !== undefined, }); @@ -820,7 +854,7 @@ describe("DesktopBrowserHost", () => { it.effect("ignores a screencast that arrives on a session after it detached", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -846,7 +880,7 @@ describe("DesktopBrowserHost", () => { it.effect("lets a guest throttle once the session waiting on its command detaches", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -873,7 +907,7 @@ describe("DesktopBrowserHost", () => { it.effect("never sends a screenshot queued by a session that has since detached", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -904,7 +938,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a streamed guest focused until its screencast ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -933,7 +967,7 @@ describe("DesktopBrowserHost", () => { it.effect("keeps a guest focused while any of its screencasts runs", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -965,7 +999,7 @@ describe("DesktopBrowserHost", () => { it.effect("paints a hidden guest only while the screenshot it is taking is pending", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -991,7 +1025,7 @@ describe("DesktopBrowserHost", () => { it.effect("stops painting for a screenshot Chromium never answers once its document goes", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const painting = yield* watchPainting(host); @@ -1036,7 +1070,7 @@ describe("DesktopBrowserHost", () => { it.effect("paints a streamed guest until its last screencast ends", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -1243,7 +1277,7 @@ describe("DesktopBrowserHost", () => { it.effect("saves a server tab's download under its CDP guid where the server asked", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); const replies = yield* watchReplies(host); @@ -1278,7 +1312,7 @@ describe("DesktopBrowserHost", () => { it.effect("tells a download the person clicked from one the agent's input started", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const debuggee = makeDebuggee(); host.attach(key, debuggee.tab); @@ -1342,7 +1376,7 @@ describe("DesktopBrowserHost", () => { it.effect("detaches only the tab whose CDP event is too large to relay", () => Effect.gen(function* () { - const host = yield* DesktopBrowserHost.make; + const host = yield* makeDrawnHost; const tabs = [makeDebuggee({ deferFocus: true }), makeDebuggee()]; const send = vi.spyOn(tabs[0]!.tab.debugger, "sendCommand"); const keys = [key, { threadId: "thread-2", tabId: "tab-2" }]; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index e0326b7b76ec1..ce5d7074a786c 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -30,6 +30,8 @@ const AGENT_INPUT_WINDOW_MS = 5_000; /** A viewer's pointer travelling over the stream activates nothing on the page. */ const POINTER_TRAVEL = new Set(["mouseMoved", "mouseWheel"]); const FOCUS_IDLE = "5 seconds"; +/** How long a screenshot waits for the client to draw its guest at full detail. */ +const CAPTURE_DRAW_WAIT = "1 second"; /** Well inside the server's 10 s DESKTOP_ATTACH_TIMEOUT, for a first page that never reports it is up. */ const FIRST_PAGE_TIMEOUT = "5 seconds"; const ERR_ABORTED = -3; @@ -101,6 +103,8 @@ export class DesktopBrowserHost extends Context.Service< readonly detach: (key: DesktopBrowserTabKey) => void; readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void; readonly setShown: (key: DesktopBrowserTabKey, shown: boolean | undefined) => void; + /** Whether the client draws the guest at full detail while it is captured. */ + readonly setCaptureDrawn: (key: DesktopBrowserTabKey, drawn: boolean | undefined) => void; readonly humanStartedDownload: (source: Electron.WebContents) => boolean; /** Whether what the page does now follows the agent's input, not a viewer's. */ readonly agentLedPage: (source: Electron.WebContents) => boolean; @@ -138,6 +142,8 @@ export const make = Effect.gen(function* () { // Kept apart from attachment: the renderer can show a webview before its debugger attaches, // and the server forgets `shown` on detach, for example while DevTools holds the debugger. const shownTabs = new Map(); + const drawnTabs = new Set(); + const drawWaiters = new Map void>>(); const emit = (event: DesktopBrowserEventType) => runFork(PubSub.publish(outbox, event)); const nextScreenshot = (tab: AttachedTab) => { @@ -266,12 +272,32 @@ export const make = Effect.gen(function* () { }); }; + /** + * A scaled guest rasters at its on-screen size until the client draws it at full detail, + * and a screenshot taken before that copies the blurred frame. A client that cannot draw + * (a hidden window, say) only delays the capture. + */ + const whenDrawn = (tab: AttachedTab) => + new Promise((resolve) => { + const id = keyOf(tab.key); + const waiters = drawWaiters.get(id) ?? new Set(); + drawWaiters.set(id, waiters); + const done = () => { + waiters.delete(done); + if (waiters.size === 0 && drawWaiters.get(id) === waiters) drawWaiters.delete(id); + resolve(); + }; + waiters.add(done); + runFork(Effect.sleep(CAPTURE_DRAW_WAIT).pipe(Effect.andThen(Effect.sync(done)))); + }); + /** Chromium answers a capture, and frees its wake lock, only once the guest paints a frame. */ const paintUntilAnswered =
(tab: AttachedTab, send: () => Promise) => { const sent = {}; tab.capturing.add(sent); syncPainting(tab); - return send().finally(() => { + // Sent at once when already drawn, so it keeps its place among the commands after it. + return (drawnTabs.has(keyOf(tab.key)) ? send() : whenDrawn(tab).then(send)).finally(() => { tab.capturing.delete(sent); syncPainting(tab); }); @@ -368,12 +394,15 @@ export const make = Effect.gen(function* () { // Waits for focus emulation; insertText and other non-CDP input would not queue behind it. const forward = (current?: () => boolean) => { const change = tab.focusChange; - const run = () => - tab.relay !== relay || (current !== undefined && !current()) + const stale = () => tab.relay !== relay || (current !== undefined && !current()); + const sendUnlessStale = () => + stale() ? Promise.reject(new Error("The page this screenshot was for has moved on.")) - : current === undefined - ? send(method, params, sessionId) - : paintUntilAnswered(tab, () => send(method, params, sessionId)); + : send(method, params, sessionId); + const run = () => + current === undefined || stale() + ? sendUnlessStale() + : paintUntilAnswered(tab, sendUnlessStale); return change === null ? run() : change.then(run); }; return method === "Page.captureScreenshot" @@ -587,6 +616,17 @@ export const make = Effect.gen(function* () { if (tabs.get(id)?.stopWaiting === null) emit({ type: "shown", ...key, shown }); }; + const setCaptureDrawn = (key: DesktopBrowserTabKey, drawn: boolean | undefined) => { + const id = keyOf(key); + if (!drawn) { + drawnTabs.delete(id); + return; + } + drawnTabs.add(id); + for (const done of drawWaiters.get(id) ?? []) done(); + drawWaiters.delete(id); + }; + const loadFailed: DesktopBrowserHost["Service"]["loadFailed"] = (key, failure) => { if (tabs.has(keyOf(key))) emit({ type: "loadFailed", ...key, ...failure }); }; @@ -663,6 +703,7 @@ export const make = Effect.gen(function* () { detach, loadFailed, setShown, + setCaptureDrawn, placeDownload, humanStartedDownload, agentLedPage, diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 1fdb7b286ba1a..2091ff3c7f8f2 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -684,6 +684,7 @@ describe("PreviewManager", () => { attach: () => {}, detach: () => {}, setShown: () => {}, + setCaptureDrawn: () => {}, loadFailed: () => {}, humanStartedDownload: () => true, agentLedPage: () => false, @@ -2462,6 +2463,7 @@ describe("PreviewManager", () => { }), ); expect(yield* Queue.take(capturing)).toBe(true); + yield* manager.setCaptureDrawn("tab_1", true); screenshot.resolve({ data: "" }); expect(yield* Queue.take(capturing)).toBe(false); }).pipe(Effect.provide(managerLayer())), diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 8fe4cf1c992af..32ac876996c81 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -1827,7 +1827,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); if (Option.isNone(tab)) return; const closedTab = tab.value; - if (closedTab.serverTab) browserHost.setShown(closedTab.serverTab, undefined); + if (closedTab.serverTab) { + browserHost.setShown(closedTab.serverTab, undefined); + browserHost.setCaptureDrawn(closedTab.serverTab, undefined); + } if (closedTab.webContentsId != null) { yield* Effect.all( [ @@ -2635,12 +2638,21 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (serverTab) browserHost.setShown(serverTab, shown); }); + const setCaptureDrawn = Effect.fn("PreviewManager.setCaptureDrawn")(function* ( + tabId: string, + drawn: boolean, + ) { + const serverTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId)?.serverTab; + if (serverTab) browserHost.setCaptureDrawn(serverTab, drawn); + }); + // A window reload or guest crash destroys the guest without the renderer reporting it hidden. // The renderer reports again once a new guest registers. const hideDestroyedGuest = Effect.fnUntraced(function* (webContentsId: number) { for (const tab of (yield* SynchronizedRef.get(tabsRef)).values()) { if (tab.webContentsId === webContentsId && tab.serverTab) { browserHost.setShown(tab.serverTab, false); + browserHost.setCaptureDrawn(tab.serverTab, false); } } }); @@ -3716,6 +3728,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function setAnnotationSendEnabled, setAudioMuted, setShown, + setCaptureDrawn, setColorScheme, setMainWindow, setForwardedShortcuts: (shortcuts: ReadonlyArray) => @@ -3932,6 +3945,7 @@ export class PreviewManager extends Context.Service< audioMuted: boolean, ) => Effect.Effect; readonly setShown: (tabId: string, shown: boolean) => Effect.Effect; + readonly setCaptureDrawn: (tabId: string, drawn: boolean) => Effect.Effect; readonly openDevTools: (tabId: string) => Effect.Effect; readonly clearCookies: ( partitions?: ReadonlyArray, @@ -4094,6 +4108,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { setZoomFactor: operations.setZoomFactor, setAudioMuted: operations.setAudioMuted, setShown: operations.setShown, + setCaptureDrawn: operations.setCaptureDrawn, openDevTools: operations.openDevTools, clearCookies: Effect.fn("PreviewManager.clearCookies")(function* (partitions) { yield* browserSession diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index 28edc42d406a8..023fb03c3aa17 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -20,6 +20,7 @@ import { useActiveBrowserRecordingTabIds } from "./browserRecording"; import { browserViewportSettingKey, resolveBrowserViewportLayout, + resolveBrowserViewportTransform, resolveFittedBrowserViewport, } from "./browserViewportLayout"; import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar"; @@ -313,6 +314,23 @@ export function HostedBrowserWebview(props: { return () => withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, false)); }, [clientSettingsHydrated, runtimeTabId, serverDriven, shown]); + // Captures copy the guest's raster, which a scaled guest only keeps at full detail on request. + const fullDetail = backgroundActivity || pictureInPicture || recordingActive; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the desktop host once the guest is drawn at full detail, so its screenshot waits for that frame + useEffect(() => { + const bridge = window.desktopBridge?.preview; + if (!clientSettingsHydrated || !bridge || !serverDriven || !fullDetail) return; + let frame = requestAnimationFrame(() => { + frame = requestAnimationFrame(() => + withDesktopTab(runtimeTabId, () => bridge.setCaptureDrawn(runtimeTabId, true)), + ); + }); + return () => { + cancelAnimationFrame(frame); + withDesktopTab(runtimeTabId, () => bridge.setCaptureDrawn(runtimeTabId, false)); + }; + }, [clientSettingsHydrated, fullDetail, runtimeTabId, serverDriven]); + if (!clientSettingsHydrated || !config) return null; // This fixed wrapper sits outside the right panel shell, so it takes thumb presses itself. @@ -322,6 +340,7 @@ export function HostedBrowserWebview(props: { }; const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive; + const viewportTransform = resolveBrowserViewportTransform(layout.viewportScale, fullDetail); const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({ active, renderingActive, @@ -354,47 +373,56 @@ export function HostedBrowserWebview(props: { onChange={commitViewportChange} /> ) : null} - + > + +
{active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? ( <> { ).toEqual({ width: 460, height: 409 }); }); }); + +describe("resolveBrowserViewportTransform", () => { + it("keeps a full-detail guest at raster scale 1 while it draws at the fitted scale", () => { + expect(resolveBrowserViewportTransform(1, true)).toBeUndefined(); + expect(resolveBrowserViewportTransform(0.6, false)).toBe("scale(0.6)"); + const values = resolveBrowserViewportTransform(0.6, true) + ?.match(/^matrix3d\((.*)\)$/)?.[1] + ?.split(",") + .map(Number); + // Column-major: the x and y columns keep their 0.6 screen terms and reach length 1 through z. + expect(values?.slice(0, 2)).toEqual([0.6, 0]); + expect(values?.slice(4, 6)).toEqual([0, 0.6]); + expect(Math.hypot(...(values?.slice(0, 3) ?? []))).toBeCloseTo(1); + expect(Math.hypot(...(values?.slice(4, 7) ?? []))).toBeCloseTo(1); + }); +}); diff --git a/apps/web/src/browser/browserViewportLayout.ts b/apps/web/src/browser/browserViewportLayout.ts index 2fe4e035100ab..7fe6b170c671d 100644 --- a/apps/web/src/browser/browserViewportLayout.ts +++ b/apps/web/src/browser/browserViewportLayout.ts @@ -125,6 +125,22 @@ export function resolveBrowserViewportLayout( }; } +/** + * Chromium rasters a CSS-scaled guest at its on-screen scale, so captures of it lose detail. + * Its raster scale also counts x/y-to-z terms, which a `preserve-3d` parent keeps and the + * screen drops, so `fullDetail` draws like `scale()` but keeps full-resolution frames. + */ +export function resolveBrowserViewportTransform( + scale: number, + fullDetail: boolean, +): string | undefined { + if (scale >= 1) return undefined; + if (!fullDetail) return `scale(${scale})`; + // Positive depth keeps the guest in front of its parent for hit testing. + const depth = Math.sqrt(1 - scale * scale); + return `matrix3d(${scale}, 0, ${depth}, 0, 0, ${scale}, ${depth}, 0, 0, 0, 1, 0, 0, 0, 0, 1)`; +} + export function resolveBrowserDeviceViewportLayout( container: { readonly width: number; readonly height: number }, setting: Exclude, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 8f5258596c5f5..3aa3d7d21fcef 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1021,6 +1021,11 @@ export const DesktopPreviewSetShownInputSchema = Schema.Struct({ shown: Schema.Boolean, }); +export const DesktopPreviewSetCaptureDrawnInputSchema = Schema.Struct({ + tabId: DesktopPreviewTabIdSchema, + drawn: Schema.Boolean, +}); + export const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({ theme: DesktopPreviewAnnotationThemeSchema, }); @@ -1287,6 +1292,8 @@ export interface DesktopPreviewBridge { stopFindInPage: (tabId: string) => Promise; /** Tells the tab's server whether its webview is on screen. */ setShown: (tabId: string, shown: boolean) => Promise; + /** Tells the tab's server whether its webview is drawn at full detail for a capture. */ + setCaptureDrawn: (tabId: string, drawn: boolean) => Promise; openDevTools: (tabId: string) => Promise; clearCookies: (environmentId: EnvironmentId, profileId?: string) => Promise; clearCache: (environmentId: EnvironmentId, profileId?: string) => Promise; From 7f81aa8386737ecb244e3fd21c95afdb0649aeb7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 14:07:43 -0800 Subject: [PATCH 013/140] test(web): pin the minute clock in the sidebar jump-hint render test (#36954) --- apps/web/src/components/Sidebar.browser.test.tsx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index f152cabf01851..be674b66520d2 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -18,6 +18,7 @@ import { act, fakeTimers, render } from "../../test/render"; import { openCommandPalette } from "../commandPaletteBus"; import { makeThreadFixture } from "../test-fixtures"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; +import { useNowMinute } from "../hooks/useNowMinute"; import { __setClientSettingsForTests, getClientSettings } from "../hooks/useSettings"; import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget"; import { useProjects, useServerConfigs, useQuietThreadShells } from "../state/entities"; @@ -36,6 +37,7 @@ vi.mock(import("../state/olderSettledShelf"), async (original) => { }); vi.mock("../state/entities", { spy: true }); vi.mock("../hooks/useHandleNewThread", { spy: true }); +vi.mock("../hooks/useNowMinute", { spy: true }); vi.mock("../hooks/useThreadRouteTarget", { spy: true }); vi.mock("./sidebar/SidebarThreadRow", { spy: true }); vi.mock("../state/session", { spy: true }); @@ -144,6 +146,8 @@ describe("sidebar render isolation", () => { threadId: threads[0]!.id, }; threads.unshift(threadShell(activeProject.id, 100)); + // A real wall-clock minute tick mid-test re-renders every row and reads as a leak. + vi.mocked(useNowMinute).mockReturnValue("2026-01-01T00:00"); vi.mocked(useProjects).mockReturnValue([activeProject]); vi.mocked(useQuietThreadShells).mockReturnValue(threads); vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef }); From 632802cd3243b204e6b17c47b3d7946beb312f21 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 14:19:58 -0800 Subject: [PATCH 014/140] fix(acp-registry): models show the reasoning levels the agent advertises for them (#36950) Co-authored-by: 0xpolarzero <0xpolarzero@gmail.com> --- packages/contracts/src/acpRegistry.ts | 2 + .../src/server/driver.test.ts | 38 +++++++++++++++++ .../src/server/driver.ts | 16 +++++-- .../provider-acp-registry/src/server/probe.ts | 42 ++++++++++++++++++- 4 files changed, 93 insertions(+), 5 deletions(-) diff --git a/packages/contracts/src/acpRegistry.ts b/packages/contracts/src/acpRegistry.ts index a1d03ef7bd000..c6ecb8862bc4a 100644 --- a/packages/contracts/src/acpRegistry.ts +++ b/packages/contracts/src/acpRegistry.ts @@ -268,6 +268,8 @@ export const AcpRegistryProbeModel = Schema.Struct({ id: AcpRegistryProbeText, name: AcpRegistryProbeText, description: AcpRegistryProbeDescription, + // The reasoning control the agent advertises for this model; null when it has none. + reasoningEffort: Schema.optionalKey(Schema.NullOr(ProviderOptionDescriptor)), }); export type AcpRegistryProbeModel = typeof AcpRegistryProbeModel.Type; diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 1495cb0bb64dd..ee88901d16905 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -271,6 +271,44 @@ describe("acpRegistrySnapshotReadiness", () => { expect(afterOpus.find((model) => model.slug === "opus")).toMatchObject({ capabilities: { optionDescriptors: [{ id: "thinking" }, { id: "mode" }] }, }); + + // Other models take the levels they advertise in `_meta`. + const effort = { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select" as const, + currentValue: "high", + options: [{ value: "high", name: "High" }], + }; + const advertised = applyAcpRegistryLiveConfiguration( + provider, + normalizeAcpRegistryLiveConfiguration([effort], undefined, { + currentModelId: "opus", + availableModels: [ + { modelId: "opus", name: "Opus" }, + { + modelId: "haiku", + name: "Haiku", + _meta: { reasoningEfforts: [{ value: "low", label: "Low" }], reasoningEffort: "low" }, + }, + { modelId: "glm", name: "GLM", _meta: { supportsReasoningEffort: false } }, + ], + }), + [], + ).models.map((model) => model.capabilities?.optionDescriptors ?? []); + expect(advertised).toEqual([ + [{ ...liveOptions[0]!, role: "reasoning" }], + [ + { + ...liveOptions[0]!, + role: "reasoning", + options: [{ id: "low", label: "Low" }], + currentValue: "low", + }, + ], + [], + ]); }); it("projects discovery without claiming authentication when no login methods are advertised", () => { diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 2db192b9c7f96..726d95a145e91 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -4,6 +4,7 @@ import { resolveOfficialAcpRegistryIconUrl, TextGenerationError, type AcpRegistryOperationError, + type AcpRegistryProbeModel, type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; @@ -111,12 +112,19 @@ function modelsFromDiscovery( (descriptor) => !modelOptionIds.has(descriptor.id), ); const sharedIds = new Set(shared.map((descriptor) => descriptor.id)); - const capabilitiesFor = (slug: string) => { + const capabilitiesFor = ({ id: slug, reasoningEffort }: AcpRegistryProbeModel) => { if (slug === discovery?.currentModelId) return capabilities; + // The levels a model advertises replace the ones an earlier session reported. const own = ( previousModels.find((model) => model.slug === slug)?.capabilities?.optionDescriptors ?? [] - ).filter((descriptor) => !sharedIds.has(descriptor.id)); - const optionDescriptors = [...shared, ...own]; + ).filter( + (descriptor) => + !sharedIds.has(descriptor.id) && + (reasoningEffort === undefined || + descriptor.type !== "select" || + descriptor.role !== "reasoning"), + ); + const optionDescriptors = [...shared, ...own, ...(reasoningEffort ? [reasoningEffort] : [])]; return optionDescriptors.length === 0 ? EMPTY_CAPABILITIES : createModelCapabilities({ optionDescriptors }); @@ -137,7 +145,7 @@ function modelsFromDiscovery( name: model.name, isCustom: false, ...(model.id === discovery?.currentModelId ? { isDefault: true } : {}), - capabilities: capabilitiesFor(model.id), + capabilities: capabilitiesFor(model), })); return providerModelsFromSettings(builtInModels, customModels, capabilities); } diff --git a/packages/provider-acp-registry/src/server/probe.ts b/packages/provider-acp-registry/src/server/probe.ts index 2fcf80cbce4d9..662f28783ca45 100644 --- a/packages/provider-acp-registry/src/server/probe.ts +++ b/packages/provider-acp-registry/src/server/probe.ts @@ -53,6 +53,39 @@ const boundedText = (value: string, maximumLength: number): string => const boundedOpaqueValue = (value: string, maximumLength: number): string | undefined => value.length > 0 && value === value.trim() && value.length <= maximumLength ? value : undefined; +/** + * The session's reasoning option with the levels a model advertises in `_meta`, in the + * shape Grok uses. Null when the model has none, undefined when it says nothing. + */ +function advertisedReasoningEffort( + option: EffectAcpSchema.SessionConfigOption | undefined, + meta: Readonly> | null | undefined, +): AcpRegistryProbeModel["reasoningEffort"] { + if (option?.type !== "select" || meta == null) return undefined; + if (meta.supportsReasoningEffort === false) return null; + if (!Array.isArray(meta.reasoningEfforts)) return undefined; + const options = meta.reasoningEfforts.flatMap((level: unknown) => + typeof level === "object" && + level !== null && + "value" in level && + typeof level.value === "string" + ? [ + { + value: level.value, + name: "label" in level && typeof level.label === "string" ? level.label : level.value, + }, + ] + : [], + ); + const currentValue = typeof meta.reasoningEffort === "string" ? meta.reasoningEffort : ""; + return ( + acpProviderOptionDescriptors({ + configOptions: [{ ...option, options, currentValue }], + modeState: undefined, + })[0] ?? null + ); +} + export function normalizeAcpRegistryWebUrl(value: string): string | undefined { if (value.length > 2_048 || !URL.canParse(value)) return undefined; const url = new URL(value); @@ -195,7 +228,14 @@ export function normalizeAcpRegistryLiveConfiguration( currentModelId === undefined ? null : (boundedOpaqueValue(currentModelId, MAX_ID_LENGTH) ?? null); - const models = normalizeModels(candidates, boundedCurrentModelId); + const effortOption = configOptions.find((option) => option.category === "thought_level"); + const models = normalizeModels(candidates, boundedCurrentModelId).map((model) => { + const reasoningEffort = advertisedReasoningEffort( + effortOption, + modelState?.availableModels.find((info) => info.modelId === model.id)?._meta, + ); + return reasoningEffort === undefined ? model : { ...model, reasoningEffort }; + }); const descriptors = acpProviderOptionDescriptors({ configOptions, modeState }); const modelOptionIds = new Set( configOptions From cbdf35f2f0bcee887abc7736236293a67658a45e Mon Sep 17 00:00:00 2001 From: Victor Date: Sat, 14 Nov 2026 16:29:15 -0600 Subject: [PATCH 015/140] fix(web): enable Send when the composer holds only a thread context (#23166) Co-authored-by: Julius Marminge --- apps/web/src/components/chat/ChatComposer.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index e25ccc6dd25e8..978bab1d1e1ca 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1102,7 +1102,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) imageCount: composerImages.length + composerFiles.length, existingAttachmentCount: editingQueuedAttachments?.length ?? 0, terminalContexts: composerTerminalContexts, - elementContextCount: composerPreviewAnnotations.length + composerReviewComments.length, + elementContextCount: + composerPreviewAnnotations.length + + composerReviewComments.length + + composerThreadContexts.length + + composerEnvironmentContexts.length, }); const composerTriggerKind = composerTrigger?.kind ?? null; const compactSlashCommandAvailable = From d080e4eb587898c5057d03b3c7148d113ddeccc3 Mon Sep 17 00:00:00 2001 From: Andrei <108398860+Yuruzuu@users.noreply.github.com> Date: Sun, 15 Nov 2026 06:30:30 +0800 Subject: [PATCH 016/140] fix(web): thread details card no longer jumps mid panel animation (#22614) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- apps/web/src/components/chat/ChatCanvas.tsx | 71 ++++++++++++++++++- .../src/components/chat/canvasStore.test.ts | 8 ++- apps/web/src/components/chat/canvasStore.ts | 4 ++ .../components/chat/chatCanvasLayout.test.ts | 14 ++++ .../chat/threadDetailsCardLayout.ts | 9 ++- 5 files changed, 101 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ChatCanvas.tsx b/apps/web/src/components/chat/ChatCanvas.tsx index e05d3befcc138..7848009308750 100644 --- a/apps/web/src/components/chat/ChatCanvas.tsx +++ b/apps/web/src/components/chat/ChatCanvas.tsx @@ -7,6 +7,41 @@ import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore import { observeResize } from "../../lib/observeResize"; import type { ScopedThreadRef } from "@t3tools/contracts"; +function panelWidthTransitions(element: HTMLElement) { + const panels = element + .closest("[data-panel-animations]") + ?.querySelectorAll('[data-slot="sidebar-gap"], [data-preview-panel-mode="inline"]'); + return Array.from(panels ?? []).flatMap((panel) => + panel + .getAnimations() + .filter( + (animation): animation is CSSTransition => + animation instanceof CSSTransition && + animation.transitionProperty === "width" && + animation.playState === "running", + ), + ); +} + +// Sample only the layout panels; seeking unrelated transitions can change their lifecycle. +function measureTransitionWidths(element: HTMLElement, transitions: CSSTransition[]) { + if (transitions.length === 0) return null; + const times = transitions.map((animation) => animation.currentTime); + // Opposite panel transitions can reach their widest points at different times. + for (const animation of transitions) { + const end = Number(animation.effect?.getComputedTiming().endTime ?? 0); + animation.currentTime = 0; + const startWidth = element.clientWidth; + animation.currentTime = end; + if (startWidth < element.clientWidth) animation.currentTime = 0; + } + const narrowestWidth = element.clientWidth; + transitions.forEach((animation, index) => { + animation.currentTime = times[index] ?? null; + }); + return { transitions, narrowestWidth }; +} + export function ChatCanvas({ store, threadRef, @@ -36,7 +71,34 @@ export function ChatCanvas({ if (!element || !probe) return; const findBar = detailsCardTopInset > 0 ? element.querySelector("[data-thread-find-bar]") : null; + let disposed = false; + // Seeking forces layout, so it runs once when a transition starts, not every frame. + let transitionWidths: ReturnType = null; const measure = () => { + const width = element.clientWidth; + const transitions = panelWidthTransitions(element); + if ( + transitions.length !== (transitionWidths?.transitions.length ?? 0) || + transitions.some((animation, index) => animation !== transitionWidths?.transitions[index]) + ) { + const settling = measureTransitionWidths(element, transitions); + if (settling && transitionWidths) { + settling.narrowestWidth = Math.min( + settling.narrowestWidth, + transitionWidths.narrowestWidth, + ); + } + transitionWidths = settling; + // The last resize can arrive while the transitions still count as running. + if (settling) { + void Promise.allSettled(settling.transitions.map((animation) => animation.finished)).then( + () => { + if (disposed || transitionWidths !== settling) return; + measure(); + }, + ); + } + } const canvasBounds = element.getBoundingClientRect(); const findBarBounds = findBar?.getBoundingClientRect(); const styles = getComputedStyle(probe); @@ -49,7 +111,8 @@ export function ChatCanvas({ bottom: findBarBounds ? findBarBounds.bottom - canvasBounds.top : 0, } : null, - width: element.clientWidth, + width, + narrowestWidth: transitionWidths?.narrowestWidth ?? width, height: element.clientHeight, padding: Number.parseFloat(styles.paddingLeft), maxChatWidth: Number.parseFloat(styles.width), @@ -65,7 +128,11 @@ export function ChatCanvas({ if (findBar) observed.push(findBar); if (composerOverlayElement) observed.push(composerOverlayElement); if (timelineElement) observed.push(timelineElement); - return observeResize(observed, measure); + const stopObserving = observeResize(observed, measure); + return () => { + disposed = true; + stopObserving(); + }; }, [store, composerOverlayElement, timelineElement, detailsCardTopInset]); const detailsCardInlineOpen = useRightPanelStore((state) => threadRef === null diff --git a/apps/web/src/components/chat/canvasStore.test.ts b/apps/web/src/components/chat/canvasStore.test.ts index ad2fe38b044ba..c7620f1db5c87 100644 --- a/apps/web/src/components/chat/canvasStore.test.ts +++ b/apps/web/src/components/chat/canvasStore.test.ts @@ -31,9 +31,9 @@ const preview: ChatCanvasPreview = { describe("chat canvas model", () => { it("shows the details card inline only where the canvas fits it beside the chat", () => { - const resolve = (width: number) => + const resolve = (width: number, narrowestWidth = width) => resolveChatCanvasModel({ - measurements: measurements(width), + measurements: { ...measurements(width), narrowestWidth }, detailsCardMeasurement: null, threadRef, preview: null, @@ -41,6 +41,7 @@ describe("chat canvas model", () => { }).detailsCardMode; expect(resolve(1400)).toBe("inline"); expect(resolve(900)).toBe("popover"); + expect(resolve(1400, 900)).toBe("popover"); }); it("moves the card into a popover when a preview below it leaves too little height", () => { @@ -79,5 +80,8 @@ describe("chat canvas model", () => { store.getState().measureDetailsCard({ threadRef, width: 280, fullContentHeight: 300 }); expect(measured.measurements).toBe(before.measurements); expect(store.getState()).toBe(measured); + store.getState().setMeasurements({ ...measurements(1400), narrowestWidth: 900 }); + expect(store.getState().measurements.narrowestWidth).toBe(900); + expect(store.getState()).not.toBe(measured); }); }); diff --git a/apps/web/src/components/chat/canvasStore.ts b/apps/web/src/components/chat/canvasStore.ts index 76fb540dc5d41..6b350cf95f22f 100644 --- a/apps/web/src/components/chat/canvasStore.ts +++ b/apps/web/src/components/chat/canvasStore.ts @@ -13,6 +13,7 @@ interface CanvasEdges { export interface ChatCanvasMeasurements { readonly width: number; + readonly narrowestWidth?: number; readonly height: number; readonly padding: number; readonly maxChatWidth: number; @@ -47,6 +48,7 @@ const sameEdges = (a: CanvasEdges | null, b: CanvasEdges | null) => const sameMeasurements = (a: ChatCanvasMeasurements, b: ChatCanvasMeasurements) => a.width === b.width && + a.narrowestWidth === b.narrowestWidth && a.height === b.height && a.padding === b.padding && a.maxChatWidth === b.maxChatWidth && @@ -101,6 +103,7 @@ export function resolveChatCanvasModel({ // preview overlap has pushed the card itself into popover mode. const preferredDetailsCard = resolveThreadDetailsCardLayout({ container, + narrowestWidth: measurements.narrowestWidth ?? measurements.width, lane, frame: null, topInset: detailsCardTopInset, @@ -139,6 +142,7 @@ export function resolveChatCanvasModel({ }); const detailsCardPlacement = resolveThreadDetailsCardLayout({ container, + narrowestWidth: measurements.narrowestWidth ?? measurements.width, lane, frame: layout.frame, overlapsDetailsCard: layout.overlapsDetailsCard, diff --git a/apps/web/src/components/chat/chatCanvasLayout.test.ts b/apps/web/src/components/chat/chatCanvasLayout.test.ts index 748d8abb5d1ac..2f9e82a9e600b 100644 --- a/apps/web/src/components/chat/chatCanvasLayout.test.ts +++ b/apps/web/src/components/chat/chatCanvasLayout.test.ts @@ -357,4 +357,18 @@ describe("workspace card beside chat", () => { expect(card.x - chat.left - chat.width).toBeGreaterThanOrEqual(32); } }); + it("stays out of a panel animation that ends or starts too narrow for it", () => { + const place = (width: number, narrowestWidth: number) => + resolveThreadDetailsCardLayout({ + container: { width, height: 900 }, + narrowestWidth, + lane: { padding: 48, minChatWidth: 640 }, + frame: null, + }); + expect(place(1344, 1344)).toMatchObject({ x: 1052 }); + expect(place(1344, 804)).toBeNull(); + expect(place(1344, 1124)).toMatchObject({ x: 1052 }); + // A window resize mid-animation leaves the sampled ends wider than the canvas. + expect(place(900, 1344)).toBeNull(); + }); }); diff --git a/apps/web/src/components/chat/threadDetailsCardLayout.ts b/apps/web/src/components/chat/threadDetailsCardLayout.ts index 7b5e1be8f29b3..a84098fb720ca 100644 --- a/apps/web/src/components/chat/threadDetailsCardLayout.ts +++ b/apps/web/src/components/chat/threadDetailsCardLayout.ts @@ -16,12 +16,15 @@ export function resolveThreadDetailsCardDensity( export function resolveThreadDetailsCardLayout({ container, + narrowestWidth = container.width, lane, frame, overlapsDetailsCard = false, topInset = 0, }: { container: { width: number; height: number }; + // While a panel animates the container, the card fits only if it fits at both ends. + narrowestWidth?: number; lane: { padding: number; minChatWidth: number }; frame: PreviewMiniPlayerFrame | null; overlapsDetailsCard?: boolean; @@ -30,7 +33,11 @@ export function resolveThreadDetailsCardLayout({ const gap = THREAD_DETAILS_CARD_GAP; const width = THREAD_DETAILS_CARD_WIDTH; const x = container.width - width - gap; - if (x - DETAILS_CARD_CLEARANCE - lane.padding < lane.minChatWidth) return null; + // The transition ends are sampled once, so a resize mid-animation can leave them + // wider than the container is now. + const fitWidth = Math.min(narrowestWidth, container.width); + if (fitWidth - width - gap - DETAILS_CARD_CLEARANCE - lane.padding < lane.minChatWidth) + return null; const y = gap + topInset; const height = overlapsDetailsCard && frame && frame.x + frame.width > x - gap && frame.x < x + width + gap From 20ff8e7173b5b52c9c7dc7709ec285ec685093ff Mon Sep 17 00:00:00 2001 From: BelKed <66956532+BelKed@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:32:52 +0100 Subject: [PATCH 017/140] fix(desktop): hold page dialogs from guest attach --- apps/desktop/src/preview/Manager.test.ts | 41 +++++++++++++++++++- apps/desktop/src/preview/Manager.ts | 30 ++++++++------ apps/desktop/src/preview/PageDialogs.test.ts | 15 ------- apps/desktop/src/preview/PageDialogs.ts | 23 +++++------ 4 files changed, 67 insertions(+), 42 deletions(-) diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index bbb0ef073078f..03ec0f6118e5b 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -1712,8 +1712,9 @@ describe("PreviewManager", () => { ), ); - const makeAudioWebContents = (id: number) => { + const makeAudioWebContents = (id: number, nativeDialog?: (...args: never[]) => void) => { const listeners = new Map void>(); + if (nativeDialog) listeners.set("-run-dialog", nativeDialog); let debuggerMessage: ((...args: ReadonlyArray) => void) | undefined; const setAudioMuted = vi.fn(); let audible = false; @@ -1766,7 +1767,8 @@ describe("PreviewManager", () => { navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), setWindowOpenHandler: vi.fn(), - listeners: () => [], + listeners: (event: string) => + event === "-run-dialog" && nativeDialog ? [nativeDialog] : [], debugger: { isAttached: () => false, attach: vi.fn(), @@ -1823,6 +1825,7 @@ describe("PreviewManager", () => { }), ); yield* manager.createTab("tab_dialog"); + yield* manager.prepareWebview(guest.wc); yield* manager.registerWebview("tab_dialog", 42); yield* Effect.yieldNow; @@ -1853,6 +1856,7 @@ describe("PreviewManager", () => { yield* Effect.yieldNow; const replacement = makeAudioWebContents(43); fromId.mockReturnValue(replacement.wc); + yield* manager.prepareWebview(replacement.wc); yield* manager.registerWebview("tab_dialog", 43); yield* Effect.yieldNow; expect(states.at(-1)?.dialog).toBeUndefined(); @@ -1873,6 +1877,39 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("holds a page dialog raised before the guest is registered", () => + withManager((manager) => + Effect.gen(function* () { + const native = vi.fn(); + const guest = makeAudioWebContents(45, native); + fromId.mockReturnValue(guest.wc); + const states: PreviewManager.PreviewTabState[] = []; + const answer = vi.fn(); + + yield* manager.subscribeStateChanges((_tabId, state) => + Effect.sync(() => { + states.push(state); + }), + ); + yield* manager.createTab("tab_dialog_early"); + yield* manager.prepareWebview(guest.wc); + guest.emit( + "-run-dialog", + { dialogType: "alert", messageText: "Hi", defaultPromptText: "" }, + answer, + ); + yield* manager.registerWebview("tab_dialog_early", 45); + yield* Effect.yieldNow; + + expect(native).not.toHaveBeenCalled(); + expect(states.at(-1)?.dialog).toEqual({ type: "alert", message: "Hi", defaultValue: "" }); + + yield* manager.answerDialog("tab_dialog_early", true, undefined); + expect(answer).toHaveBeenCalledExactlyOnceWith(true, ""); + }), + ), + ); + effectIt.effect("ignores audio state from a replaced guest", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index a2c9077849886..caa15fd4cab53 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -965,16 +965,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); const syncTabDialog = Effect.fn("PreviewManager.syncTabDialog")(function* ( - tabId: string, wc: Electron.WebContents, dialog: DesktopPreviewDialog | null, ) { const updatedAt = yield* currentIso; const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => { - const current = tabs.get(tabId); - if (!current || current.webContentsId !== wc.id) { - return [Option.none(), tabs] as const; - } + const entry = [...tabs].find(([, tab]) => tab.webContentsId === wc.id); + if (!entry) return [Option.none(), tabs] as const; + const [tabId, current] = entry; const { dialog: _dialog, ...withoutDialog } = current; const state: PreviewTabState = { ...withoutDialog, @@ -982,15 +980,23 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function updatedAt, }; return [ - Option.some(state), + Option.some([tabId, state] as const), replaceMap(tabs, (copy) => { copy.set(tabId, state); }), ] as const; }); - if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value); + if (Option.isSome(next)) yield* emitIfCurrent(next.value[0], next.value[1]); }); + const ensureDialogHold = (wc: Electron.WebContents) => { + if (dialogHolds.has(wc.id)) return; + dialogHolds.set( + wc.id, + holdPageDialogs(wc, (dialog) => runFork(syncTabDialog(wc, dialog))), + ); + }; + const requireWebContents = Effect.fn("PreviewManager.requireWebContents")(function* ( tabId: string, ) { @@ -1230,7 +1236,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const scope = yield* Scope.fork(parentScope, "sequential"); const attachmentId = Symbol(); let detachPasskeys = () => {}; - let dialogHold: PageDialogHold | undefined; let documentId = 0; let nextRequestId = 0; let activeCapture: { @@ -1687,8 +1692,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); wc.ipc.off(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys(); - if (dialogHolds.get(wc.id) === dialogHold) dialogHolds.delete(wc.id); - dialogHold?.release(); + dialogHolds.get(wc.id)?.answer(false); }).pipe(Effect.ignore), ); const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () { @@ -1705,8 +1709,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.on("did-fail-load", failed as never); wc.on("audio-state-changed", audioStateChanged); wc.on("found-in-page", foundInPage as never); - dialogHold = holdPageDialogs(wc, (dialog) => runFork(syncTabDialog(tabId, wc, dialog))); - dialogHolds.set(wc.id, dialogHold); wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput); wc.ipc.on(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); @@ -2002,8 +2004,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null; const failure = guestLoadFailures.get(webContentsId); const { favicon: _favicon, dialog: _dialog, ...currentWithoutFavicon } = current; + const pendingDialog = dialogHolds.get(webContentsId)?.current(); const next: PreviewTabState = { ...currentWithoutFavicon, + ...(pendingDialog ? { dialog: pendingDialog } : {}), webContentsId, navStatus: failure && (pendingUrl === null || pendingUrl === failure.url) @@ -2078,6 +2082,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ) { yield* rendererHistory.register(wc, { surface: "preview" }); const webContentsId = wc.id; + ensureDialogHold(wc); wc.on("did-start-navigation", (event) => { if (event.isMainFrame && !event.isSameDocument) guestLoadFailures.delete(webContentsId); }); @@ -2092,6 +2097,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.once("destroyed", () => { guestLoadFailures.delete(webContentsId); dialogHolds.get(webContentsId)?.closed(); + dialogHolds.delete(webContentsId); runFork(hideDestroyedGuest(webContentsId)); runFork(detachControlSession(webContentsId)); }); diff --git a/apps/desktop/src/preview/PageDialogs.test.ts b/apps/desktop/src/preview/PageDialogs.test.ts index 88f9bf31f53d4..c702b444c6298 100644 --- a/apps/desktop/src/preview/PageDialogs.test.ts +++ b/apps/desktop/src/preview/PageDialogs.test.ts @@ -61,19 +61,4 @@ describe("holdPageDialogs", () => { expect(hold.answer(true)).toBe(false); expect(callback).not.toHaveBeenCalled(); }); - - it("dismisses a pending dialog and hands the native handler back on release", () => { - const { contents, native, changed, hold, callback } = setup(); - contents.emit("-run-dialog", info, callback); - callback.mockImplementation(() => { - throw new Error("callback already used"); - }); - - hold.release(); - - expect(callback).toHaveBeenCalledWith(false, ""); - expect(changed).toHaveBeenLastCalledWith(null); - contents.emit("-run-dialog", info, vi.fn()); - expect(native).toHaveBeenCalledOnce(); - }); }); diff --git a/apps/desktop/src/preview/PageDialogs.ts b/apps/desktop/src/preview/PageDialogs.ts index 08c7a86331676..96d9feb538f13 100644 --- a/apps/desktop/src/preview/PageDialogs.ts +++ b/apps/desktop/src/preview/PageDialogs.ts @@ -13,7 +13,7 @@ export interface PageDialogHold { readonly answer: (accept: boolean, promptText?: string) => boolean; /** Forgets the pending dialog after something else, such as CDP, closed it. */ readonly closed: () => void; - readonly release: () => void; + readonly current: () => DesktopPreviewDialog | null; } // Electron shows page dialogs as a native app-modal box from the `-run-dialog` event and never @@ -22,11 +22,12 @@ export function holdPageDialogs( contents: NodeJS.EventEmitter, changed: (dialog: DesktopPreviewDialog | null) => void, ): PageDialogHold { - const native = contents.listeners("-run-dialog") as Array<(...args: unknown[]) => void>; let pending: DialogCallback | null = null; + let shown: DesktopPreviewDialog | null = null; const clear = () => { if (pending === null) return; pending = null; + shown = null; changed(null); }; const deliver = (callback: DialogCallback, accept: boolean, userInput: string) => { @@ -41,13 +42,16 @@ export function holdPageDialogs( const previous = pending; if (previous !== null) deliver(previous, false, ""); pending = callback; - changed({ + shown = { type: info.dialogType, message: info.messageText, defaultValue: info.defaultPromptText, - }); + }; + changed(shown); }; - for (const listener of native) contents.off("-run-dialog", listener); + for (const listener of contents.listeners("-run-dialog")) { + contents.off("-run-dialog", listener as (...args: unknown[]) => void); + } contents.on("-run-dialog", run); contents.on("-cancel-dialogs", clear); return { @@ -58,13 +62,6 @@ export function holdPageDialogs( return deliver(callback, accept, promptText ?? ""); }, closed: clear, - release: () => { - const callback = pending; - clear(); - if (callback !== null) deliver(callback, false, ""); - contents.off("-run-dialog", run); - contents.off("-cancel-dialogs", clear); - for (const listener of native) contents.on("-run-dialog", listener); - }, + current: () => shown, }; } From 2dd810d0f609415a205af637f9e6983dfb5785b1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 14 Nov 2026 14:33:08 -0800 Subject: [PATCH 018/140] fix(web,mobile): /btw and /side drafts show the send arrow while a turn runs (#36932) --- apps/mobile/src/features/threads/ThreadComposer.tsx | 8 +++++++- apps/mobile/src/features/threads/ThreadDetailScreen.tsx | 4 ++++ apps/web/src/components/chat/ChatComposer.tsx | 8 ++++++-- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index fe4393a97bddf..fdd6b414a46e5 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -30,6 +30,7 @@ import { hasProviderUsageLimits, isUsageLimitsCommand, } from "@t3tools/shared/usageLimits"; +import { parseSideChatCommand } from "@t3tools/shared/composerTrigger"; import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native"; import type { ReactNode } from "react"; import { useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; @@ -236,6 +237,8 @@ export interface ThreadComposerProps { readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; readonly activeThreadBusy: boolean; + /** Sending declines a pending approval and redirects the agent, so `/side` is plain text. */ + readonly redirectsApproval: boolean; readonly canStopThread: boolean; readonly environmentId: EnvironmentId; readonly projectCwd: string | null; @@ -499,7 +502,10 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps }); const sendPresentation = resolveComposerSendPresentation({ editingQueuedMessage: queuedEdit !== null, - running: props.activeThreadBusy, + // A side-chat command starts a side chat; it never queues or steers the running turn. + running: + props.activeThreadBusy && + (props.redirectsApproval || parseSideChatCommand(draftMessage) === null), canSteer: props.canSteerActiveTurn, followUpBehavior: props.followUpBehavior, deliveryDeferred: diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 12805a1483429..73b985fc20144 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1890,6 +1890,10 @@ function ThreadDetailBody( serverConfig={props.serverConfig} queueCount={props.selectedThreadQueueCount} activeThreadBusy={props.activeThreadBusy} + redirectsApproval={ + props.activePendingApprovals.length > 0 && + props.activePendingUserInput === null + } canStopThread={props.canStopThread} environmentId={props.environmentId} projectCwd={props.threadCwd ?? props.projectWorkspaceRoot} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 978bab1d1e1ca..77dce596892d5 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -53,7 +53,7 @@ import * as Schema from "effect/Schema"; import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions"; import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; +import { parseSideChatCommand, serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { type FolderDropTarget, folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; import { splitTransferredFiles } from "./workspaceFileDrop"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; @@ -3731,7 +3731,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) compact={isComposerPrimaryActionsCompact} canOperateThread={canOperateThread} pendingAction={pendingPrimaryAction} - isRunning={phase === "running" || phase === "connecting"} + // A side-chat command starts a side chat; it never queues or steers the turn. + isRunning={ + (phase === "running" || phase === "connecting") && + !(props.sideChatAvailable === true && parseSideChatCommand(prompt) !== null) + } canInterrupt={canInterrupt} runId={activeThread?.runtime?.activeRunId ?? null} followUpBehavior={followUpBehavior} From ab2bf940f620f4ddf920588eb6c6cc88f2e67428 Mon Sep 17 00:00:00 2001 From: Advait Paliwal Date: Sat, 14 Nov 2026 17:33:20 -0500 Subject: [PATCH 019/140] fix(server): migrated databases can return freed space to disk (#30066) Co-authored-by: maria-rcks Co-authored-by: Julius Marminge --- .../persistence/initializeV2Database.test.ts | 4 +- .../src/persistence/initializeV2Database.ts | 39 +++++++++++++------ 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/apps/server/src/persistence/initializeV2Database.test.ts b/apps/server/src/persistence/initializeV2Database.test.ts index f8c68f49ceb9a..aa8357542e927 100644 --- a/apps/server/src/persistence/initializeV2Database.test.ts +++ b/apps/server/src/persistence/initializeV2Database.test.ts @@ -132,7 +132,7 @@ it.effect("includes committed WAL data and does not publish a failed snapshot", const source = new NodeSqlite.DatabaseSync(sourcePath); try { source.exec( - "PRAGMA journal_mode=WAL; CREATE TABLE messages(text TEXT); INSERT INTO messages VALUES ('committed'); BEGIN; INSERT INTO messages VALUES ('uncommitted');", + "PRAGMA journal_mode=WAL; CREATE TABLE messages(text TEXT); INSERT INTO messages VALUES ('committed'); CREATE TABLE dropped(blob BLOB); INSERT INTO dropped VALUES (randomblob(65536)); DROP TABLE dropped; BEGIN; INSERT INTO messages VALUES ('uncommitted');", ); yield* initializeV2Database(destinationPath); const copy = new NodeSqlite.DatabaseSync(destinationPath, { readOnly: true }); @@ -144,6 +144,8 @@ it.effect("includes committed WAL data and does not publish a failed snapshot", .map((row) => row.text), ["committed"], ); + assert.deepEqual(copy.prepare("PRAGMA auto_vacuum").get(), { auto_vacuum: 2 }); + assert.deepEqual(copy.prepare("PRAGMA freelist_count").get(), { freelist_count: 0 }); } finally { copy.close(); } diff --git a/apps/server/src/persistence/initializeV2Database.ts b/apps/server/src/persistence/initializeV2Database.ts index 492567c7980da..1a9f4bac55543 100644 --- a/apps/server/src/persistence/initializeV2Database.ts +++ b/apps/server/src/persistence/initializeV2Database.ts @@ -1,4 +1,4 @@ -import * as NodeSqlite from "node:sqlite"; +import * as NodeWorkerThreads from "node:worker_threads"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -26,6 +26,20 @@ const isProcessAlive = (pid: number): boolean => { } }; +// V1 files predate auto_vacuum, and a page backup would keep that. VACUUM INTO compacts the copy and +// enables incremental mode, so the server can return freed pages; the worker keeps it off the event loop. +const snapshotWorkerSource = ` +const { workerData } = require("node:worker_threads"); +const { DatabaseSync } = require("node:sqlite"); +const database = new DatabaseSync(workerData.sourcePath, { readOnly: true }); +try { + database.exec("PRAGMA auto_vacuum = INCREMENTAL"); + database.prepare("VACUUM INTO ?").run(workerData.snapshotPath); +} finally { + database.close(); +} +`; + // Legacy names have no PID; newer copies stay while their process is alive. const removeAbandonedCopies = Effect.fn("removeAbandonedCopies")(function* (directory: string) { const fs = yield* FileSystem.FileSystem; @@ -60,16 +74,19 @@ export const initializeV2Database = Effect.fn("initializeV2Database")(function* prefix: `.v2-import-${process.pid}-`, }); const snapshotPath = path.join(temporaryDirectory, "snapshot.sqlite"); - yield* Effect.tryPromise({ - try: async () => { - const database = new NodeSqlite.DatabaseSync(sourcePath, { readOnly: true }); - try { - await NodeSqlite.backup(database, snapshotPath); - } finally { - database.close(); - } - }, - catch: (cause) => new V2DatabaseImportError({ sourcePath, destinationPath, cause }), + yield* Effect.callback((resume) => { + const fail = (cause: unknown) => + resume(Effect.fail(new V2DatabaseImportError({ sourcePath, destinationPath, cause }))); + const worker = new NodeWorkerThreads.Worker(snapshotWorkerSource, { + eval: true, + workerData: { sourcePath, snapshotPath }, + }); + worker.once("error", fail); + worker.once("exit", (code) => + code === 0 ? resume(Effect.void) : fail(new Error(`Snapshot worker exited with ${code}`)), + ); + // Interruption waits for the worker to exit before the scope removes its directory. + return Effect.promise(() => worker.terminate()); }); // Publish only a complete snapshot, without replacing an existing V2 database. yield* fs.link(snapshotPath, destinationPath).pipe( From 88c42f471b0ccebb9d404e334b2179664fc22239 Mon Sep 17 00:00:00 2001 From: Hirbod <504909+hirbod@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:38:10 +0000 Subject: [PATCH 020/140] fix(devices): rename EAS Simulator to Expo Simulators (#36951) --- apps/server/graphql.config.ts | 2 +- apps/server/src/device/DeviceHost.ts | 2 +- apps/server/src/device/DeviceHubProxy.ts | 2 +- apps/server/src/device/DeviceService.test.ts | 2 +- apps/server/src/device/DeviceService.ts | 6 +-- apps/server/src/device/EasDeviceHost.test.ts | 12 +++--- apps/server/src/device/EasDeviceHost.ts | 42 ++++++++++--------- apps/server/src/device/ExpoApi.test.ts | 2 +- apps/server/src/device/ExpoApi.ts | 4 +- apps/server/src/device/easProjectId.test.ts | 2 +- apps/server/src/device/easProjectId.ts | 4 +- .../src/device/localSshDeviceHost.test.ts | 2 +- apps/server/src/mcp/McpDeviceToolkit.test.ts | 2 +- .../src/mcp/toolkits/device/handlers.ts | 4 +- apps/server/src/mcp/toolkits/device/tools.ts | 2 +- apps/server/src/serverSettings.test.ts | 6 +-- apps/server/src/settingsSecrets.ts | 2 +- .../web/src/components/device/DeviceSetup.tsx | 2 +- .../src/components/device/DeviceWorkspace.tsx | 2 +- .../settings/DeviceSourcesSettings.tsx | 8 ++-- .../settings/EasDeviceHostEditor.tsx | 12 +++--- .../settings/SecretsSettings.logic.test.ts | 4 +- .../easDeviceHostsSettings.logic.test.ts | 4 +- .../settings/easDeviceHostsSettings.logic.ts | 4 +- apps/web/src/state/device.ts | 2 +- docs/internals/devices.md | 12 +++--- docs/user/devices.md | 2 +- packages/client-runtime/src/device/stream.ts | 4 +- packages/client-runtime/src/state/device.ts | 4 +- packages/contracts/src/device.test.ts | 18 ++++---- packages/contracts/src/device.ts | 22 +++++----- packages/contracts/src/settings.test.ts | 8 ++-- 32 files changed, 104 insertions(+), 102 deletions(-) diff --git a/apps/server/graphql.config.ts b/apps/server/graphql.config.ts index f042d039410db..56d7c92d603af 100644 --- a/apps/server/graphql.config.ts +++ b/apps/server/graphql.config.ts @@ -1,7 +1,7 @@ import { defineConfig } from "@effect/graphql-generator/Config"; // `schema/expo.graphql` is api.expo.dev's schema, read by introspection -// (`vp run generate:expo-schema`). The EAS Simulator operations are the ones +// (`vp run generate:expo-schema`). The Expo Simulators operations are the ones // eas-cli's `simulator:*` commands send; Expo does not document them. export default defineConfig({ schema: "./schema/expo.graphql", diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.ts index eafa3b6319de3..898b028c4329c 100644 --- a/apps/server/src/device/DeviceHost.ts +++ b/apps/server/src/device/DeviceHost.ts @@ -139,7 +139,7 @@ export interface DeviceOperations { deviceId: string, ) => Effect.Effect; /** - * Set by hosts that end devices on their own (EAS stops sessions at their + * Set by hosts that end devices on their own (Expo stops sessions at their * limits), so a session on a device the host stops listing is dropped. */ readonly endsDevices?: boolean; diff --git a/apps/server/src/device/DeviceHubProxy.ts b/apps/server/src/device/DeviceHubProxy.ts index 56132433c8869..0d606df1d513a 100644 --- a/apps/server/src/device/DeviceHubProxy.ts +++ b/apps/server/src/device/DeviceHubProxy.ts @@ -155,7 +155,7 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* ( const response = yield* httpClient.execute(upstreamRequest); const headers: Record = {}; for (const [name, value] of Object.entries(response.headers)) { - // A cookie from an upstream such as an EAS session's preview host would land on T3's origin. + // A cookie from an upstream such as an Expo Simulators session's preview host would land on T3's origin. if ( name === "content-encoding" || name === "transfer-encoding" || diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 71c7b6994ca86..ff93492f4c1f1 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -347,7 +347,7 @@ const fixture = Effect.fn("fixture")(function* ( }), ), ); - // The host ending a device on its own, as EAS does at a session's limits. + // The host ending a device on its own, as Expo does at a session's limits. const endDevice = () => { booted = false; }; diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index 78b31b87aefd3..12efc1b1f297c 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -163,7 +163,7 @@ export class DeviceService extends Context.Service< readonly testHost: ( config: SshDeviceHostConfig, ) => Effect.Effect; - /** Who an Expo credential signs in as and which EAS projects it can run sessions under. */ + /** Who an Expo credential signs in as and which Expo projects it can run sessions under. */ readonly easAccount: ( input: DeviceEasAccountInput, ) => Effect.Effect; @@ -598,7 +598,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* ), ...devices.filter((device) => !incompletePlatforms.includes(device.platform)), ], - // A host that ends devices itself (EAS stops sessions at their limits) + // A host that ends devices itself (Expo stops sessions at their limits) // leaves sessions on devices it no longer lists with nothing to stream. // Other hosts can miss a device for one listing, so theirs stay. sessions: ready.devices.endsDevices @@ -1127,7 +1127,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* easAccount: Effect.fn("DeviceService.easAccount")(function () { return Effect.fail( new DeviceEasAccountError({ - reason: "EAS accounts are unavailable in this device service.", + reason: "Expo accounts are unavailable in this device service.", }), ); }), diff --git a/apps/server/src/device/EasDeviceHost.test.ts b/apps/server/src/device/EasDeviceHost.test.ts index 3c083cdcbb7f8..eaceea13f4fbf 100644 --- a/apps/server/src/device/EasDeviceHost.test.ts +++ b/apps/server/src/device/EasDeviceHost.test.ts @@ -26,7 +26,7 @@ const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454"; const config = (overrides: Partial = {}): EasDeviceHostConfig => ({ kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", appId: APP_ID, accessToken: "expo-token", maxSessionMinutes: 25, @@ -174,7 +174,7 @@ const fakeExpo = ( node: { id: "someone-else", status: "IN_PROGRESS", - name: "T3 Code · EAS Simulator · 000000", + name: "T3 Code · Expo Simulators · 000000", }, }, ...(options.active ?? []).map((node) => ({ node })), @@ -260,7 +260,7 @@ const makeHost = ( Effect.provideService(Scope.Scope, scope), ); -describe("EAS Simulator host", () => { +describe("Expo Simulators host", () => { it.effect("starts a bounded session and routes its stream and agent to that session", () => Effect.gen(function* () { const expo = fakeExpo(); @@ -433,13 +433,13 @@ describe("EAS Simulator host", () => { yield* ready.devices.boot(catalogDevice!); const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip); expect(refused.message).toBe( - "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.", + "Expo Simulators is unavailable: Expo Simulators is limited to 1 running session. Close one in the Device panel first.", ); expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1); }).pipe(Effect.scoped, Effect.provide(layer)), ); - it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () => + it.effect("tells concurrent sessions apart although Expo gives each the same UDID", () => Effect.gen(function* () { const expo = fakeExpo(); const scope = yield* Scope.make(); @@ -610,7 +610,7 @@ describe("EAS Simulator host", () => { }).pipe(Effect.scoped, Effect.provide(layer)), ); - it.effect("asks for an EAS project before starting anything when none can be found", () => + it.effect("asks for an Expo project before starting anything when none can be found", () => Effect.gen(function* () { const expo = fakeExpo(); const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make()); diff --git a/apps/server/src/device/EasDeviceHost.ts b/apps/server/src/device/EasDeviceHost.ts index 719cfbf435a8a..0751a41b6d309 100644 --- a/apps/server/src/device/EasDeviceHost.ts +++ b/apps/server/src/device/EasDeviceHost.ts @@ -1,5 +1,5 @@ /** - * Cloud simulators from EAS Simulator. A device exists only while a session + * Cloud simulators from Expo Simulators. A device exists only while a session * runs, and every session bills the Expo account until it stops, so this host * bounds each one, stops all of them when it stops, and stops sessions a * previous server left behind. It never touches sessions it did not start. @@ -59,14 +59,14 @@ const decodeServeEmuApi = Schema.decodeUnknownEffect( */ const PLATFORMS = { ios: { - name: "iPhone (EAS Simulator)", + name: "iPhone (Expo Simulator)", hubPrefix: "/vendor/serve-sim", previewPrefix: "", protocol: "serve-sim", remoteDeviceId: (api: unknown) => decodeServeSimApi(api).pipe(Effect.map((api) => api.device)), }, android: { - name: "Android (EAS Simulator)", + name: "Android (Expo Simulator)", hubPrefix: "/vendor/serve-emu", previewPrefix: "/vendor/serve-emu", protocol: "serve-emu", @@ -74,7 +74,7 @@ const PLATFORMS = { }, } as const; -/** EAS picks the simulator model; one entry starts a session. */ +/** Expo picks the simulator model; one entry starts a session. */ const CATALOG: ReadonlyArray = [ { id: "eas-ios", @@ -163,7 +163,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice >(); const hostId = config.id; const ledgerPath = path.join(server.stateDir, "device", "eas", `${hostId}.json`); - // Keyed by Expo's session id, which is also the device id: every EAS + // Keyed by Expo's session id, which is also the device id: every Expo // simulator reports the same remote device id, so that id cannot tell sessions apart. const sessions = new Map(); const checkedAt = new Map(); @@ -239,7 +239,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice Effect.flatMap(decodeLedger), Effect.mapError((cause) => unavailable( - `The record of running EAS sessions at ${ledgerPath} could not be read. Fix or remove it.`, + `The record of running Expo Simulators sessions at ${ledgerPath} could not be read. Fix or remove it.`, cause, ), ), @@ -256,7 +256,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice Effect.provide(services), Effect.mapError((cause) => unavailable( - `The record of running EAS sessions at ${ledgerPath} could not be written.`, + `The record of running Expo Simulators sessions at ${ledgerPath} could not be written.`, cause, ), ), @@ -267,13 +267,13 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice entries.map((entry) => (entry.name === name ? { ...entry, refused: true } : entry)), ).pipe( Effect.catch((cause) => - Effect.logWarning("Could not update the EAS session record", { name, cause }), + Effect.logWarning("Could not update the Expo Simulators session record", { name, cause }), ), ); const forgetEntry = (name: string) => writeLedger((entries) => entries.filter((entry) => entry.name !== name)).pipe( Effect.catch((cause) => - Effect.logWarning("Could not update the EAS session record", { name, cause }), + Effect.logWarning("Could not update the Expo Simulators session record", { name, cause }), ), ); @@ -282,7 +282,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice expo.stop(sessionId).pipe( Effect.andThen(forgetEntry(name)), Effect.tapError((cause) => - Effect.logWarning("Could not stop EAS Simulator session", { sessionId, cause }), + Effect.logWarning("Could not stop Expo Simulators session", { sessionId, cause }), ), ); @@ -403,7 +403,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice }, reapLock.withPermit, Effect.catch((cause) => - Effect.logWarning("Could not stop recorded EAS Simulator sessions", { cause }), + Effect.logWarning("Could not stop recorded Expo Simulators sessions", { cause }), ), ); @@ -439,7 +439,9 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice hostId, deviceId: sessionId, reason: "launch_failed", - cause: new Error(`EAS Simulator session ended (${session.status}) before it was ready`), + cause: new Error( + `Expo Simulators session ended (${session.status}) before it was ready`, + ), }); } if (session.status === "IN_PROGRESS" && session.endpoints) return session.endpoints; @@ -456,7 +458,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice hostId, deviceId: sessionId, reason: "timeout", - cause: new Error("EAS Simulator session did not start in time"), + cause: new Error("Expo Simulators session did not start in time"), }), ), }), @@ -504,7 +506,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice ); if (!appId) { return yield* unavailable( - "No EAS project to run the session under. Choose one for this host in Settings, or open the device from a thread whose project names extra.eas.projectId in app.json or its app config.", + "No Expo project to run the session under. Choose one for this host in Settings, or open the device from a thread whose project names extra.eas.projectId in app.json or its app config.", ); } const access = yield* expo @@ -512,7 +514,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice .pipe(Effect.mapError((error) => unavailable(error.message, error))); if (!access.available) { return yield* unavailable( - `EAS Simulator is not enabled for the ${access.account} Expo account.`, + `Expo Simulators is not enabled for the ${access.account} Expo account.`, ); } const entry = { name, appId, recordedAt: yield* Clock.currentTimeMillis }; @@ -593,7 +595,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice hostId, deviceId: sessionId, reason: "launch_failed", - cause: new Error("EAS Simulator returned no preview endpoint"), + cause: new Error("Expo Simulators returned no preview endpoint"), }); } const origin = new URL(endpoints.preview.url).origin; @@ -767,7 +769,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice new DeviceOperationError({ operation: "screenshot", reason: "request_failed", - cause: new Error("The EAS Simulator session is not running"), + cause: new Error("The Expo Simulator is not running"), }), ), onSome: (session) => @@ -795,7 +797,7 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice }), agentEndpoint: (deviceId) => Option.match(sessionFor(deviceId), { - onNone: () => Effect.fail(unavailable("This EAS Simulator device is no longer running.")), + onNone: () => Effect.fail(unavailable("This Expo Simulator is no longer running.")), onSome: (session) => Effect.succeed({ ...session.agent, agentDeviceId: session.remoteDeviceId }), }), @@ -858,11 +860,11 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice onNone: () => Effect.void, onSome: (running) => releaseAgentDeviceSession(http, running.agent)(session), }), - // Device settings run simctl on the simulator's own machine, which EAS does not expose. + // Device settings run simctl on the simulator's own machine, which Expo does not expose. run: () => Effect.succeed({ stdout: "", - stderr: "EAS Simulator devices cannot run host commands.", + stderr: "Devices from Expo Simulators cannot run host commands.", code: 127, }), helpers: { serveSimAxSettings: null, serveSimCli: null }, diff --git a/apps/server/src/device/ExpoApi.test.ts b/apps/server/src/device/ExpoApi.test.ts index 730d34d38d9f8..491a75f97a0e7 100644 --- a/apps/server/src/device/ExpoApi.test.ts +++ b/apps/server/src/device/ExpoApi.test.ts @@ -154,7 +154,7 @@ describe("Expo API", () => { .availability("app-1") .pipe(Effect.flip); expect(graphQl.message).toBe( - "Expo could not check EAS Simulator access: Feature not enabled", + "Expo could not check Expo Simulators access: Feature not enabled", ); const rejected = yield* makeExpoApi(respond(new Response("no", { status: 401 })), credential) .stop("session-1") diff --git a/apps/server/src/device/ExpoApi.ts b/apps/server/src/device/ExpoApi.ts index 90a276eeffb99..99371b564e6c1 100644 --- a/apps/server/src/device/ExpoApi.ts +++ b/apps/server/src/device/ExpoApi.ts @@ -1,5 +1,5 @@ /** - * Expo's GraphQL API for EAS Simulator sessions. The operations in + * Expo's GraphQL API for Expo Simulators sessions. The operations in * `ExpoApi.graphql` are the ones eas-cli's `simulator:*` commands send; their * client is generated from `schema/expo.graphql` (`vp run generate`). */ @@ -313,7 +313,7 @@ export const makeExpoApi = (http: HttpClient.HttpClient, credential: ExpoCredent ), ), availability: (appId: string) => - call("check EAS Simulator access", (expo) => + call("check Expo Simulators access", (expo) => expo.T3EasSimulatorAvailability({ appId, filter: [DEVICE_RUN_SESSIONS_GATE] }), ).pipe( Effect.map(({ app }) => { diff --git a/apps/server/src/device/easProjectId.test.ts b/apps/server/src/device/easProjectId.test.ts index 42139f4eff1e1..ea23f444e7f49 100644 --- a/apps/server/src/device/easProjectId.test.ts +++ b/apps/server/src/device/easProjectId.test.ts @@ -246,7 +246,7 @@ it.effect("gives no answer when an app's config is there but cannot be read", () }).pipe(Effect.scoped, Effect.provide(layer)), ); -it.effect("does not guess between apps that name different EAS projects", () => +it.effect("does not guess between apps that name different Expo projects", () => Effect.gen(function* () { const root = yield* workspace({ "apps/one/app.json": JSON.stringify({ expo: { extra: { eas: { projectId: ID_A } } } }), diff --git a/apps/server/src/device/easProjectId.ts b/apps/server/src/device/easProjectId.ts index 524dd6d9519c0..528db26870ca5 100644 --- a/apps/server/src/device/easProjectId.ts +++ b/apps/server/src/device/easProjectId.ts @@ -33,7 +33,7 @@ const SPREAD_LATER = /\.\.\./; // Space, a comment, or an opening parenthesis: what may sit between `...` // and the thing spread. Sticky, so the scan moves through the file once. const SPREAD_FILLER = /(?:\s+|\/\/[^\n\r\u2028\u2029]*|\/\*(?:[^*]|\*(?!\/))*\*\/|\()/y; -// `config`'s `extra` and `extra.eas` entries, the holders of the EAS id +// `config`'s `extra` and `extra.eas` entries, the holders of the Expo project id // (dotted, optional-chained or in brackets). const EXTRA_OF_CONFIG = String.raw`config(?:\s*\??\.\s*extra|\s*(?:\?\.)?\s*\[\s*["'\x60]extra["'\x60]\s*\])`; const EAS_OF_CONFIG = @@ -197,7 +197,7 @@ const projectIdsOf = Effect.fn("easProjectId.projectIdsOf")(function* (dir: stri }); /** - * The EAS project of a workspace's Expo app: its root, or one app below + * The Expo project of a workspace's Expo app: its root, or one app below * `apps/` or `packages/`. None when there is none, a config is ambiguous, or * the apps disagree, so the caller asks for an explicit choice instead of * billing the wrong project. diff --git a/apps/server/src/device/localSshDeviceHost.test.ts b/apps/server/src/device/localSshDeviceHost.test.ts index 4021be704a06e..623f2583acd27 100644 --- a/apps/server/src/device/localSshDeviceHost.test.ts +++ b/apps/server/src/device/localSshDeviceHost.test.ts @@ -83,7 +83,7 @@ it.effect("removes only self targets from a fanned-out host list", () => const eas = { kind: "eas" as const, id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: "", maxSessionMinutes: 30, idleMinutes: 10, diff --git a/apps/server/src/mcp/McpDeviceToolkit.test.ts b/apps/server/src/mcp/McpDeviceToolkit.test.ts index 1904a24010bee..91c33029be305 100644 --- a/apps/server/src/mcp/McpDeviceToolkit.test.ts +++ b/apps/server/src/mcp/McpDeviceToolkit.test.ts @@ -135,7 +135,7 @@ const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({ screenshot: () => Effect.succeed({ device, png }), close: () => Effect.void, testHost: () => Effect.die("not used"), - // As for an EAS device, agent-device knows the device by a different id than T3. + // As for an Expo device, agent-device knows the device by a different id than T3. agentTarget: () => Effect.succeed({ agentDeviceId: "SIM-UDID", diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.ts index d4f0a4fac6a67..382beed7284ac 100644 --- a/apps/server/src/mcp/toolkits/device/handlers.ts +++ b/apps/server/src/mcp/toolkits/device/handlers.ts @@ -49,7 +49,7 @@ export function agentDeviceQuickStart( .filter(Boolean) .join(" ") : host?.kind === "eas" - ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine." + ? "This is an Expo Simulators session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine." : device.platform === "ios" ? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast." : "The Android snapshot helper installs itself on first use."; @@ -275,7 +275,7 @@ const handlers = { after.devices.find( (candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId, ) ?? target; - // Target the opened device: an EAS device and its agent-device daemon + // Target the opened device: an Expo device and its agent-device daemon // exist only once its session runs, and Android ids change on boot. const opened = { threadId: scope.thread.threadId, diff --git a/apps/server/src/mcp/toolkits/device/tools.ts b/apps/server/src/mcp/toolkits/device/tools.ts index 0a79af2efb0f6..14ed87217368e 100644 --- a/apps/server/src/mcp/toolkits/device/tools.ts +++ b/apps/server/src/mcp/toolkits/device/tools.ts @@ -58,7 +58,7 @@ const DeviceOpenTool = Tool.make("device_open", { FileSystem.FileSystem, Path.Path, ServerConfig.ServerConfig, - // The thread's project can name the EAS project a cloud device runs under. + // The thread's project can name the Expo project a cloud device runs under. ProjectService.ProjectService, ], }) diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 3ca2d29da7c81..873649cb168f5 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -1469,7 +1469,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" { kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: "expo-secret", maxSessionMinutes: 30, idleMinutes: 10, @@ -1786,7 +1786,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" { kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: easReference, maxSessionMinutes: 30, idleMinutes: 10, @@ -1906,7 +1906,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" { kind: "eas", id: "eas", - label: "EAS Simulator", + label: "Expo Simulators", accessToken: personal("Expo/token"), maxSessionMinutes: 30, idleMinutes: 10, diff --git a/apps/server/src/settingsSecrets.ts b/apps/server/src/settingsSecrets.ts index 22ea8ae882583..a38072d19813f 100644 --- a/apps/server/src/settingsSecrets.ts +++ b/apps/server/src/settingsSecrets.ts @@ -235,7 +235,7 @@ function mapSecretFieldGroups( ) as EasDeviceHostConfig, ); - // Its own prefix: an EAS and a Simlock host may share an id. + // Its own prefix: an Expo and a Simlock host may share an id. const simlockDeviceHosts = settings.simlockDeviceHosts.map( (host) => mapFields( diff --git a/apps/web/src/components/device/DeviceSetup.tsx b/apps/web/src/components/device/DeviceSetup.tsx index 283525ea6e164..f167d35192b92 100644 --- a/apps/web/src/components/device/DeviceSetup.tsx +++ b/apps/web/src/components/device/DeviceSetup.tsx @@ -138,7 +138,7 @@ export function platformSetupStatus(state: DeviceServiceState, platform: DeviceP ready: true, message: remoteHost?.kind === "eas" - ? `${remoteHost.label} starts ${platform === "ios" ? "iOS Simulators" : "Android emulators"} in the cloud with EAS Simulator.` + ? `${remoteHost.label} starts ${platform === "ios" ? "iOS Simulators" : "Android emulators"} in the cloud with Expo Simulators.` : platform === "ios" ? `Xcode and iOS Simulator are available${location}.` : `The Android SDK and Emulator are available${location}.`, diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsx index 21f51520ba3a3..d9206535017b9 100644 --- a/apps/web/src/components/device/DeviceWorkspace.tsx +++ b/apps/web/src/components/device/DeviceWorkspace.tsx @@ -33,7 +33,7 @@ export function DeviceWorkspace(props: { // A capture always finishes, even if the panel hides or closes meanwhile; the user asked for it. const capturing = useRef(false); const access = useDeviceHubAccess(props.environmentId, props.device.hostId); - // Settings and tools run commands on the device's own machine, which EAS and Simlock do not expose. + // Settings and tools run commands on the device's own machine, which Expo and Simlock do not expose. const runsHostCommands = props.hostKind === "local" || props.hostKind === "ssh"; const controls = useDeviceControls({ ...props, diff --git a/apps/web/src/components/settings/DeviceSourcesSettings.tsx b/apps/web/src/components/settings/DeviceSourcesSettings.tsx index 9d4e07b0fb0f4..2b8ce2ae0ff63 100644 --- a/apps/web/src/components/settings/DeviceSourcesSettings.tsx +++ b/apps/web/src/components/settings/DeviceSourcesSettings.tsx @@ -84,7 +84,7 @@ interface SourceRow { readonly description: ReactNode; readonly environments: ReadonlyArray; /** - * One machine or account every environment reaches the same way (an SSH host, EAS, a Simlock + * One machine or account every environment reaches the same way (an SSH host, Expo, a Simlock * pool), so its platforms are the same for all of them. Local simulators differ per machine. */ readonly shared: boolean; @@ -262,7 +262,7 @@ export function DeviceSourcesSettings(props: { ), }, })), - remove ? "EAS host not removed everywhere" : "EAS host not saved everywhere", + remove ? "Expo host not removed everywhere" : "Expo host not saved everywhere", ); if (saved) setEditing(null); }; @@ -460,7 +460,7 @@ export function DeviceSourcesSettings(props: { key: `eas:${host.id}`, shared: true, title: host.label, - kind: "EAS", + kind: "Expo", description: easSessionLimits(host), environments: active.map((member) => { const added = (member.settings?.easDeviceHosts ?? []).some( @@ -551,7 +551,7 @@ export function DeviceSourcesSettings(props: { }) } > - EAS Simulator + Expo Simulators ) : null} {props.supportsSimlock && simlockEnabled ? ( diff --git a/apps/web/src/components/settings/EasDeviceHostEditor.tsx b/apps/web/src/components/settings/EasDeviceHostEditor.tsx index e11d9dfa748aa..3207887133e60 100644 --- a/apps/web/src/components/settings/EasDeviceHostEditor.tsx +++ b/apps/web/src/components/settings/EasDeviceHostEditor.tsx @@ -174,7 +174,7 @@ export function EasDeviceHostEditor(props: { }} > - {props.isNew ? "Add EAS host" : "Edit EAS host"} + {props.isNew ? "Add Expo host" : "Edit Expo host"} The environment's server signs in to Expo and starts the sessions. Without a token here it uses EXPO_TOKEN, then its eas login. @@ -277,7 +277,7 @@ export function EasDeviceHostEditor(props: {
- EAS project + Expo project