diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 57251254f68fe..d59dfe721e8e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -591,7 +591,7 @@ jobs: name: Mobile Native Static Analysis needs: changes if: ${{ !cancelled() && needs.changes.outputs.mobile_native != 'false' }} - runs-on: blacksmith-6vcpu-macos-26 + runs-on: blacksmith-6vcpu-macos-27 timeout-minutes: 10 steps: - name: Checkout diff --git a/.github/workflows/desktop-macos-preview-publish.yml b/.github/workflows/desktop-macos-preview-publish.yml index 2fdfee717fc75..38eae71622ca5 100644 --- a/.github/workflows/desktop-macos-preview-publish.yml +++ b/.github/workflows/desktop-macos-preview-publish.yml @@ -316,6 +316,7 @@ jobs: rust_target: aarch64-apple-darwin resource_key: darwin-arm64 cli_archive: false + untrusted_bundle: true # Release assets download without a GitHub account, unlike workflow # artifacts. All preview DMGs live on one rolling prerelease tagged diff --git a/.github/workflows/mobile-dev-client.yml b/.github/workflows/mobile-dev-client.yml index d30e20d78775c..eb7bb0882616e 100644 --- a/.github/workflows/mobile-dev-client.yml +++ b/.github/workflows/mobile-dev-client.yml @@ -219,7 +219,7 @@ jobs: ios: name: iOS simulator if: github.repository == 'pingdotgg/t3code' && (github.event_name != 'workflow_dispatch' || inputs.platform == 'ios') - runs-on: blacksmith-12vcpu-macos-26 + runs-on: blacksmith-12vcpu-macos-27 timeout-minutes: 60 concurrency: group: mobile-dev-client-ios-${{ github.event_name == 'pull_request' && github.event.pull_request.number || inputs.fingerprint || github.sha }} diff --git a/.github/workflows/mobile-eas-production.yml b/.github/workflows/mobile-eas-production.yml index 497df5fe922aa..f15b72d10ee0d 100644 --- a/.github/workflows/mobile-eas-production.yml +++ b/.github/workflows/mobile-eas-production.yml @@ -680,8 +680,8 @@ jobs: echo ":rocket: android: submitted and recorded \`$BUILD_TAG\`" >> "$GITHUB_STEP_SUMMARY" # Off unless the MOBILE_IOS_LOCAL_BUILDS repository variable is `true`; the - # production job only sets ios_build then. Store binaries need the final - # Xcode 27.1; MOBILE_IOS_ALLOW_XCODE_RC=true accepts the release candidate. + # production job only sets ios_build then. Xcode 27.1 matches the EAS build + # image in eas.json. # No sticky disk: it mounts ext4 and only works on Linux runners. ios: name: iOS store build @@ -701,7 +701,6 @@ jobs: EXPO_TOKEN: ${{ secrets.EXPO_PRODUCTION_TOKEN }} PROFILE: ${{ needs.production.outputs.ios_profile }} BUILD_TAG: mobile-ios-build/${{ needs.production.outputs.ios_profile }}/${{ needs.production.outputs.ios_version }}/${{ needs.production.outputs.ios_fingerprint }} - ALLOW_XCODE_RC: ${{ vars.MOBILE_IOS_ALLOW_XCODE_RC == 'true' }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -739,12 +738,9 @@ jobs: if: steps.record.outputs.built != 'true' run: | xcode=/Applications/Xcode_27.1.app - if [ ! -d "$xcode" ] && [ "$ALLOW_XCODE_RC" = "true" ]; then - xcode=/Applications/Xcode_27.1_Release_Candidate.app - fi if [ ! -d "$xcode" ]; then ls -d /Applications/Xcode*.app - echo "::error::Xcode 27.1 (final) is not on this runner. Set the MOBILE_IOS_ALLOW_XCODE_RC repository variable to true to build store binaries with the release candidate." + echo "::error::Xcode 27.1 is not on this runner." exit 1 fi sudo xcode-select -s "$xcode/Contents/Developer" diff --git a/.github/workflows/mobile-showcase-screenshots.yml b/.github/workflows/mobile-showcase-screenshots.yml index 842fdab7449d0..33a5faaa379c8 100644 --- a/.github/workflows/mobile-showcase-screenshots.yml +++ b/.github/workflows/mobile-showcase-screenshots.yml @@ -45,7 +45,7 @@ jobs: ios: name: iPhone, iPhone Duo, and iPad 13 if: inputs.platform == 'all' || inputs.platform == 'ios' - runs-on: blacksmith-12vcpu-macos-26 + runs-on: blacksmith-12vcpu-macos-27 # Capturing every palette multiplies the device matrix by six, and only the # one native build is shared between them. timeout-minutes: ${{ inputs.theme == 'all' && 300 || 60 }} diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 48f410f0c920a..4252cb46e7a05 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -70,6 +70,12 @@ on: required: false default: false type: boolean + # Whether the JS bundle came from a pull request. This job holds the + # signing secrets, so packaging then skips every step that runs the bundle. + untrusted_bundle: + required: false + default: false + type: boolean # A runner of the target's own platform and architecture, for a `runner` # that cannot execute the target. The build job skips everything that # runs the packaged binaries, and a second job runs it there. @@ -134,6 +140,14 @@ jobs: T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: ${{ inputs.clerk_cli_oauth_client_id }} T3CODE_RELAY_URL: ${{ inputs.relay_url }} steps: + # The launch check and the CLI archive smoke test both run the bundle. + - name: Reject running an untrusted bundle + if: inputs.untrusted_bundle && (inputs.launch_check || inputs.cli_archive) + shell: bash + run: | + echo "::error::untrusted_bundle cannot be combined with launch_check or cli_archive, which run the bundle." + exit 1 + # This repository is public, so Git needs no credentials. checkout's # credential cleanup runs submodule foreach even with submodules disabled, # which fails on the orphaned gitlinks in our vendored .repos tree. @@ -573,6 +587,7 @@ jobs: pnpm_config_prefer_offline: "true" T3CODE_DESKTOP_REUSE_RESOURCE_MONITOR: true T3CODE_DESKTOP_REUSE_LINUX_CAPTURE_HELPERS: ${{ steps.capture_helper_cache.outputs.cache-hit == 'true' }} + T3CODE_DESKTOP_UNTRUSTED_BUNDLE: ${{ inputs.untrusted_bundle }} CSC_LINK: ${{ secrets.CSC_LINK }} CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }} APPLE_API_KEY: ${{ secrets.APPLE_API_KEY }} diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index d43e7a8388b83..3e8b4967dfde5 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -56,7 +56,7 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { `echo $$ >'${root}/mounter.pid'`, canMount ? `echo '${image}'` : 'echo "Cannot mount AppImage"; exit 1', // Like the FUSE runtime, any of these unmounts. fd 3 reports to the test when it is open. - `trap 'echo unmounted >&3 2>/dev/null; touch "${root}/unmounted"; exit 0' TERM HUP INT`, + "trap 'echo unmounted >&3 2>/dev/null; exit 0' TERM HUP INT", "trap 'echo mounted >&3 2>/dev/null' WINCH", "while :; do sleep 0.05; done", "", diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts index e9c8336feaf4b..8e8a2812ab245 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts @@ -204,6 +204,35 @@ describe("DesktopLinuxUrlHandler", () => { assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png"); }); + it.each([ + { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: true }, + { + from: "T3-Code-0.1.9-nightly.20261110.4449-arm64.AppImage", + to: "T3-Code-Nightly-arm64.AppImage", + restored: true, + }, + { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-0.1.9-x86_64.AppImage", restored: false }, + { from: "t3code.AppImage", to: "T3-Code-x86_64.AppImage", restored: false }, + { from: "T3-Code-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false }, + { from: "../T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false }, + ])("finds the launch path an update from $from to $to removed", ({ from, to, restored }) => { + for (const dir of ["/home/alice/Applications", '/home/al ice/My "100%" $Apps\\x']) { + const previous = dir + "/" + from; + const previousEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({ + displayName: "T3 Code (Beta)", + execTarget: previous, + scheme: "t3code", + }); + assert.equal( + DesktopLinuxUrlHandler.replacedVersionedAppImagePath({ + previousEntry, + appImagePath: dir + "/" + to, + }), + restored ? previous : null, + ); + } + }); + it.effect( "writes the handler entry, refreshes the MIME cache, and claims the scheme default", () => { diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts index 64535c5b3ac11..35fd46dd7ae50 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts @@ -96,6 +96,38 @@ export function renderUrlHandlerDesktopEntry(input: { ].join("\n"); } +function parseUrlHandlerExecTarget(entry: string): string | null { + const exec = /^Exec=(.*) %U$/mu.exec(entry)?.[1]; + if (exec === undefined) return null; + const unescaped = exec.replace(/\\([\\nrt])/gu, (_, char: string) => + char === "n" ? "\n" : char === "r" ? "\r" : char === "t" ? "\t" : char, + ); + const quoted = /^"(.*)"$/su.exec(unescaped)?.[1]; + return ( + quoted === undefined ? unescaped : quoted.replace(/\\([\\`$"])/gu, (_, char: string) => char) + ).replaceAll("%%", "%"); +} + +const APPIMAGE_NAME_VERSION = /\d+\.\d+\.\d+/u; + +// An updater from before version-free AppImage names deletes its own file and installs the update +// beside it under the new name. The previous launch's entry still names the path launchers use. +export function replacedVersionedAppImagePath(input: { + readonly previousEntry: string; + readonly appImagePath: string; +}): string | null { + const previous = parseUrlHandlerExecTarget(input.previousEntry); + if (previous === null) return null; + const previousName = previous.slice(previous.lastIndexOf("/") + 1); + const currentName = input.appImagePath.slice(input.appImagePath.lastIndexOf("/") + 1); + return previous.startsWith("/") && + previous.slice(0, -previousName.length) === input.appImagePath.slice(0, -currentName.length) && + APPIMAGE_NAME_VERSION.test(previousName) && + !APPIMAGE_NAME_VERSION.test(currentName) + ? previous + : null; +} + // Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive. const LINUX_THEME_ICON_SIZE = "256x256"; diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index 34607e08b844f..45887a928abb7 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -16,6 +16,7 @@ const { copyFileSyncMock, execFileSyncMock, readFileSyncMock, + symlinkSyncMock, } = vi.hoisted(() => ({ appendSwitchMock: vi.fn(), getSwitchValueMock: vi.fn(), @@ -27,6 +28,7 @@ const { copyFileSyncMock: vi.fn(), execFileSyncMock: vi.fn(), readFileSyncMock: vi.fn(), + symlinkSyncMock: vi.fn(), })); vi.mock("electron", () => ({ @@ -51,6 +53,7 @@ vi.mock("node:fs", () => ({ mkdirSync: mkdirSyncMock, writeFileSync: writeFileSyncMock, copyFileSync: copyFileSyncMock, + symlinkSync: symlinkSyncMock, })); vi.mock("node:child_process", () => ({ @@ -72,6 +75,7 @@ describe("DesktopPreReadyPlatform", () => { copyFileSyncMock.mockReset(); execFileSyncMock.mockReset(); readFileSyncMock.mockReset().mockReturnValue("{}"); + symlinkSyncMock.mockReset(); }); it.effect("persists Linux scaling synchronously across relaunches and settings rewrites", () => { @@ -181,6 +185,47 @@ describe("DesktopPreReadyPlatform", () => { ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); }); + it.effect.each([ + { relaunchedByUpdater: "true", restored: true }, + { relaunchedByUpdater: "", restored: false }, + ])( + "restores the versioned AppImage path an update removed (updater relaunch: $relaunchedByUpdater)", + ({ relaunchedByUpdater, restored }) => { + vi.stubEnv("VITE_DEV_SERVER_URL", ""); + getSwitchValueMock.mockReturnValue(""); + const entryPath = "/xdg/applications/com.t3tools.T3Code.desktop"; + const files = new Map([[entryPath, "Exec=/Applications/T3-Code-0.1.8-x86_64.AppImage %U\n"]]); + readFileSyncMock.mockImplementation((path: string) => files.get(path) ?? "{}"); + writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => { + files.set(path, String(contents)); + }); + + return Effect.scoped( + Effect.gen(function* () { + yield* Layer.build( + DesktopPreReadyPlatform.layer.pipe( + Layer.provide(Layer.succeed(HostProcess.Platform, "linux")), + Layer.provide( + DesktopConfig.layerTest({ + XDG_DATA_HOME: "/xdg", + APPIMAGE: "/Applications/T3-Code-x86_64.AppImage", + APPIMAGE_SILENT_INSTALL: relaunchedByUpdater, + }), + ), + ), + ); + assert.deepEqual( + symlinkSyncMock.mock.calls, + restored + ? [["T3-Code-x86_64.AppImage", "/Applications/T3-Code-0.1.8-x86_64.AppImage"]] + : [], + ); + assert.include(files.get(entryPath), "Exec=/Applications/T3-Code-x86_64.AppImage %U"); + }), + ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); + }, + ); + it.effect("points the early portal entry at a configured distribution launcher", () => { vi.stubEnv("VITE_DEV_SERVER_URL", ""); getSwitchValueMock.mockReturnValue(""); diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index df8059133fc20..8ac4654636ab6 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -14,7 +14,10 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts"; import { trimmedString } from "./DesktopConfig.ts"; import { resolveDesktopAppBranding } from "./DesktopEnvironment.ts"; -import { renderUrlHandlerDesktopEntry } from "./DesktopLinuxUrlHandler.ts"; +import { + renderUrlHandlerDesktopEntry, + replacedVersionedAppImagePath, +} from "./DesktopLinuxUrlHandler.ts"; import * as ElectronProtocol from "../electron/ElectronProtocol.ts"; export interface DesktopPreReadyCommandLineReader { @@ -56,6 +59,8 @@ const LinuxDesktopEntryConfig = Config.all({ xdgDataHome: trimmedString("XDG_DATA_HOME"), launcherPath: trimmedString("T3CODE_DESKTOP_LAUNCHER_PATH"), appImagePath: trimmedString("APPIMAGE"), + // electron-updater sets this on the AppImage it relaunches after installing an update. + relaunchedByUpdater: trimmedString("APPIMAGE_SILENT_INSTALL"), }); /** @public */ @@ -116,8 +121,26 @@ export const make = Effect.gen(function* () { ); } catch {} } + const desktopEntryPath = NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName); + const { appImagePath } = linuxDesktopEntryConfig; + if ( + Option.isSome(appImagePath) && + Option.isNone(linuxDesktopEntryConfig.launcherPath) && + Option.contains(linuxDesktopEntryConfig.relaunchedByUpdater, "true") + ) { + try { + const replacedPath = replacedVersionedAppImagePath({ + previousEntry: NodeFS.readFileSync(desktopEntryPath, "utf8"), + appImagePath: appImagePath.value, + }); + // Relative, so the pair survives a moved folder; symlink never overwrites a file. + if (replacedPath !== null) { + NodeFS.symlinkSync(NodePath.posix.basename(appImagePath.value), replacedPath); + } + } catch {} + } NodeFS.writeFileSync( - NodePath.posix.join(applicationsDir, linux.linuxDesktopEntryName), + desktopEntryPath, renderUrlHandlerDesktopEntry({ displayName: resolveDesktopAppBranding({ isDevelopment: linux.isDevelopment, diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 3a107f211b997..926bdcfd27762 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -89,6 +89,7 @@ export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webvie export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate"; export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back"; export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward"; +export const PREVIEW_STOP_LOADING_CHANNEL = "desktop:preview-stop-loading"; export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh"; export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in"; export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out"; diff --git a/apps/desktop/src/ipc/methods/preview.ts b/apps/desktop/src/ipc/methods/preview.ts index ea291b66b3149..cc810fee072ad 100644 --- a/apps/desktop/src/ipc/methods/preview.ts +++ b/apps/desktop/src/ipc/methods/preview.ts @@ -168,6 +168,11 @@ const refresh = tabMethod( "desktop.ipc.preview.refresh", (manager, tabId) => manager.refresh(tabId), ); +const stopLoading = tabMethod( + IpcChannels.PREVIEW_STOP_LOADING_CHANNEL, + "desktop.ipc.preview.stopLoading", + (manager, tabId) => manager.stopLoading(tabId), +); const zoomIn = tabMethod( IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, "desktop.ipc.preview.zoomIn", @@ -472,6 +477,7 @@ export const methods = [ goBack, goForward, refresh, + stopLoading, zoomIn, zoomOut, resetZoom, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 8720e557de84c..d7a31216e16a9 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -12,7 +12,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; // @effect-diagnostics-next-line nodeBuiltinImport:off - Version output must flush before Electron exits, without acquiring the runtime. import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Electron from "electron"; @@ -123,6 +125,15 @@ const layerDesktopSshEnvironment = Layer.unwrap( nodeEngineRange: serverPackageJson.engines.node, }), ), + resolveLauncherId: yield* Effect.cached( + DesktopSshEnvironment.readOrCreateLauncherId( + environment.path.join(environment.stateDir, "ssh-launcher-id"), + ).pipe( + Effect.provide( + yield* Effect.context(), + ), + ), + ), }); }), ); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 85ce1b0068061..bdbcc2e9c9dc0 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -390,6 +390,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }), goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }), refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }), + stopLoading: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_STOP_LOADING_CHANNEL, { tabId }), zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }), zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }), resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }), diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index 393e4cccccf9c..d6f25d66aa810 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -1298,6 +1298,41 @@ describe("DesktopBrowserHost", () => { }), ); + it.effect("stops crediting the agent once a person acts through a viewer", () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.make; + const debuggee = makeDebuggee(); + host.attach(key, debuggee.tab); + const replies = yield* watchReplies(host); + const raw = (message: Record) => + host.handleCommandLine(encodeJson({ type: "cdp", ...key, message: encodeJson(message) })); + const viewer = (id: number, method: string, type: string) => + raw({ id, method, params: { type }, sessionId: "t3-preview-page-1" }); + const led = () => host.agentLedPage(debuggee.tab.webContents); + + yield* command(host, 1, "DOM.getDocument"); + expect(led()).toBe(false); + yield* raw({ id: 2, method: "Target.attachToTarget", params: { targetId: "GUEST" } }); + expect(yield* Queue.take(replies)).toBe(2); + yield* raw({ id: 3, method: "Page.startScreencast", sessionId: "t3-preview-page-1" }); + + for (const [method, type] of [ + ["Input.dispatchKeyEvent", "rawKeyDown"], + ["Input.dispatchMouseEvent", "mousePressed"], + ["Input.dispatchTouchEvent", "touchStart"], + ] as const) { + yield* command(host, 4, "Runtime.evaluate"); + expect(led()).toBe(true); + // The viewer's pointer only passes over the page the agent drives. + yield* viewer(5, "Input.dispatchMouseEvent", "mouseMoved"); + yield* viewer(6, "Input.dispatchMouseEvent", "mouseWheel"); + expect(led()).toBe(true); + yield* viewer(7, method, type); + expect(led()).toBe(false); + } + }).pipe(Effect.scoped), + ); + it.effect("detaches only the tab whose CDP event is too large to relay", () => Effect.gen(function* () { const host = yield* DesktopBrowserHost.make; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.ts b/apps/desktop/src/preview/DesktopBrowserHost.ts index e5f43634d204a..296be2fa6709f 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.ts @@ -26,7 +26,9 @@ const AGENT_INPUT_COMMAND = /"method":"(?:Input\.|Page\.navigate"|Runtime\.(?:evaluate|callFunctionOn)")/; /** The same commands as above, by method, for the relay's sends. */ const AGENT_INPUT_METHOD = /^(?:Input\.|Page\.navigate$|Runtime\.(?:evaluate|callFunctionOn)$)/; -const AGENT_DOWNLOAD_WINDOW_MS = 5_000; +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"; /** 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"; @@ -60,6 +62,8 @@ interface AttachedTab { downloadDirectory: string | null; pendingDownloadGuid: string | null; agentInputAt: number; + /** When the agent last drove the page with no person's input through a viewer since. */ + agentLedAt: number; focusEmulated: boolean; focusChange: Promise | null; focusUses: number; @@ -98,6 +102,8 @@ export class DesktopBrowserHost extends Context.Service< readonly loadFailed: (key: DesktopBrowserTabKey, failure: PreviewAutomationLoadError) => void; readonly setShown: (key: DesktopBrowserTabKey, shown: 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; readonly placeDownload: (source: Electron.WebContents, item: Electron.DownloadItem) => boolean; readonly pointers: Stream.Stream<{ readonly key: DesktopBrowserTabKey; @@ -351,11 +357,13 @@ export const make = Effect.gen(function* () { if (tab.screencasts.size > 0) return Promise.resolve({}); } // A person's input through a viewer, or Playwright's own housekeeping, is not the agent's. - if ( - AGENT_INPUT_METHOD.test(method) && - (owner === undefined || !streamingOwners.has(owner)) - ) { - tab.agentUsed = true; + if (AGENT_INPUT_METHOD.test(method)) { + if (owner === undefined || !streamingOwners.has(owner)) { + tab.agentUsed = true; + tab.agentLedAt = performance.now(); + } else if (method.startsWith("Input.") && !POINTER_TRAVEL.has(params["type"])) { + tab.agentLedAt = Number.NEGATIVE_INFINITY; + } } // Waits for focus emulation; insertText and other non-CDP input would not queue behind it. const forward = (current?: () => boolean) => { @@ -490,6 +498,7 @@ export const make = Effect.gen(function* () { downloadDirectory: null, pendingDownloadGuid: null, agentInputAt: Number.NEGATIVE_INFINITY, + agentLedAt: Number.NEGATIVE_INFINITY, focusEmulated: false, focusChange: null, focusUses: 0, @@ -604,7 +613,12 @@ export const make = Effect.gen(function* () { const humanStartedDownload = (source: Electron.WebContents) => { const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source); - return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_DOWNLOAD_WINDOW_MS; + return tab !== undefined && performance.now() - tab.agentInputAt > AGENT_INPUT_WINDOW_MS; + }; + + const agentLedPage = (source: Electron.WebContents) => { + const tab = [...tabs.values()].find((candidate) => candidate.debuggee.webContents === source); + return tab !== undefined && performance.now() - tab.agentLedAt <= AGENT_INPUT_WINDOW_MS; }; const announceAll = Effect.suspend(() => { @@ -647,6 +661,7 @@ export const make = Effect.gen(function* () { setShown, placeDownload, humanStartedDownload, + agentLedPage, }); }); diff --git a/apps/desktop/src/preview/GuestInput.test.ts b/apps/desktop/src/preview/GuestInput.test.ts index a0889940a6682..48191ce2c4b98 100644 --- a/apps/desktop/src/preview/GuestInput.test.ts +++ b/apps/desktop/src/preview/GuestInput.test.ts @@ -44,6 +44,30 @@ describe("preview guest input", () => { expect(guest.sendCommand).not.toHaveBeenCalledWith("Input.insertText", expect.anything()); }); + it("stops the guest navigation without stopping its embedder", async () => { + let guestLoading = true; + let hostLoading = true; + const guest = { + stop: () => { + guestLoading = false; + }, + }; + const debuggee = { + sendCommand: async () => { + hostLoading = false; + return {}; + }, + }; + await sendPageCommand( + guest as unknown as Electron.WebContents, + debuggee as unknown as Electron.Debugger, + "Page.stopLoading", + {}, + ); + expect(guestLoading).toBe(false); + expect(hostLoading).toBe(true); + }); + it.each([ { sessionId: undefined, diff --git a/apps/desktop/src/preview/GuestInput.ts b/apps/desktop/src/preview/GuestInput.ts index 2af13af8d7daa..4d794beea62bc 100644 --- a/apps/desktop/src/preview/GuestInput.ts +++ b/apps/desktop/src/preview/GuestInput.ts @@ -185,6 +185,10 @@ export const sendPageCommand = async ( else webContents.reload(); return {}; } + if (method === "Page.stopLoading") { + webContents.stop(); + return {}; + } if (!FOCUS_ROUTED_INPUT.has(method) || webContents.focusedFrame) { return debuggee.sendCommand(method, params); } diff --git a/apps/desktop/src/preview/GuestProtocol.ts b/apps/desktop/src/preview/GuestProtocol.ts index 0a9f4cb85c008..1d24079d1947f 100644 --- a/apps/desktop/src/preview/GuestProtocol.ts +++ b/apps/desktop/src/preview/GuestProtocol.ts @@ -5,7 +5,6 @@ export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured"; export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme"; export const ANNOTATION_SEND_ENABLED_CHANNEL = "preview:annotation-send-enabled"; export const HUMAN_INPUT_CHANNEL = "preview:human-input"; -export const MOUSE_NAVIGATE_CHANNEL = "preview:mouse-navigate"; // Sent to the hosting element (ipc-message). The web app mirrors this // literal in HostedBrowserWebview because it cannot import from the desktop app. export const POINTER_DOWN_HOST_CHANNEL = "preview:pointer-down"; @@ -15,6 +14,7 @@ export const RECORDING_POINTER_CHANNEL = "preview:recording-pointer"; export const RECORDING_KEY_CHANNEL = "preview:recording-key"; export const RECORDING_INPUT_CHANNEL = "preview:recording-input"; export const RECORDING_CONTROLLER_CHANNEL = "preview:recording-controller"; +export const THUMB_PRESS_CHANNEL = "preview:thumb-press"; export const PASSKEY_CREATE_CHANNEL = "preview:passkey-create"; export const PASSKEY_GET_CHANNEL = "preview:passkey-get"; export const PASSKEY_BRIDGE_ARGUMENT = "--t3code-preview-passkey-bridge"; diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index b344b1ac93b2b..e8ce5eaae3696 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -619,6 +619,7 @@ describe("PreviewManager", () => { setShown: () => {}, loadFailed: () => {}, humanStartedDownload: () => true, + agentLedPage: () => false, placeDownload: () => true, }), Layer.mock(PreviewPasskeys.PreviewPasskeys)({ @@ -745,6 +746,69 @@ describe("PreviewManager", () => { ), ); + effectIt.effect("keeps mouse back and forward buttons inside the preview tab", () => + withManager((manager) => + Effect.gen(function* () { + const preview = makeFaviconWebContents(); + const goBack = vi.fn(); + const goForward = vi.fn(); + const send = vi.fn(); + let canGoBack = false; + Object.assign(preview.webContents, { + navigationHistory: { + canGoBack: () => canGoBack, + canGoForward: () => true, + goBack, + goForward, + }, + getZoomFactor: () => 2, + send, + }); + fromId.mockReturnValue(preview.webContents); + yield* manager.createTab("tab_mouse_navigation"); + yield* manager.registerWebview("tab_mouse_navigation", 42); + + // Electron reports thumb buttons as "back"/"forward" for every frame of the guest, iframes included. + const beforeMouse = preview.listeners.get("before-mouse-event"); + expect(beforeMouse, "guest has no before-mouse-event listener").toBeDefined(); + const press = (type: "mouseDown" | "mouseUp", button: string) => { + const preventDefault = vi.fn(); + beforeMouse!({ preventDefault } as never, { type, button, x: 10, y: 10 } as never); + return preventDefault; + }; + + // At the start of tab history the press is still swallowed, or the host app goes back instead. + expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); + expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); + expect(goBack).not.toHaveBeenCalled(); + + canGoBack = true; + expect(press("mouseDown", "back")).toHaveBeenCalledOnce(); + expect(goBack).not.toHaveBeenCalled(); + expect(press("mouseUp", "back")).toHaveBeenCalledOnce(); + expect(goBack).toHaveBeenCalledOnce(); + expect(press("mouseDown", "forward")).toHaveBeenCalledOnce(); + expect(press("mouseUp", "forward")).toHaveBeenCalledOnce(); + expect(goForward).toHaveBeenCalledOnce(); + for (const button of ["left", "right"]) { + expect(press("mouseDown", button)).not.toHaveBeenCalled(); + expect(press("mouseUp", button)).not.toHaveBeenCalled(); + } + expect(goBack).toHaveBeenCalledOnce(); + expect(goForward).toHaveBeenCalledOnce(); + // The guest replays dropped presses for human input and recordings, in CSS px. + expect(send.mock.calls.filter(([channel]) => channel === "preview:thumb-press")).toEqual([ + ["preview:thumb-press", "down", 5, 5, 3], + ["preview:thumb-press", "up", 5, 5, 3], + ["preview:thumb-press", "down", 5, 5, 3], + ["preview:thumb-press", "up", 5, 5, 3], + ["preview:thumb-press", "down", 5, 5, 4], + ["preview:thumb-press", "up", 5, 5, 4], + ]); + }), + ), + ); + effectIt.effect("keeps editing and forwarded shortcuts in whichever tab holds focus", () => withManager((manager) => Effect.gen(function* () { @@ -2133,6 +2197,71 @@ describe("PreviewManager", () => { }).pipe(Effect.provide(managerLayer())), ); + effectIt.effect( + "opens a new-tab link in the background only when the agent's input led to it", + () => + Effect.gen(function* () { + const host = yield* DesktopBrowserHost.DesktopBrowserHost; + const serverTab = { threadId: "thread-1", tabId: "server-tab-1" }; + const contents = Object.assign( + makeTestPreviewWebContents(async () => { + throw new Error("unused"); + }, 42), + { + isDevToolsOpened: () => false, + getUserAgent: () => "Electron", + focusedFrame: null, + }, + ); + fromId.mockReturnValue(contents); + const manager = yield* PreviewManager.PreviewManager; + const openLinks = yield* Queue.unbounded(); + yield* manager.subscribeOpenLinks(({ background }) => + Queue.offer(openLinks, background).pipe(Effect.asVoid), + ); + const attached = yield* Deferred.make(); + yield* host.events.pipe( + Stream.runForEach((line) => + new TextDecoder().decode(line).includes('"type":"attached"') + ? Deferred.succeed(attached, undefined) + : Effect.void, + ), + Effect.forkScoped, + ); + yield* manager.createTab("tab_1", { serverTab }); + yield* manager.registerWebview("tab_1", 42); + yield* Deferred.await(attached); + const openWindow = vi.mocked(contents.setWindowOpenHandler).mock.calls[0]![0]; + const openBlankLink = Effect.suspend(() => { + openWindow({ + url: "https://example.com/next", + disposition: "foreground-tab", + } as Electron.HandlerDetails); + return Queue.take(openLinks); + }); + + expect(yield* openBlankLink).toBe(false); + + yield* host.handleCommandLine( + JSON.stringify({ + type: "cdp", + ...serverTab, + message: JSON.stringify({ + id: 1, + method: "Runtime.evaluate", + params: { expression: "document.querySelector('a').click()" }, + sessionId: "t3-preview-page", + }), + }), + ); + expect(yield* openBlankLink).toBe(true); + + // A person clicking in the guest itself gives it a focused frame. + Object.assign(contents, { focusedFrame: {} }); + expect(yield* openBlankLink).toBe(false); + }).pipe(Effect.provide(managerLayer()), Effect.scoped), + ); + effectIt.effect("reports early and subsequent load failures for the current guest", () => Effect.gen(function* () { const host = yield* DesktopBrowserHost.DesktopBrowserHost; diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 686248bf8892d..56957783405b1 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -81,13 +81,13 @@ import { CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, - MOUSE_NAVIGATE_CHANNEL, PAGE_UNHANDLED_SHORTCUT_CHANNEL, RECORDING_CURSOR_CHANNEL, RECORDING_INPUT_CHANNEL, RECORDING_CONTROLLER_CHANNEL, RECORDING_POINTER_CHANNEL, START_PICK_CHANNEL, + THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; @@ -1490,15 +1490,27 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const humanInput = (_event: unknown, rawSignal?: unknown): void => { runFork(handleHumanInput(rawSignal)); }; - const mouseNavigate = (_event: unknown, payload?: unknown): void => { - const direction = - typeof payload === "object" && payload !== null && "direction" in payload - ? (payload as { direction?: unknown }).direction - : undefined; - if (direction !== "back" && direction !== "forward") return; + // Chromium navigates the outermost WebContents (the host app) on thumb buttons, even from guest iframes. + const beforeMouse = (event: Electron.Event, mouse: Electron.MouseInputEvent): void => { + // Electron reports thumb buttons as "back" and "forward", which its typings omit. + const button: string | undefined = mouse.button; + if (button !== "back" && button !== "forward") return; + if (mouse.type !== "mouseDown" && mouse.type !== "mouseUp") return; + event.preventDefault(); + // The page never sees the press, so the guest replays it; these coordinates are DIPs, not CSS px. + const zoom = wc.getZoomFactor(); + const phase = mouse.type === "mouseDown" ? "down" : "up"; + wc.send( + THUMB_PRESS_CHANNEL, + phase, + mouse.x / zoom, + mouse.y / zoom, + button === "back" ? 3 : 4, + ); + if (phase !== "up") return; runFork( attempt({ operation: "mouseNavigate", tabId, webContentsId: wc.id }, () => { - if (direction === "back") { + if (button === "back") { if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack(); } else if (wc.navigationHistory.canGoForward()) { wc.navigationHistory.goForward(); @@ -1608,9 +1620,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.off("found-in-page", foundInPage as never); wc.off("did-create-window", windowCreated); wc.off("before-input-event", beforeInput); + wc.off("before-mouse-event", beforeMouse); wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.off(RECORDING_INPUT_CHANNEL, recordingInput); - wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate); wc.ipc.off(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys(); }).pipe(Effect.ignore), @@ -1631,7 +1643,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.on("found-in-page", foundInPage as never); wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput); wc.ipc.on(RECORDING_INPUT_CHANNEL, recordingInput); - wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate); wc.ipc.on(PAGE_UNHANDLED_SHORTCUT_CHANNEL, pageUnhandledShortcut); detachPasskeys = passkeys.attachGuest(wc); wc.setWindowOpenHandler((details) => { @@ -1645,7 +1656,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function emitOpenLink({ tabId, url: details.url, - background: details.disposition === "background-tab", + // A person's own click or key leaves the guest a focused frame; GuestInput hands + // focus back after the agent's press, so a foreground tab would take it again. + background: + details.disposition === "background-tab" || + (wc.focusedFrame === null && browserHost.agentLedPage(wc)), }), ); return { action: "deny" }; @@ -1659,6 +1674,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.on("did-create-window", windowCreated); wc.on("before-input-event", beforeInput); + wc.on("before-mouse-event", beforeMouse); }); yield* Ref.update(attachedRef, (attached) => replaceMap(attached, (copy) => { @@ -2148,6 +2164,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function if (wc.navigationHistory.canGoForward()) wc.navigationHistory.goForward(); }); const refresh = (tabId: string) => withWebContents("refresh", tabId, (wc) => wc.reload()); + const stopLoading = (tabId: string) => withWebContents("stopLoading", tabId, (wc) => wc.stop()); const hardReload = (tabId: string) => withWebContents("hardReload", tabId, (wc) => wc.reloadIgnoringCache()); const findInPage = ( @@ -3531,6 +3548,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function prepareWebview, reapplyZoom, refresh, + stopLoading, registerWebview, resetZoom: (tabId: string) => applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR), setZoomFactor: (tabId: string, zoomFactor: number) => @@ -3732,6 +3750,7 @@ export class PreviewManager extends Context.Service< readonly goBack: (tabId: string) => Effect.Effect; readonly goForward: (tabId: string) => Effect.Effect; readonly refresh: (tabId: string) => Effect.Effect; + readonly stopLoading: (tabId: string) => Effect.Effect; readonly zoomIn: (tabId: string) => Effect.Effect; readonly zoomOut: (tabId: string) => Effect.Effect; readonly resetZoom: (tabId: string) => Effect.Effect; @@ -3906,6 +3925,7 @@ export const make = Effect.gen(function* PreviewManagerMake() { goBack: operations.goBack, goForward: operations.goForward, refresh: operations.refresh, + stopLoading: operations.stopLoading, zoomIn: operations.zoomIn, zoomOut: operations.zoomOut, resetZoom: operations.resetZoom, diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index cbaf873e49332..42867b9d9cb44 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -39,7 +39,6 @@ import { CANCEL_PICK_CHANNEL, ELEMENT_PICKED_CHANNEL, HUMAN_INPUT_CHANNEL, - MOUSE_NAVIGATE_CHANNEL, POINTER_DOWN_HOST_CHANNEL, PAGE_UNHANDLED_SHORTCUT_CHANNEL, RECORDING_CURSOR_CHANNEL, @@ -48,6 +47,7 @@ import { RECORDING_INPUT_CHANNEL, RECORDING_CONTROLLER_CHANNEL, START_PICK_CHANNEL, + THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui"; const INPUT_LAYER_ATTRIBUTE = "data-t3code-annotation-input"; @@ -249,34 +249,28 @@ const isolateOverlayKey = (event: KeyboardEvent): void => { for (const type of ["keydown", "keypress", "keyup"] as const) window.addEventListener(type, isolateOverlayKey, true); -const MOUSE_BUTTON_BACK = 3; -const MOUSE_BUTTON_FORWARD = 4; - -const navigationDirectionForButton = (button: number): "back" | "forward" | null => { - if (button === MOUSE_BUTTON_BACK) return "back"; - if (button === MOUSE_BUTTON_FORWARD) return "forward"; - return null; -}; - -// Chromium routes thumb-button navigation to the focused WebContents; navigate this hovered guest explicitly. -const suppressNavigationButton = (event: MouseEvent): void => { - if (!event.isTrusted || navigationDirectionForButton(event.button) === null) return; - event.preventDefault(); - event.stopImmediatePropagation(); -}; - -const requestNavigationForButton = (event: MouseEvent): void => { - if (!event.isTrusted) return; - const direction = navigationDirectionForButton(event.button); - if (direction === null) return; - event.preventDefault(); - event.stopImmediatePropagation(); - ipcRenderer.send(MOUSE_NAVIGATE_CHANNEL, { direction }); -}; - -window.addEventListener("mousedown", suppressNavigationButton, true); -window.addEventListener("mouseup", requestNavigationForButton, true); -window.addEventListener("auxclick", suppressNavigationButton, true); +let replayedThumbPress: { readonly x: number; readonly y: number } | null = null; +ipcRenderer.on( + THUMB_PRESS_CHANNEL, + (_event, phase: unknown, x: unknown, y: unknown, button: unknown) => { + if (phase !== "down" && phase !== "up") return; + if (typeof x !== "number" || typeof y !== "number" || typeof button !== "number") return; + // Main reports presses inside a frame in that frame's coordinates. + const inFrame = document.querySelector("iframe:hover, frame:hover, object:hover, embed:hover"); + if (phase === "up") { + const pressed = replayedThumbPress; + replayedThumbPress = null; + // A replayed press is always released, at its own point if the release lands in a frame. + if (pressed) recordingCursor?.press(inFrame ? pressed : { x, y }, "up"); + return; + } + if (inFrame) return; + replayedThumbPress = { x, y }; + ipcRenderer.sendToHost(POINTER_DOWN_HOST_CHANNEL); + ipcRenderer.send(HUMAN_INPUT_CHANNEL, { kind: "pointer", x, y, button }); + recordingCursor?.press({ x, y }, "down"); + }, +); const nextId = createAnnotationIdSource(); diff --git a/apps/desktop/src/preview/RecordingCursor.ts b/apps/desktop/src/preview/RecordingCursor.ts index 29f1865de291f..ab74c361b68e0 100644 --- a/apps/desktop/src/preview/RecordingCursor.ts +++ b/apps/desktop/src/preview/RecordingCursor.ts @@ -156,13 +156,15 @@ export function installRecordingCursor( moveHuman(point); pointer(point, "move"); }; + const press = (point: { readonly x: number; readonly y: number }, phase: "down" | "up") => { + if (phase === "down") moveHuman(point); + pointer(point, phase); + }; const pointerDown = (event: PointerEvent) => { - if (event.pointerType === "touch") return; - moveHuman({ x: event.clientX, y: event.clientY }); - pointer({ x: event.clientX, y: event.clientY }, "down"); + if (event.pointerType !== "touch") press({ x: event.clientX, y: event.clientY }, "down"); }; const pointerUp = (event: PointerEvent) => { - if (event.pointerType !== "touch") pointer({ x: event.clientX, y: event.clientY }, "up"); + if (event.pointerType !== "touch") press({ x: event.clientX, y: event.clientY }, "up"); }; const keyDown = (event: KeyboardEvent) => { if (event.isComposing || event.repeat) return; @@ -196,6 +198,7 @@ export function installRecordingCursor( window.addEventListener("blur", hide); return { move, + press, keyPress, setController, setTheme, diff --git a/apps/desktop/src/settings/DesktopAppSettings.test.ts b/apps/desktop/src/settings/DesktopAppSettings.test.ts index 1d28ed1862385..04406f63c6b3d 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.test.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.test.ts @@ -240,6 +240,28 @@ describe("DesktopSettings", () => { ), ); + it.effect("keeps Local environment off when another value in the file is unreadable", () => + withSettings( + Effect.gen(function* () { + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const settings = yield* DesktopAppSettings.DesktopAppSettings; + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.writeFileString( + environment.desktopSettingsPath, + `{ "localEnvironmentEnabled": false, "serverExposureMode": "tailnet" }\n`, + ); + + assert.isFalse((yield* settings.load).localEnvironmentEnabled); + yield* settings.setMainWindowBounds({ x: 10, y: 20, width: 800, height: 600 }, false); + assert.include( + yield* fileSystem.readFileString(environment.desktopSettingsPath), + `"localEnvironmentEnabled":false`, + ); + }), + ), + ); + it.effect("rejects window bounds that do not satisfy the domain schema", () => withSettings( Effect.gen(function* () { diff --git a/apps/desktop/src/settings/DesktopAppSettings.ts b/apps/desktop/src/settings/DesktopAppSettings.ts index 1bb8a2521d881..e81da70660648 100644 --- a/apps/desktop/src/settings/DesktopAppSettings.ts +++ b/apps/desktop/src/settings/DesktopAppSettings.ts @@ -90,20 +90,25 @@ const DesktopWindowBoundsDocument = Schema.Struct({ height: Schema.Number, }); +// A value this build cannot read drops only its own key, so the rest of the file +// still loads and is written back instead of every setting resetting to defaults. +const optionalReadableKey = (schema: S) => + Schema.optionalKey(schema.pipe(Schema.catchDecoding(() => Effect.succeedNone))); + const DesktopSettingsDocument = Schema.Struct({ - localEnvironmentEnabled: Schema.optionalKey(Schema.Boolean), - linuxPasswordStore: Schema.optionalKey(Schema.Unknown), - mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)), - mainWindowMaximized: Schema.optionalKey(Schema.Boolean), - serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema), - tailscaleServeEnabled: Schema.optionalKey(Schema.Boolean), - tailscaleServePort: Schema.optionalKey(Schema.Number), - updateChannel: Schema.optionalKey(DesktopUpdateChannelSchema), - updateChannelConfiguredByUser: Schema.optionalKey(Schema.Boolean), - wslBackendEnabled: Schema.optionalKey(Schema.Boolean), - wslMode: Schema.optionalKey(Schema.Literals(["local", "wsl"])), - wslDistro: Schema.optionalKey(Schema.NullOr(Schema.String)), - wslOnly: Schema.optionalKey(Schema.Boolean), + localEnvironmentEnabled: optionalReadableKey(Schema.Boolean), + linuxPasswordStore: optionalReadableKey(Schema.Unknown), + mainWindowBounds: optionalReadableKey(Schema.NullOr(DesktopWindowBoundsDocument)), + mainWindowMaximized: optionalReadableKey(Schema.Boolean), + serverExposureMode: optionalReadableKey(DesktopServerExposureModeSchema), + tailscaleServeEnabled: optionalReadableKey(Schema.Boolean), + tailscaleServePort: optionalReadableKey(Schema.Number), + updateChannel: optionalReadableKey(DesktopUpdateChannelSchema), + updateChannelConfiguredByUser: optionalReadableKey(Schema.Boolean), + wslBackendEnabled: optionalReadableKey(Schema.Boolean), + wslMode: optionalReadableKey(Schema.Literals(["local", "wsl"])), + wslDistro: optionalReadableKey(Schema.NullOr(Schema.String)), + wslOnly: optionalReadableKey(Schema.Boolean), }); type DesktopSettingsDocument = typeof DesktopSettingsDocument.Type; diff --git a/apps/desktop/src/ssh/DesktopSshEnvironment.ts b/apps/desktop/src/ssh/DesktopSshEnvironment.ts index d47984e2bcb59..0693c16cc15fd 100644 --- a/apps/desktop/src/ssh/DesktopSshEnvironment.ts +++ b/apps/desktop/src/ssh/DesktopSshEnvironment.ts @@ -19,6 +19,7 @@ import { import * as SshTunnel from "@t3tools/ssh/tunnel"; import * as Context from "effect/Context"; import type * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -70,8 +71,30 @@ export class DesktopSshEnvironment extends Context.Service< export interface DesktopSshEnvironmentLayerOptions { readonly resolveCliRunner?: Effect.Effect; + readonly resolveLauncherId?: Effect.Effect; } +// Remote servers record this ID as their owner, so it has to outlive restarts, +// updates and edits to a saved connection. Without a stored one there is none. +export const readOrCreateLauncherId = Effect.fn("desktop.ssh.readOrCreateLauncherId")( + function* (filePath: string) { + const fileSystem = yield* FileSystem.FileSystem; + const random = yield* SecureRandom.SecureRandom; + // Any other read failure may hide a stored ID, which a new one would overwrite. + const stored = yield* fileSystem.readFileString(filePath).pipe( + Effect.catchIf( + (cause) => cause.reason._tag === "NotFound", + () => Effect.succeed(""), + ), + ); + if (/^[0-9a-f]{32}$/u.test(stored.trim())) return stored.trim(); + const launcherId = (yield* random.uuidV4()).replace(/-/g, ""); + yield* fileSystem.writeFileString(filePath, `${launcherId}\n`); + return launcherId; + }, + Effect.orElseSucceed(() => null), +); + function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) { return discoverSshHosts(input ?? {}); } @@ -164,10 +187,13 @@ export const make = Effect.gen(function* () { export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) => Layer.effect(DesktopSshEnvironment, make).pipe( Layer.provide( - SshTunnel.SshEnvironmentManager.layer( - options.resolveCliRunner === undefined + SshTunnel.SshEnvironmentManager.layer({ + ...(options.resolveCliRunner === undefined ? {} - : { resolveCliRunner: options.resolveCliRunner }, - ), + : { resolveCliRunner: options.resolveCliRunner }), + ...(options.resolveLauncherId === undefined + ? {} + : { resolveLauncherId: options.resolveLauncherId }), + }), ), ); diff --git a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift index 0f4e70b20cc3c..924fa4ddeb14a 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3ScrollEdgeBleedView.swift @@ -19,6 +19,7 @@ final class T3ScrollEdgeBleedView: ExpoView { /// React Native's clipping, saved while bleeding. React Native only rewrites it when the /// `overflow` style changes, so it stays off while bleeding. private var containerClipped: Bool? + private var indicatorObservations: [NSKeyValueObservation] = [] required init(appContext: AppContext? = nil) { super.init(appContext: appContext) @@ -136,12 +137,29 @@ final class T3ScrollEdgeBleedView: ExpoView { containerClipped = containerClipped ?? true container.layer.masksToBounds = false } + applyIndicatorInset() + // React Native rewrites every indicator inset when its `scrollIndicatorInsets` prop changes, + // which the keyboard-aware list animates while a reply streams; put the inset back at once. + if bleeding, indicatorObservations.isEmpty { + let keyPaths = [\UIScrollView.verticalScrollIndicatorInsets, \.scrollIndicatorInsets] + indicatorObservations = keyPaths.map { + scrollView.observe($0) { [weak self] _, _ in + MainActor.assumeIsolated { self?.applyIndicatorInset() } + } + } + } else if !bleeding { + indicatorObservations = [] + } + applied = bleeding + } + + private func applyIndicatorInset() { + guard let scrollView else { return } var indicators = scrollView.verticalScrollIndicatorInsets if indicators.right != bleed.right { indicators.right = bleed.right scrollView.verticalScrollIndicatorInsets = indicators } - applied = bleeding } private func detach() { diff --git a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift index d8f0b29ebce52..1ed02e6a16cbf 100644 --- a/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift +++ b/apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift @@ -285,7 +285,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte didSet { guard oldValue != fontSize else { return } inputField.font = UIFont.monospacedSystemFont(ofSize: max(fontSize, 13), weight: .regular) - resetSurface() + applyConfigInPlace() } } @@ -321,14 +321,14 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte didSet { guard oldValue != appearanceScheme else { return } appearance = TerminalAppearanceScheme(value: appearanceScheme) - resetSurface() + applyConfigInPlace() } } var themeConfig: String = "" { didSet { guard oldValue != themeConfig else { return } - resetSurface() + applyConfigInPlace() } } @@ -663,7 +663,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte surfaceCreationFailed = true return } - loadThemeConfig(into: config) + // Creation proceeds without the file, as before; font_size is also set on the surface config. + _ = loadThemeConfig(into: config) ghostty_config_finalize(config) defer { ghostty_config_free(config) } @@ -710,6 +711,27 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte setNeedsLayout() } + // Font and theme change in place: a new surface would replay output and re-answer its queries. + private func applyConfigInPlace() { + guard let app, let surface else { + resetSurface() + return + } + guard let config = ghostty_config_new() else { return } + defer { ghostty_config_free(config) } + let loaded = loadThemeConfig(into: config) + ghostty_config_finalize(config) + ghostty_app_set_color_scheme(app, appearance.ghosttyColorScheme) + ghostty_surface_set_color_scheme(surface, appearance.ghosttyColorScheme) + tickApp() + // Without the file, the config lacks font-size and would reset the surface to defaults. + if loaded { + ghostty_surface_update_config(surface, config) + } + resizeSurface() + setNeedsLayout() + } + private func destroySurface() { // Unblock the io thread before ghostty_surface_free joins it. tickApp() @@ -933,16 +955,16 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate, UIEditMenuInte terminalViewport.backgroundColor = backgroundColorValue } - private func loadThemeConfig(into config: ghostty_config_t) { - guard let path = writeThemeConfigFile() else { return } + private func loadThemeConfig(into config: ghostty_config_t) -> Bool { + guard let path = writeThemeConfigFile() else { return false } path.withCString { cString in ghostty_config_load_file(config, cString) } + return true } private func writeThemeConfigFile() -> String? { - guard !themeConfig.isEmpty else { return nil } - let configContents = themeConfig + let configContents = "\(themeConfig)\nfont-size = \(String(format: "%g", Double(fontSize)))\n" let url = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent("t3-terminal-theme-\(appearance.rawValue).ghostty") diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx index b56472b4d052d..89f225dc52ff3 100644 --- a/apps/mobile/src/App.tsx +++ b/apps/mobile/src/App.tsx @@ -83,7 +83,10 @@ import { splashCanHide, useLaunchSplashHomeRowsPending, } from "./features/home/home-launch-splash"; -import { restoreSettingsLinkState } from "./features/settings/settings-navigation"; +import { + restoreSettingsLinkState, + settingsLinkAction, +} from "./features/settings/settings-navigation"; import { hydrateWorkspaceSelections, launchWorkspaceURL, @@ -144,14 +147,16 @@ const appLinking = { getActionFromState: ( state: Parameters[0], options: Parameters[1], - ): ReturnType => - // Our router handles the selection; React Navigation's type only lists its own actions. - (workspaceDetailLinkAction(state) as ReturnType) ?? - pairingFormLinkAction( - state, - rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined, - ) ?? - getActionFromState(state, options), + ): ReturnType => { + const current = rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined; + return ( + // Our router handles the selection; React Navigation's type only lists its own actions. + (workspaceDetailLinkAction(state) as ReturnType) ?? + pairingFormLinkAction(state, current) ?? + settingsLinkAction(state, current) ?? + getActionFromState(state, options) + ); + }, getStateFromPath: getAppStateFromPath, }; diff --git a/apps/mobile/src/components/ui/AppBar.tsx b/apps/mobile/src/components/ui/AppBar.tsx index 7690b135f9e11..b691faa300dae 100644 --- a/apps/mobile/src/components/ui/AppBar.tsx +++ b/apps/mobile/src/components/ui/AppBar.tsx @@ -1,8 +1,8 @@ import { Toolbar } from "./Toolbar"; import { AppActivityIndicator } from "./AppActivityIndicator"; import type { HeaderBarButtonMailSearchToolbarItem, SearchBarCommands } from "react-native-screens"; -import { NavigationContext } from "@react-navigation/native"; -import { use, useId, useLayoutEffect, useRef } from "react"; +import { NavigationContext, NavigationRouteContext } from "@react-navigation/native"; +import { use, useId, useLayoutEffect, useRef, useSyncExternalStore } from "react"; import { View } from "react-native"; import { createNativeHeaderMenu } from "./nativeHeaderMenu.ios"; import { ScreenHeaderButton } from "./ScreenHeaderButton"; @@ -63,6 +63,17 @@ export function AppBar(props: AppBarProps) { ? { ...props.backInSplitView, onPress: splitBackPress } : null; const navigation = use(NavigationContext); + const route = use(NavigationRouteContext); + // A thread opened from another thread sits on it, not beside the list, so it keeps Back. + const threadBelow = useSyncExternalStore( + (onChange) => navigation?.addListener("state", onChange) ?? (() => {}), + () => { + const routes = navigation?.getState()?.routes; + const index = routes?.findIndex((candidate) => candidate.key === route?.key) ?? -1; + return route?.name === "Thread" && index > 0 && routes?.[index - 1]?.name === "Thread"; + }, + ); + const listBeside = layout.usesSplitView && props.onBackToList !== undefined && !threadBelow; const rootBack = !layout.usesSplitView && props.onBackToList && navigation?.canGoBack() === false ? props.onBackToList @@ -113,7 +124,7 @@ export function AppBar(props: AppBarProps) { headerBackVisible: props.onClose === undefined && splitBack === null && - !(layout.usesSplitView && props.onBackToList) && + !listBeside && !(props.guardBack && props.onBack), ...(props.guardBack ? { gestureEnabled: false } : undefined), title: props.title, diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx index 0c40fc4e088b4..b962d716b992a 100644 --- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx @@ -63,6 +63,7 @@ function DocumentWebPreview(props: { readonly uri: string }) { originWhitelist={["*"]} allowsBackForwardNavigationGestures allowsFullscreenVideo + allowsInlineMediaPlayback setSupportMultipleWindows={false} onShouldStartLoadWithRequest={(request) => { if (request.isTopFrame !== false && isPdfPreviewUri(request.url)) { diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx index a464f0db63f01..3bca0ba8be1a9 100644 --- a/apps/mobile/src/features/home/HomeRouteScreen.tsx +++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx @@ -10,10 +10,7 @@ import { useMemo, useState } from "react"; import { Platform } from "react-native"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; -import { - pickableProjectGroups, - resolveScratchProjectScopeKey, -} from "@t3tools/client-runtime/state/project-grouping"; +import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { useProjects } from "../../state/entities"; import { steadyNavigationThreadShellsAtom } from "../../state/threads"; @@ -32,7 +29,7 @@ import { useAtomValueWhileVisible, useHomeRouteVisible, } from "./home-route-visibility"; -import { buildHomeProjectScopes } from "./homeThreadList"; +import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "./homeThreadList"; import { usePendingTaskListActions } from "./usePendingTaskListActions"; import { useThreadListActions } from "./useThreadListActions"; import { useWorkspaceTabs } from "../layout/workspace/WorkspaceTabsContext"; @@ -131,36 +128,26 @@ export function HomeRouteScreen() { setSelectedProjectKey, } = useHomeListOptions(availableEnvironmentIds); const selectedEnvironmentId = listOptions.selectedEnvironmentId; - // A legacy per-environment scratch key resolves here on every render; the stored - // value is only rewritten when the user picks a filter. - const resolvedProjectKey = resolveScratchProjectScopeKey( - listOptions.selectedProjectKey, - projects, - { - sidebarProjectGroupingMode: listOptions.projectGroupingMode, - sidebarProjectGroupingOverrides: {}, - }, + const projectScopes = useMemo( + () => + buildHomeProjectScopes({ + projects, + environmentId: selectedEnvironmentId, + projectGroupingMode: listOptions.projectGroupingMode, + }), + [listOptions.projectGroupingMode, projects, selectedEnvironmentId], ); const projectFilterOptions = useMemo( () => - pickableProjectGroups( - buildHomeProjectScopes({ - projects, - environmentId: selectedEnvironmentId, - projectGroupingMode: listOptions.projectGroupingMode, - }), - ).map((scope) => ({ + pickableProjectGroups(projectScopes).map((scope) => ({ key: scope.key, label: scope.title, project: scope.representative, })), - [listOptions.projectGroupingMode, projects, selectedEnvironmentId], + [projectScopes], ); - const selectedProjectKey = projectFilterOptions.some( - (project) => project.key === resolvedProjectKey, - ) - ? resolvedProjectKey - : null; + const selectedProjectKey = + resolveHomeProjectFilterScope(projectScopes, projects, listOptions)?.key ?? null; if (layout.usesSplitView && !nativePrimaryColumn) { return ( diff --git a/apps/mobile/src/features/home/homeThreadList.ts b/apps/mobile/src/features/home/homeThreadList.ts index 1b2e1a8c541f7..7c0392497645b 100644 --- a/apps/mobile/src/features/home/homeThreadList.ts +++ b/apps/mobile/src/features/home/homeThreadList.ts @@ -1,4 +1,8 @@ -import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; +import { + buildProjectGroups, + pickableProjectGroups, + resolveScratchProjectScopeKey, +} from "@t3tools/client-runtime/state/project-grouping"; import type { EnvironmentProject, EnvironmentThreadShell, @@ -70,6 +74,24 @@ export function buildHomeProjectScopes(input: { }); } +/** The scope the thread list's project filter shows; an archived or unknown key shows all projects. */ +export function resolveHomeProjectFilterScope( + scopes: ReadonlyArray, + projects: ReadonlyArray, + options: { + readonly selectedProjectKey: string | null; + readonly projectGroupingMode: SidebarProjectGroupingMode; + }, +): HomeProjectScope | null { + // A legacy per-environment scratch key resolves here; the stored value is only + // rewritten when the user picks a filter. + const key = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { + sidebarProjectGroupingMode: options.projectGroupingMode, + sidebarProjectGroupingOverrides: {}, + }); + return pickableProjectGroups(scopes).find((scope) => scope.key === key) ?? null; +} + export function findHomeProjectScope( scopes: ReadonlyArray, key: string | null, diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx index b9eeaf31f6a0b..b008956d50147 100644 --- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx +++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx @@ -64,6 +64,8 @@ import { useProjects } from "../../state/entities"; import { environmentThreadShells } from "../../state/threads"; import { withKnownPullRequestSummary } from "../../state/use-thread-pr"; import { mobilePreferencesAtom } from "../../state/preferences"; +import { savedConnectionsByIdAtom } from "../../state/use-remote-environment-registry"; +import { workspaceConnections } from "../../state/workspace"; import { DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS, resolveMobileProjectGroupingSettings, @@ -88,7 +90,8 @@ import { import { startOpeningDetail } from "./workspace/useSelectWorkspaceDetail"; import { useWorkspaceTabs } from "./workspace/WorkspaceTabsContext"; import { HomeListOptionsProvider } from "../home/home-list-options"; -import { newTaskDestination } from "../threads/new-task-project-selection"; +import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; +import { newTaskDestination, newTaskFilteredProject } from "../threads/new-task-project-selection"; import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary"; import { PaneContext } from "../../components/ui/Pane"; import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation"; @@ -613,12 +616,38 @@ function AdaptiveWorkspaceLayoutContent( : undefined; const preferences = appAtomRegistry.get(mobilePreferencesAtom); const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined; + // Resolve the thread list's filter as useHomeListOptions does: a removed connection's filter reads as all. + const listFilters = saved?.threadListFilters; + const listEnvironmentId = + listFilters?.environmentId != null && + appAtomRegistry.get(savedConnectionsByIdAtom)[listFilters.environmentId] !== undefined + ? listFilters.environmentId + : null; + const filteredScope = resolveHomeProjectFilterScope( + buildHomeProjectScopes({ projects, environmentId: listEnvironmentId, projectGroupingMode }), + projects, + { selectedProjectKey: listFilters?.projectKey ?? null, projectGroupingMode }, + ); + const connectedEnvironmentIds = new Set( + appAtomRegistry + .get(workspaceConnections.environmentsAtom) + .filter((environment) => environment.connectionState === "connected") + .map((environment) => environment.environmentId), + ); handleSelectThreadRoute( newTaskDestination({ projects, requestId: uuidv4(), useLastProject: saved?.useLastProjectForNewThreads, currentProject: environmentId && projectId ? { environmentId, projectId } : undefined, + filteredProject: filteredScope + ? newTaskFilteredProject( + filteredScope, + listEnvironmentId, + connectedEnvironmentIds, + saved?.lastNewThreadProjectRef ?? saved?.lastThreadProject ?? undefined, + ) + : undefined, lastProject: saved?.lastNewThreadProjectRef ?? saved?.lastThreadProject ?? undefined, }), ); diff --git a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx index a03a36bc94762..75d139621562a 100644 --- a/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx +++ b/apps/mobile/src/features/layout/workspace/WorkspaceRootScreen.android.tsx @@ -24,6 +24,8 @@ import { WorkspaceAppBarScope } from "../../../components/ui/WorkspaceAppBar.and import { usePaneRole } from "../../../components/ui/Pane"; import { AndroidWorkspaceSidebar } from "./AndroidWorkspaceSidebar.android"; import type { WorkspaceTab } from "./workspace-tabs-state"; +import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab"; +import { useHardwareBack } from "../../../lib/backHandler"; const TABS: readonly WorkspaceTab[] = NAVIGATION_TAB_ORDER; @@ -49,6 +51,18 @@ function WorkspaceRoot() { : 16, }; const tab = workspace.state.selectedTab; + const selectTab = useSelectWorkspaceTab(); + // Tabs are panes of Home, not routes, so Back has nothing to pop and would leave the app. + // An open search keeps Back for itself. + useHardwareBack( + tab !== "threads" && + enabled.includes("threads") && + workspace.state.tabs[tab].searchMode === "resting", + () => { + selectTab("threads"); + return true; + }, + ); return ( diff --git a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts index 3f217fd70c8bc..3cd3fe6d0978f 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tab-navigation.test.ts @@ -1,6 +1,7 @@ +import * as NodeModule from "node:module"; import { describe, expect, it } from "vite-plus/test"; -import { restoreSettingsLinkState } from "../../settings/settings-navigation"; +import { restoreSettingsLinkState, settingsLinkAction } from "../../settings/settings-navigation"; import { workspaceSelectionsIn, workspaceTabColumns, @@ -19,6 +20,17 @@ const pullRequest = { params: { environmentId: "env", projectId: "project", repository: "o/r", number: 7 }, }; const settings = { key: "settings", name: "Settings" }; +const requireFromNative = NodeModule.createRequire( + NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"), +); +const { getStateFromPath } = requireFromNative("@react-navigation/core") as { + readonly getStateFromPath: typeof import("@react-navigation/native").getStateFromPath; +}; +const { StackRouter } = NodeModule.createRequire( + requireFromNative.resolve("@react-navigation/core/package.json"), +)("@react-navigation/routers") as { + readonly StackRouter: typeof import("@react-navigation/native").StackRouter; +}; const available = { thread: () => true, pullRequest: () => true }; const names = (state: { routes: readonly { name: string }[] }) => state.routes.map((route) => route.name); @@ -218,6 +230,31 @@ describe("Settings links", () => { expect(restoreSettingsLinkState(bare, undefined)).toBe(bare); }); + it("opens a link sent to the running app on the Settings tab, as its button does", () => { + const screens = { + Home: "", + Settings: "settings", + SettingsAbout: "settings/about", + SettingsAppearance: "settings/appearance", + }; + const router = StackRouter({}); + const options = { routeNames: Object.keys(screens), routeParamList: {}, routeGetIdList: {} }; + const open = router.getRehydratedState( + { index: 2, routes: [{ name: "Home" }, { name: "Settings" }, { name: "SettingsAbout" }] }, + options, + ); + const follow = (path: string) => { + const link = getStateFromPath(path, { initialRouteName: "Home", screens })!; + const action = settingsLinkAction(link, open)!; + return router.getStateForAction(open, action, options)!; + }; + + expect(names(follow("settings"))).toEqual(["Home", "Settings"]); + const appearance = follow("settings/appearance"); + expect(names(appearance)).toEqual(["Home", "Settings", "SettingsAppearance"]); + expect(appearance.routes[1]!.key).toBe(open.routes[1]!.key); + }); + it("opens the sign-in link as a modal over the workspace", () => { const state = { routes: [{ name: "Home" }, { name: "SettingsAuth" }] }; expect(restoreSettingsLinkState(state, "SettingsAppearance")).toBe(state); diff --git a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts index f1c839630eb34..797da115a20eb 100644 --- a/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts +++ b/apps/mobile/src/features/layout/workspace/workspace-tabs-state.test.ts @@ -11,6 +11,8 @@ import { workspaceSearchBottomClearance, workspaceDockBottomClearance, workspaceUsesColumns, + type WorkspaceTab, + type WorkspaceTabsState, } from "./workspace-tabs-state"; describe("compact list clearance", () => { @@ -179,12 +181,25 @@ describe("workspace root navigation", () => { }); }); -const mocks = vi.hoisted(() => ({ split: false, floating: false })); +const mocks = vi.hoisted(() => ({ + split: false, + floating: false, + state: undefined as WorkspaceTabsState | undefined, + openWorkspaceTab: (_tab: string) => {}, + backListeners: new Set<() => boolean>(), +})); vi.mock("../../settings/appearance/AppearancePreferencesProvider", () => ({ useAndroidFloatingTabs: () => mocks.floating, })); vi.mock("react-native", () => ({ + BackHandler: { + addEventListener: (_event: string, listener: () => boolean) => { + mocks.backListeners.add(listener); + return { remove: () => mocks.backListeners.delete(listener) }; + }, + }, + Keyboard: { dismiss: () => undefined }, useWindowDimensions: () => ({ width: 400, height: 800 }), View: ({ children }: { children: ReactNode }) => createElement("div", null, children), })); @@ -198,12 +213,16 @@ vi.mock("../AdaptiveWorkspaceLayout", () => ({ startNewTask: () => undefined, }), })); +vi.mock("@react-navigation/native", () => ({ useIsFocused: () => true })); +vi.mock("../adaptive-workspace-context", () => ({ + useAdaptiveWorkspaceLayout: () => ({ openWorkspaceTab: mocks.openWorkspaceTab }), +})); vi.mock("./navigation-tabs", () => ({ useEnabledNavigationTabs: () => ["threads", "pullRequests", "usage"], })); vi.mock("./WorkspaceTabsContext", () => ({ WorkspaceTabsContext: createContext(null), - useWorkspaceTabs: () => ({ state: { selectedTab: "usage" } }), + useWorkspaceTabs: () => ({ state: mocks.state, dispatch: () => undefined }), })); vi.mock("./WorkspaceExtraTab", () => ({ WorkspaceExtraTab: function UsageProbe() { @@ -238,13 +257,37 @@ vi.mock("../../../components/ui/WorkspaceAppBar.android", () => ({ WorkspaceAppBarScope: ({ children }: { children: ReactNode }) => children, })); -function setup(split: boolean, floating: boolean) { +function setup(split: boolean, floating: boolean, state = selected("usage")) { mocks.split = split; mocks.floating = floating; + mocks.state = state; + mocks.openWorkspaceTab = () => undefined; + mocks.backListeners.clear(); vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); return { [Symbol.dispose]: () => vi.unstubAllGlobals() }; } +function selected(tab: WorkspaceTab) { + return workspaceTabsReducer(initialWorkspaceTabsState(), { type: "select", tab }); +} + +/** Android calls the newest listener first and stops at the first that handles Back. */ +function pressBack() { + return [...mocks.backListeners].reverse().some((listener) => listener()); +} + +it("Back from the Pulls tab returns to Threads instead of leaving the app", async () => { + using _actEnvironment = setup(false, false, selected("pullRequests")); + const opened: string[] = []; + mocks.openWorkspaceTab = (tab) => opened.push(tab); + const root = createRoot(document.createElement("div")); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + await act(async () => root.render(createElement(WorkspaceRootScreen))); + + expect(pressBack()).toBe(true); + expect(opened).toEqual(["threads"]); +}); + it.each([ [false, false], [true, false], diff --git a/apps/mobile/src/features/projects/AddProjectScreen.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.test.ts index ab331d0149e15..4718133f7a5a5 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.test.ts +++ b/apps/mobile/src/features/projects/AddProjectScreen.test.ts @@ -6,7 +6,11 @@ import * as NodeModule from "node:module"; import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { workspaceDetailRouter } from "../layout/workspace/workspace-detail-selection"; import type { NavigationState } from "@react-navigation/native"; -import { AuthOrchestrationOperateScope, AuthSourceControlWriteScope } from "@t3tools/contracts"; +import { + AuthFilesystemReadScope, + AuthOrchestrationOperateScope, + AuthSourceControlWriteScope, +} from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { act, createElement, isValidElement, type ReactNode } from "react"; @@ -22,7 +26,9 @@ const state = vi.hoisted(() => ({ id: string; title: string; workspaceRoot: string; + repositoryIdentity?: { canonicalKey: string }; }[], + cloneDestinations: [] as string[], createResult: null as Promise | null, createNewResult: null as Promise | null, startCloneResult: null as Promise | null, @@ -134,7 +140,15 @@ vi.mock("../../state/use-remote-environment-registry", () => ({ }), })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); -vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => () => {} })); +// Only filesystem.browse of `~` answers, with the host's home as its parentPath. +vi.mock("../../state/use-atom-query-runner", () => ({ + useAtomQueryRunner: + () => + async ({ input }: { input?: { partialPath?: string } }) => + input?.partialPath === "~" + ? AsyncResult.success({ parentPath: "/home/tester", entries: [] }) + : undefined, +})); vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({ data: null }) })); vi.mock("../../state/presentation", () => ({ useEnvironmentPresentation: () => ({ isReady: true, presentation: null }), @@ -144,6 +158,7 @@ vi.mock("../../state/sourceControl", () => ({ sourceControlEnvironment: { discovery: (input: unknown) => input, startProjectClone: async ({ input }: { input: { destinationPath: string } }) => { + state.cloneDestinations.push(input.destinationPath); if (state.startCloneResult) return state.startCloneResult; NodeFS.mkdirSync(input.destinationPath); return AsyncResult.success(undefined); @@ -230,7 +245,7 @@ function cloneAction() { renderScreen(() => AddProjectDestinationScreen({ environmentId: "environment", - remoteUrl: "https://example.com/repo.git", + remoteUrl: "https://example.com/owner/repo.git", repositoryName: "repo", }), ), @@ -274,6 +289,38 @@ describe("clone project permissions", () => { expect(state.projects).toEqual([]); }, ); + + it.each([ + [ + "opens the existing project of that repository instead of cloning into its folder", + "example.com/owner/repo", + false, + ], + ["leaves a folder holding another repository to the clone", "example.com/owner/other", true], + ])("%s", async (_name, canonicalKey, clones) => { + state.scopes.add(AuthOrchestrationOperateScope); + state.cloneDestinations = []; + state.startCloneResult = Promise.resolve( + AsyncResult.failure(Cause.fail(new Error("Destination is not empty"))), + ); + state.existingProjects = [ + { + environmentId: "environment", + id: "existing", + title: "repo", + workspaceRoot: NodePath.join(state.baseDirectory, "repo"), + repositoryIdentity: { canonicalKey }, + }, + ]; + try { + await cloneAction()(); + + expect(state.cloneDestinations.length > 0).toBe(clones); + } finally { + state.existingProjects = []; + state.startCloneResult = null; + } + }); }); function mountProjectFlow( @@ -488,10 +535,10 @@ describe("add project source environment", () => { }); describe("local project navigation", () => { - function setup() { + function setup(baseDirectory = "/tmp/t3-mobile-audit-fixture") { state.navigationState = undefined; state.scopes = new Set([AuthOrchestrationOperateScope]); - state.baseDirectory = "/tmp/t3-mobile-audit-fixture"; + state.baseDirectory = baseDirectory; state.projects = []; state.dispatch.mockReset(); state.alert.mockReset(); @@ -523,6 +570,28 @@ describe("local project navigation", () => { ); }); + it("opens an existing project typed as a home-relative path instead of creating it", async () => { + state.existingProjects = [ + { + environmentId: "environment", + id: "existing", + title: "bike-documents", + workspaceRoot: "/home/tester/projects/bike-documents", + }, + ]; + try { + const { created, projected, submit } = setup("~/projects/bike-documents/"); + state.scopes.add(AuthFilesystemReadScope); + created.resolve(AsyncResult.success(undefined)); + projected.resolve(null); + await submit(); + + expect(state.projects).toEqual([]); + } finally { + state.existingProjects = []; + } + }); + it("does not replace a reopened flow when the previous submission finishes", async () => { const { created, projected, submit } = setup(); const navigation = mountProjectFlow(false); diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx index 33b7de17c3914..56518cd071eac 100644 --- a/apps/mobile/src/features/projects/AddProjectScreen.tsx +++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx @@ -387,7 +387,26 @@ function useBrowsePathInput( [browseNavigation], ); - return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath }; + // Registered roots are absolute and `~` expands on the host, so ask the host for its home. + const resolveHomePath = async (path: string): Promise => { + if ( + !/^~(?:[\\/]|$)/.test(path) || + !environment || + !readEnvironmentScope(environment.environmentId, AuthFilesystemReadScope) || + !canPreloadBrowsePath(environmentRuntime?.connectionState) + ) { + return path; + } + const home = await loadBrowsePath({ + environmentId: environment.environmentId, + input: { partialPath: "~" }, + }); + return AsyncResult.isSuccess(home) && home.value + ? `${home.value.parentPath.replace(/[\\/]+$/, "")}${path.slice(1)}` + : path; + }; + + return { isBrowseNavigating, pathInput, setPathInput, navigateToBrowsePath, resolveHomePath }; } function useEnvironmentOptions( @@ -730,16 +749,76 @@ async function draftWithPrompt( return draftId; } -function useCreateProject(environment: EnvironmentOption | null) { +function useOpenExistingProject(environment: EnvironmentOption | null) { const openNewTaskDraft = useOpenNewTaskDraft(); - const navigation = useNavigation(); - const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); const updateProject = useAtomCommand(projectEnvironment.update, { label: "project unarchive", }); const projects = useProjects(); - return async (workspaceRoot: string, originRoute = getActiveRoute(navigation)) => { + return async ( + path: string, + originRoute: ReturnType, + clone?: { readonly remoteUrl: string; readonly prompt: string | null }, + ): Promise => { + if (!environment) return false; + const existing = findExistingAddProject({ + projects, + environmentId: environment.environmentId, + path, + }); + if (!existing) return false; + // A folder holding another repository is not this clone; let the clone report it occupied. + if ( + clone && + existing.repositoryIdentity?.canonicalKey !== + sourceControlClients.repositoryKeyFromRemote(clone.remoteUrl) + ) { + return false; + } + const prompt = clone?.prompt; + // Adding an archived project's folder again brings the project back. + const unarchived = + existing.archivedAt == null || + ( + await updateProject({ + environmentId: existing.environmentId, + input: { projectId: existing.id, archived: false }, + }) + )._tag === "Success"; + Dialog.alert( + "Project already exists", + unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, + ); + openNewTaskDraft( + { + environmentId: existing.environmentId, + projectId: existing.id, + title: existing.title, + ...(prompt + ? await draftWithPrompt(existing.environmentId, existing.id, prompt).then( + (draftId) => ({ draftId }), + () => ({}), + ) + : {}), + }, + originRoute, + ); + return true; + }; +} + +function useCreateProject(environment: EnvironmentOption | null) { + const openNewTaskDraft = useOpenNewTaskDraft(); + const navigation = useNavigation(); + const createProject = useAtomCommand(projectEnvironment.create, { reportFailure: false }); + const openExistingProject = useOpenExistingProject(environment); + + return async ( + workspaceRoot: string, + originRoute = getActiveRoute(navigation), + lookupPath = workspaceRoot, + ) => { if ( !environment || !canCreateProjectInEnvironment(environment.connectionState) || @@ -752,33 +831,7 @@ function useCreateProject(environment: EnvironmentOption | null) { return; } - const existing = findExistingAddProject({ - projects, - environmentId: environment.environmentId, - path: workspaceRoot, - }); - if (existing) { - // Adding an archived project's folder again brings the project back. - const unarchived = - existing.archivedAt == null || - ( - await updateProject({ - environmentId: existing.environmentId, - input: { projectId: existing.id, archived: false }, - }) - )._tag === "Success"; - Dialog.alert( - "Project already exists", - unarchived ? existing.title : `${existing.title} is still archived. Try again later.`, - ); - openNewTaskDraft( - { - environmentId: existing.environmentId, - projectId: existing.id, - title: existing.title, - }, - originRoute, - ); + if (await openExistingProject(lookupPath, originRoute)) { return; } @@ -1313,8 +1366,9 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st environment?.environmentId ?? null, AuthOrchestrationOperateScope, ); + const navigation = useNavigation(); const createProject = useCreateProject(environment); - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = + const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = useBrowsePathInput(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1333,7 +1387,11 @@ export function AddProjectLocalFolderScreen(props: { readonly environmentId?: st } setIsSubmitting(true); - const result = await createProject(resolved.path); + const originRoute = getActiveRoute(navigation); + const lookupPath = resolved.path.startsWith("~") + ? await resolveHomePath(resolved.path) + : resolved.path; + const result = await createProject(resolved.path, originRoute, lookupPath); if (result && AsyncResult.isFailure(result)) { setError(errorMessage(Cause.squash(result.cause))); } @@ -1404,11 +1462,9 @@ export function AddProjectDestinationScreen(props: { ? getCloneDirectoryPath(remoteUrl, true, repositoryName) : null; const cloneDirectoryName = ghqDirectoryPath?.split("/").at(-1) ?? repositoryName; - const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput( - environment, - cloneDirectoryName, - ghqDirectoryPath ?? repositoryName, - ); + const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput, resolveHomePath } = + useBrowsePathInput(environment, cloneDirectoryName, ghqDirectoryPath ?? repositoryName); + const openExistingProject = useOpenExistingProject(environment); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); @@ -1436,6 +1492,15 @@ export function AddProjectDestinationScreen(props: { const originRoute = getActiveRoute(navigation); setIsSubmitting(true); + if ( + await openExistingProject(await resolveHomePath(resolved.path), originRoute, { + remoteUrl, + prompt: prompt ?? null, + }) + ) { + setIsSubmitting(false); + return; + } const title = inferProjectTitleFromPath(resolved.path); const startResult = await startProjectClone({ environmentId: environment.environmentId, diff --git a/apps/mobile/src/features/settings/settings-navigation.ts b/apps/mobile/src/features/settings/settings-navigation.ts index b97bc948c0a2b..a414d1014a695 100644 --- a/apps/mobile/src/features/settings/settings-navigation.ts +++ b/apps/mobile/src/features/settings/settings-navigation.ts @@ -91,6 +91,24 @@ export function settingsNavigationState, + current: NavigationState | undefined, +) { + const top = link.routes.at(-1); + if (!current || !top || top.state || !isSettingsRoute(top.name)) return undefined; + const page = top.name === "Settings" ? undefined : (top.name as SettingsPageName); + return { + type: "RESET" as const, + payload: settingsNavigationState(current, page, top.params), + target: current.key, + }; +} + /** Opens one Settings page in the Settings tab, from anywhere outside it. */ export function openSettings( navigation: RootStackNavigation, diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx index 5202257e3bc8e..ab0ba504ac050 100644 --- a/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx +++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx @@ -1,7 +1,7 @@ import { applyTerminalAttachStreamEvent, EMPTY_TERMINAL_BUFFER_STATE, - terminalOutputText, + terminalOutputReplay, } from "@t3tools/client-runtime/state/terminal"; import { act, useImperativeHandle, useLayoutEffect, type ReactNode } from "react"; import { createRoot } from "react-dom/client"; @@ -106,7 +106,7 @@ function setup(revision: number | null) { ? null : (revision ?? 0) >= 1 ? "" - : terminalOutputText(state.output) + : terminalOutputReplay(state.output) } isRunning onInput={() => {}} @@ -163,6 +163,24 @@ it.each([null, 1])( } else { expect(mocks.write).not.toHaveBeenCalled(); expect(mocks.initialBuffers).toEqual(["retained", "ined-new"]); + // An older binary recreates its emulator unless the next buffer extends the last one. + // The buffer is full here, so the erase must not push the earlier output out. + let cleared = applyTerminalAttachStreamEvent( + state, + { type: "output", threadId: "thread", terminalId: "term-1", data: "\u001b[?1049h" }, + 16, + ); + await harness.render(cleared); + cleared = applyTerminalAttachStreamEvent( + cleared, + { type: "cleared", threadId: "thread", terminalId: "term-1" }, + 16, + ); + await harness.render(cleared); + expect(mocks.initialBuffers.slice(2)).toEqual([ + "ined-new\u001b[?1049h", + "ined-new\u001b[?1049h\u001b[H\u001b[2J\u001b[3J", + ]); } }, ); diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx index 1702c2f303ded..333cb9c0eadef 100644 --- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx +++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx @@ -1,4 +1,8 @@ -import type { TerminalGrid, TerminalOutputState } from "@t3tools/client-runtime/state/terminal"; +import { + terminalOutputText, + type TerminalGrid, + type TerminalOutputState, +} from "@t3tools/client-runtime/state/terminal"; import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react"; import { Pressable, @@ -199,7 +203,12 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface({ }); export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) { - const buffer = useTerminalSurfaceBuffer(props); + // The text fallback draws escape sequences literally, so it gets displayed text, not the replay. + const buffer = useTerminalSurfaceBuffer( + resolveNativeTerminalSurfaceView() || props.output === null + ? props + : { terminalKey: props.terminalKey, buffer: terminalOutputText(props.output) }, + ); return ; }); diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index e2b7bdd0e7961..44edf6bc16f61 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -151,6 +151,7 @@ import { scopedThreadKey } from "../../lib/scopedEntities"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { downloadAndShareAttachment } from "../../lib/attachmentDownload"; import { splitMarkdownDetails } from "../../lib/markdownDetails"; +import { markdownReferenceDefinitions, withReferenceDefinitions } from "../../lib/markdownDocument"; import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks"; import { SelectableMarkdownText, @@ -235,6 +236,8 @@ import { useAtomQueryRunner } from "../../state/use-atom-query-runner"; import { readEnvironmentScope, usePreparedConnection } from "../../state/session"; import { environmentProjects, projectEnvironment } from "../../state/projects"; import { + agentWorkingDirectories, + findAgentDirectoryMatch, needsWorkspaceBasenameLookup, pickProjectLinkMatch, pickWorkspaceLinkMatch, @@ -255,7 +258,11 @@ import { useModelMentions } from "../../state/model-mentions"; import { composerDocumentAttachmentRecord } from "../../lib/composerContext"; import * as Option from "effect/Option"; import { appAtomRegistry } from "../../state/atom-registry"; -import { environmentThreadShells, threadEnvironment } from "../../state/threads"; +import { + environmentThreadDetails, + environmentThreadShells, + threadEnvironment, +} from "../../state/threads"; import { ThreadWorkflowOpening } from "./thread-workflow-opening"; import { useWorkflowOpening } from "./use-workflow-opening"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -1062,10 +1069,18 @@ function ThreadMediaVisibility(props: { readonly children: ReactNode }) { useViewabilityAmount((token) => setVisible(token.sizeVisible > 0)); return {props.children}; } + +/** The reply a link sits in; a file it cites may be where the agent worked before writing it. */ +type MarkdownLinkReply = Pick; + interface MarkdownLinkHandlers { - readonly onLinkPress: (href: string) => void; + readonly onLinkPress: (href: string, reply?: MarkdownLinkReply) => void; readonly fileContextMenu: (href: string) => MarkdownFileContextMenu | undefined; - readonly onFileContextMenuAction: (href: string, actionId: string) => void; + readonly onFileContextMenuAction: ( + href: string, + actionId: string, + reply?: MarkdownLinkReply, + ) => void; readonly onImagePress?: (href: string) => void; readonly resolveImageSource?: MarkdownImageSourceResolver; readonly fileEmbedLabel?: (href: string, standalone: boolean) => string | null; @@ -1131,6 +1146,7 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { readonly environmentId: EnvironmentId; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; + readonly reply?: MarkdownLinkReply | undefined; readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; readonly renderImage: MarkdownImageRenderer; readonly skills?: ReadonlyArray | undefined; @@ -1140,6 +1156,9 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { const threadIcons = useThreadChipIcons(props.environmentId, liveMarkdown); const linkHandlers: MarkdownLinkHandlers = { ...props.linkHandlers, + onLinkPress: (href) => props.linkHandlers.onLinkPress(href, props.reply), + onFileContextMenuAction: (href, actionId) => + props.linkHandlers.onFileContextMenuAction(href, actionId, props.reply), linkCustomization: (href) => withChipIcon(props.linkHandlers.linkCustomization?.(href), threadIcons.get(href)), }; @@ -1160,6 +1179,8 @@ const AssistantMarkdownContent = memo(function AssistantMarkdownContent(props: { // Folds split first, so an artifact card inside a fold stays inside it. function AssistantMarkdownBlocks(props: { readonly markdown: string; + /** The reply's reference definitions, passed down by the enclosing fold. */ + readonly definitions?: ReadonlyArray | undefined; readonly markdownStyles: MarkdownStyleSet; readonly linkHandlers: MarkdownLinkHandlers; readonly onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; @@ -1167,15 +1188,20 @@ function AssistantMarkdownBlocks(props: { readonly skills?: ReadonlyArray | undefined; readonly models: ReturnType; }) { - const blocks = useMemo( - () => - splitMarkdownDetails(props.markdown).map((block) => - block.kind === "details" - ? block - : { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) }, - ), - [props.markdown], - ); + const { blocks, definitions } = useMemo(() => { + const blocks = splitMarkdownDetails(props.markdown).map((block) => + block.kind === "details" + ? block + : { ...block, segments: splitCodexArtifactTemplateMarkdown(block.markdown) }, + ); + const [first] = blocks; + // A reply rendered as one document resolves its own references; skip the extra parse. + const whole = blocks.length === 1 && first?.kind === "markdown" && first.segments.length === 1; + return { + blocks, + definitions: props.definitions ?? (whole ? [] : markdownReferenceDefinitions(props.markdown)), + }; + }, [props.markdown, props.definitions]); return blocks.map((block) => { if (block.kind === "details") { return ( @@ -1184,7 +1210,7 @@ function AssistantMarkdownBlocks(props: { summary={block.summary} initiallyOpen={block.open} > - + ); } @@ -1203,7 +1229,9 @@ function AssistantMarkdownBlocks(props: { return ( + + + + + ); + } + if (entry.type === "mcp-app") { return ( => { const relativePath = resolveWorkspaceRelativeFilePath(props.workspaceRoot, path); if ( @@ -2944,6 +2992,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { root, entries: result._tag === "Success" ? result.value.entries : [], })); + const metadataOf = (target: string) => + executeAtomQuery( + appAtomRegistry, + projectEnvironment.fileMetadata({ + environmentId: props.environmentId, + input: { path: target }, + }), + queryOptions, + ); const lookup = async () => { const own = await searchRoot(workspaceRoot); let match = pickWorkspaceLinkMatch(relativePath, workspaceRoot, own.entries); @@ -2968,15 +3025,35 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ? null : pickProjectLinkMatch(relativePath, await Promise.all(otherRoots.map(searchRoot))); } + if (match === null && reply !== undefined && !signal.aborted) { + // No project has the file, so it opens where the agent last worked, as written. + const agentRoots = agentWorkingDirectories( + appAtomRegistry.get( + environmentThreadDetails.quietThreadAtom( + scopeThreadRef(props.environmentId, props.threadId), + ), + )?.projection.visibleTurnItems ?? [], + reply, + ).filter((root) => root !== workspaceRoot); + const agentPaths = agentRoots.map((root) => resolveWorkspaceFilePath(root, relativePath)); + if (agentPaths.length === 0) return relativePath; + const [original, ...found] = await Promise.all( + [originalPath, ...agentPaths].map(metadataOf), + ); + if (original?._tag !== "Success" || original.value !== null) return relativePath; + const index = found.findIndex( + (result) => result._tag === "Success" && result.value?.kind === "file", + ); + const literal = agentPaths[index]; + if (literal !== undefined || !needsWorkspaceBasenameLookup(relativePath)) { + return literal ?? relativePath; + } + return ( + (await findAgentDirectoryMatch(relativePath, agentRoots, searchRoot)) ?? relativePath + ); + } if (!match || match === relativePath || signal.aborted) return relativePath; - const metadata = await executeAtomQuery( - appAtomRegistry, - projectEnvironment.fileMetadata({ - environmentId: props.environmentId, - input: { path: originalPath }, - }), - queryOptions, - ); + const metadata = await metadataOf(originalPath); // Another project's file never replaces a thread-local file the search missed. return metadata._tag === "Success" && (needsWorkspaceBasenameLookup(relativePath) && !otherProject @@ -2987,7 +3064,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }; return lookup().catch(() => relativePath); }; - const onMarkdownLinkPress = (href: string, imageEmbed = false) => { + const onMarkdownLinkPress = (href: string, imageEmbed = false, reply?: MarkdownLinkReply) => { markdownLinkRequest.current?.abort(); const request = new AbortController(); markdownLinkRequest.current = request; @@ -3059,7 +3136,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { if (presentation.kind === "file") { const path = resolveFileLinkPath(props.workspaceRoot, presentation.path); if (path === null) return; - void findFileLinkTarget(presentation.path, path, request.signal).then((target) => { + void findFileLinkTarget(presentation.path, path, request.signal, reply).then((target) => { if (request.signal.aborted) return; void Haptics.selectionAsync(); navigation.navigate("ThreadFile", { @@ -3101,7 +3178,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }, standalone, ), - onLinkPress: onMarkdownLinkPress, + onLinkPress: (href, reply) => onMarkdownLinkPress(href, false, reply), linkCustomization: enrichedThreadLinkCustomization, onImagePress: (href) => onMarkdownLinkPress(href, true), resolveImageSource, @@ -3143,7 +3220,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const target = resolveFileChipTarget(href, props.workspaceRoot); return target ? fileChipMenu(target) : pullRequestLinkMenu.fileContextMenu(href); }, - onFileContextMenuAction: (href, actionId) => { + onFileContextMenuAction: (href, actionId, reply) => { const skill = enrichedSkillReference(href, props.skills); if (skill) { const instructionsPath = enrichedSkillInstructionsPath(skill); @@ -3174,7 +3251,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { markdownLinkRequest.current?.abort(); const request = new AbortController(); markdownLinkRequest.current = request; - void findFileLinkTarget(presentation.path, path, request.signal).then((found) => { + void findFileLinkTarget(presentation.path, path, request.signal, reply).then((found) => { if (request.signal.aborted) return; const fullPath = props.workspaceRoot && !isAbsolutePath(found) @@ -3199,7 +3276,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { return; } case "open-file": - onMarkdownLinkPress(href); + onMarkdownLinkPress(href, false, reply); return; case "save": shareFileChip(target); diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 2a0d310d90aa7..28d3689a30455 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -2,10 +2,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon"; import { useActiveNewTask } from "../../state/active-new-task"; import { ThreadUndoNotice } from "../home/ThreadUndoNotice"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; -import { - pickableProjectGroups, - resolveScratchProjectScopeKey, -} from "@t3tools/client-runtime/state/project-grouping"; +import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping"; import { useAppearancePreferences, useAndroidFloatingTabs, @@ -49,7 +46,7 @@ import { requestThreadMessageJump } from "./threadMessageJump"; import { useThreadListSearchMatches } from "./useThreadListSearchMatches"; import { useHomeListOptions } from "../home/home-list-options"; import { buildHomeListFilterMenuItems } from "../home/home-list-filter-menu"; -import { buildHomeProjectScopes } from "../home/homeThreadList"; +import { buildHomeProjectScopes, resolveHomeProjectFilterScope } from "../home/homeThreadList"; import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions"; import { usePendingTaskListActions } from "../home/usePendingTaskListActions"; import { useThreadListActions } from "../home/useThreadListActions"; @@ -176,12 +173,6 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ) ? [options.selectedEnvironmentId] : []; - // A legacy per-environment scratch key resolves here on every render; the stored - // value is only rewritten when the user picks a filter. - const resolvedProjectKey = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { - sidebarProjectGroupingMode: options.projectGroupingMode, - sidebarProjectGroupingOverrides: {}, - }); const projectScopes = useMemo( () => buildHomeProjectScopes({ @@ -211,9 +202,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) { ), [projectScopes], ); - // An archived project's filter reads as all projects, matching the filter menu. - const selectedProjectScope = - pickableProjectGroups(projectScopes).find((scope) => scope.key === resolvedProjectKey) ?? null; + const selectedProjectScope = resolveHomeProjectFilterScope(projectScopes, projects, options); const threadSearch = useThreadSearch( searchEnvironmentIds, props.searchQuery, diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx index ab8d94d085a9b..a0ed0c0c4766f 100644 --- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx +++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx @@ -97,7 +97,7 @@ import { resolveNewTaskBranchWorktreePath, resolveNewTaskLocalWorkspaceSelection, } from "./new-task-context-presentation"; -import { resolveEnvironmentProjectMatch } from "./new-task-project-selection"; +import { isSameRepository, resolveEnvironmentProjectMatch } from "./new-task-project-selection"; import { useNewTaskProjectDefaults } from "./use-new-task-project-defaults"; import { resolveNewThreadRuntimeMode } from "./thread-settings-options"; import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation"; @@ -586,11 +586,14 @@ export function NewTaskFlowProvider( replaceComposerDraftAttachments(selectedProjectDraftKey, []); }; - const carryDraftContentTo = (project: EnvironmentProject): string => { + const carryDraftContentTo = ( + project: EnvironmentProject, + options?: Parameters[2], + ): string => { const target = { environmentId: project.environmentId, projectId: project.id }; const current = readFlow().draftKey; if (current !== null && isNewTaskDraftKey(current)) { - retargetNewTaskDraft(current, target); + retargetNewTaskDraft(current, target, options); return current; } return createNewTaskDraft(target); @@ -613,7 +616,12 @@ export function NewTaskFlowProvider( selectedProject, ); updateFlow({ - draftKey: match ? carryDraftContentTo(match) : readFlow().draftKey, + // A name or title match may be another repository, which must not receive the PR checkout. + draftKey: match + ? carryDraftContentTo(match, { + keepPullRequestWorkspace: isSameRepository(match, selectedProject), + }) + : readFlow().draftKey, environmentId, projectKey: match ? scopedProjectKey(match.environmentId, match.id) : null, }); diff --git a/apps/mobile/src/features/threads/new-task-project-selection.test.ts b/apps/mobile/src/features/threads/new-task-project-selection.test.ts index b6800e4deef33..18f92d749f46d 100644 --- a/apps/mobile/src/features/threads/new-task-project-selection.test.ts +++ b/apps/mobile/src/features/threads/new-task-project-selection.test.ts @@ -5,7 +5,9 @@ import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import type { HomeProjectScope } from "../home/homeThreadList"; import { getProjectScopeSelectionTarget, + isSameRepository, newTaskDestination, + newTaskFilteredProject, resolveDraftProjectSelection, resolveEnvironmentProjectMatch, resolveNewTaskScratchOption, @@ -77,6 +79,37 @@ describe("getProjectScopeSelectionTarget", () => { }); }); +describe("newTaskFilteredProject", () => { + it("never starts in an archived copy of the filtered project", () => { + const mac = { ...makeProject("t3code", "mac"), archivedAt: "2026-01-01T00:00:00.000Z" }; + const server = makeProject("t3code", "server"); + expect( + newTaskFilteredProject( + makeScope([mac, server]), + null, + new Set([mac.environmentId, server.environmentId]), + { environmentId: "mac", projectId: "t3code" }, + ), + ).toEqual({ environmentId: "server", projectId: "t3code" }); + }); + + it("prefers the remembered copy of the filtered project", () => { + const mac = makeProject("t3code", "mac"); + const server = makeProject("t3code", "server"); + const connected = new Set([mac.environmentId, server.environmentId]); + const filtered = (last?: { readonly environmentId: string; readonly projectId: string }) => + newTaskFilteredProject(makeScope([mac, server]), null, connected, last); + expect(filtered({ environmentId: "server", projectId: "t3code" })).toEqual({ + environmentId: "server", + projectId: "t3code", + }); + expect(filtered({ environmentId: "server", projectId: "other" })).toEqual({ + environmentId: "mac", + projectId: "t3code", + }); + }); +}); + describe("resolveEnvironmentProjectMatch", () => { it("follows the same repository onto the target machine", () => { const selected = makeProject("t3code", "mac", { repositoryKey: "github.com/t3tools/t3code" }); @@ -85,6 +118,7 @@ describe("resolveEnvironmentProjectMatch", () => { makeProject("t3code-clone", "server", { repositoryKey: "github.com/t3tools/t3code" }), ]; expect(resolveEnvironmentProjectMatch(target, selected)).toBe(target[1]); + expect(isSameRepository(target[1]!, selected)).toBe(true); }); it("falls back to workspace basename, then title, for unindexed projects", () => { @@ -94,6 +128,7 @@ describe("resolveEnvironmentProjectMatch", () => { makeProject("srv", "server", { workspaceRoot: "/home/me/t3code" }), ]; expect(resolveEnvironmentProjectMatch(byBasename, selected)).toBe(byBasename[1]); + expect(isSameRepository(byBasename[1]!, selected)).toBe(false); const byTitle = [ makeProject("other", "server"), @@ -115,6 +150,7 @@ describe("resolveEnvironmentProjectMatch", () => { const unindexed = makeProject("unindexed", "server", { workspaceRoot: "/srv/t3code" }); expect(resolveEnvironmentProjectMatch([fork, unindexed], selected)).toBe(unindexed); expect(resolveEnvironmentProjectMatch([fork], selected)).toBe(fork); + expect(isSameRepository(fork, selected)).toBe(false); }); }); @@ -173,6 +209,7 @@ describe("newTaskDestination", () => { readonly useLastProject: boolean | undefined; readonly projects: ReadonlyArray; readonly current?: EnvironmentProject; + readonly filtered?: EnvironmentProject; readonly last?: { readonly environmentId: string; readonly projectId: string }; }) { return newTaskDestination({ @@ -183,17 +220,26 @@ describe("newTaskDestination", () => { environmentId: options.current.environmentId, projectId: options.current.id, }, + filteredProject: options.filtered && { + environmentId: options.filtered.environmentId, + projectId: options.filtered.id, + }, lastProject: options.last, }); } - it("keeps the last new-thread project while viewing another project's thread", () => { - const projects = [makeProject("remembered"), makeProject("current", "other-environment")]; + it("keeps the last new-thread project ahead of current and filtered projects", () => { + const projects = [ + makeProject("remembered"), + makeProject("current", "other-environment"), + makeProject("filtered"), + ]; expect( destination({ useLastProject: true, projects, current: projects[1], + filtered: projects[2], last: { environmentId: "environment", projectId: "remembered" }, }), ).toEqual({ @@ -201,6 +247,20 @@ describe("newTaskDestination", () => { }); }); + it("uses the thread list's filtered project when remembered and current projects are unavailable", () => { + const projects = [makeProject("bravo"), makeProject("alpha")]; + expect( + destination({ + useLastProject: true, + projects, + filtered: projects[1], + last: { environmentId: "removed-environment", projectId: "bravo" }, + }), + ).toEqual({ + draft: { requestId: "request", environmentId: "environment", projectId: "alpha" }, + }); + }); + it("opens the picker for an archived last project, but keeps an archived current one", () => { const archived = { ...makeProject("archived"), archivedAt: "2026-01-01T00:00:00.000Z" }; expect( @@ -262,6 +322,7 @@ describe("newTaskDestination", () => { useLastProject: false, projects: [only], current: only, + filtered: only, last: { environmentId: "environment", projectId: "only" }, }), ).toEqual(picker); diff --git a/apps/mobile/src/features/threads/new-task-project-selection.ts b/apps/mobile/src/features/threads/new-task-project-selection.ts index da90a327e96aa..6886424d1d0e9 100644 --- a/apps/mobile/src/features/threads/new-task-project-selection.ts +++ b/apps/mobile/src/features/threads/new-task-project-selection.ts @@ -117,6 +117,19 @@ export function resolveEnvironmentProjectMatch( ); } +/** Both projects have a known repository identity, and it is the same one. */ +export function isSameRepository( + left: EnvironmentProject | null, + right: EnvironmentProject | null, +): boolean { + return ( + left?.repositoryIdentity != null && + right?.repositoryIdentity != null && + repositoryGroupingKeyOf(left.repositoryIdentity) === + repositoryGroupingKeyOf(right.repositoryIdentity) + ); +} + export function resolveDraftProjectSelection( selectedProjectKey: string | null, projects: ReadonlyArray, @@ -147,11 +160,35 @@ export function resolveDraftProjectSelection( type ProjectRef = { readonly environmentId: string; readonly projectId: string }; +/** The live copy of the thread list's filtered project a new thread starts in: the remembered one if it is a copy. */ +export function newTaskFilteredProject( + scope: HomeProjectScope, + preferredEnvironmentId: EnvironmentId | null, + connectedEnvironmentIds: ReadonlySet, + lastProject: ProjectRef | undefined, +): ProjectRef | undefined { + const live = scope.projects.filter((project) => project.archivedAt == null); + if (live.length === 0) return undefined; + const project = + live.find( + (candidate) => + candidate.environmentId === lastProject?.environmentId && + candidate.id === lastProject.projectId, + ) ?? + getProjectScopeSelectionTarget( + { ...scope, projects: live }, + preferredEnvironmentId, + connectedEnvironmentIds, + ); + return { environmentId: project.environmentId, projectId: project.id }; +} + export function newTaskDestination(options: { readonly projects: ReadonlyArray; readonly requestId: string; readonly useLastProject: boolean | undefined; readonly currentProject: ProjectRef | undefined; + readonly filteredProject: ProjectRef | undefined; readonly lastProject: ProjectRef | undefined; }) { const find = (ref: ProjectRef | undefined) => @@ -163,7 +200,9 @@ export function newTaskDestination(options: { const project = options.useLastProject === false ? undefined - : ((last?.archivedAt == null ? last : undefined) ?? find(options.currentProject)); + : ((last?.archivedAt == null ? last : undefined) ?? + find(options.currentProject) ?? + find(options.filteredProject)); return project ? { draft: { diff --git a/apps/mobile/src/lib/markdownDetails.test.ts b/apps/mobile/src/lib/markdownDetails.test.ts index f4eae44872520..c90d89838f4c6 100644 --- a/apps/mobile/src/lib/markdownDetails.test.ts +++ b/apps/mobile/src/lib/markdownDetails.test.ts @@ -1,6 +1,33 @@ import { describe, expect, it } from "vite-plus/test"; import { splitMarkdownDetails } from "./markdownDetails"; +import { + markdownForNativeParsing, + markdownReferenceDefinitions, + withReferenceDefinitions, +} from "./markdownDocument"; +import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown"; + +type NativeNode = Awaited>; + +/** Where the native parser sends each link and image in one rendered fragment of a reply. */ +async function referenceDestinations(reply: string, pick: number) { + const segment = splitMarkdownDetails(reply)[pick]; + const fragment = segment?.kind === "details" ? segment.body : (segment?.markdown ?? ""); + const urls: Array = []; + const visit = (node: NativeNode) => { + if (node.type === "Link" || node.type === "Image") urls.push(node.attributes?.url); + node.children?.forEach(visit); + }; + visit( + await parseMarkdown( + markdownForNativeParsing( + withReferenceDefinitions(fragment, markdownReferenceDefinitions(reply)), + ), + ), + ); + return urls; +} describe("splitMarkdownDetails", () => { // regression: #28059 mobile chat showed every
fold open @@ -78,3 +105,57 @@ describe("splitMarkdownDetails", () => { ).toMatchObject([{ kind: "details", open: false }]); }); }); + +describe("withReferenceDefinitions", () => { + it("resolves a fragment's references from the whole reply, its own definitions first", async () => { + const fold = "\n\n
Aa
\n\n"; + for (const [reply, pick, expected] of [ + // Into a fold, with an escaped label and a Windows destination kept as written. + [ + "
\nA\n\n[config][c] ![B][a\\]b]\n\n
\n\n[c]: C:\\work\\.t3\\settings.json\n[a\\]b]: https://example.com/a", + 0, + ["C:\\work\\.t3\\settings.json", "https://example.com/a"], + ], + // Out of a fold. + [ + "See [d].\n\n
\nA\n\n[d]: https://example.com\n\n
", + 0, + ["https://example.com"], + ], + // A quoted definition that wraps onto continuation lines. + [`See [d].${fold}> [d]:\n> https://example.com\n> "Title"`, 0, ["https://example.com"]], + // A definition the compact HTML block hides from the reply's parse, with a label that wraps. + [ + "See [the\n doc].\n\n
Aa
\n[The Doc]: https://example.com", + 0, + ["https://example.com"], + ], + // A literal ">" in a wrapped label is part of the label, not a quote marker. + [ + `[part rest] and [part > rest]${fold}[part\n > rest]: https://example.com/a\n\n[part rest]: https://example.com/b`, + 0, + ["https://example.com/b", "https://example.com/a"], + ], + // A fragment's own definition wins, however the parser equates the two labels. + [ + "[ x ]: https://outside.example\n\n
\nS\n\nSee [x].\n\n[X]: https://inside.example\n\n
", + 1, + ["https://inside.example"], + ], + [ + "[SS]: https://outside.example\n\n
\nS\n\nSee [SS].\n\n[\u00df]: https://inside.example\n\n
", + 1, + ["https://inside.example"], + ], + ] as const) { + expect(await referenceDestinations(reply, pick)).toEqual(expected); + } + }); + + it("leaves a fragment with nothing to resolve as written", () => { + expect(withReferenceDefinitions("See [d].", [])).toBe("See [d]."); + expect(withReferenceDefinitions("Plain text.", ["[d]: https://example.com"])).toBe( + "Plain text.", + ); + }); +}); diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index 526b2eb49e9c0..8a1b58ef09e71 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -284,6 +284,41 @@ export function markdownWithHtml(markdown: string): string { return applyMarkdownEdits(markdown, edits); } +/** Reference definitions as authored, one line each, so a Windows destination keeps its backslashes. */ +export function markdownReferenceDefinitions(markdown: string): string[] { + if (!markdown.includes("]:")) return []; + // Flattened as the renderer does it: a raw HTML block hides the definitions inside it. + const flattened = markdownWithHtml(markdown); + const definitions: string[] = []; + const visit = (node: MarkdownNode, quotes: number) => { + if (node.type === "definition") { + // A wrapped definition drops its indent and the enclosing quotes' markers, not a literal ">". + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "g"); + definitions.push( + flattened.slice(node.position?.start.offset, node.position?.end.offset).replace(wrap, " "), + ); + } + if (!("children" in node)) return; + for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + }; + visit(parser.parse(flattened), 0); + return definitions; +} + +/** + * A reply split into folds and cards renders each fragment as its own document, so each one + * carries the reply's definitions. The first definition of a label wins, so the fragment's own + * lead: the renderer then prefers them by its own label matching, with none reimplemented here. + */ +export function withReferenceDefinitions( + fragment: string, + replyDefinitions: ReadonlyArray, +): string { + if (replyDefinitions.length === 0 || !fragment.includes("[")) return fragment; + const definitions = new Set([...markdownReferenceDefinitions(fragment), ...replyDefinitions]); + return `${[...definitions].join("\n")}\n\n${fragment}`; +} + // Start only at the beginning of a backtick run to avoid retrying every suffix. const INLINE_CODE_SPAN = /(? + | Extract | { readonly type: "activity-group"; readonly id: string; @@ -1121,7 +1129,10 @@ function feedEntryFoldRunId(entry: ThreadFeedEntry, runlessKey: RunId | null): R if (entry.type === "message") { return entry.message.role === "assistant" ? (entry.message.runId ?? runlessKey) : null; } - return entry.type === "activity-group" || entry.type === "html-render" || entry.type === "mcp-app" + return entry.type === "activity-group" || + entry.type === "html-render" || + entry.type === "sent-message" || + entry.type === "mcp-app" ? (entry.runId ?? runlessKey) : null; } @@ -1251,6 +1262,7 @@ function deriveThreadFeedRunFolds( !(entry.type === "message" && retainedAnswerIds.has(entry.message.id)) && entry.type !== "viewed-image" && entry.type !== "html-render" && + entry.type !== "sent-message" && entry.type !== "mcp-app" && entry.id !== visibleCompactionId && !( @@ -2429,6 +2441,23 @@ export function buildThreadFeed( entryRows.push(index); continue; } + const sentMessage = + item.type === "dynamic_tool" && item.status === "completed" + ? sentMessageFromToolItem(item) + : undefined; + if (sentMessage !== undefined) { + const entry: RawThreadFeedEntry = { + type: "sent-message", + id: `sent-message:${row.visibility}:${row.sourceThreadId}:${row.sourceItemId}`, + createdAt, + runId: item.runId, + text: sentMessage, + }; + projectedEntriesCache.set(row, { attemptId, entries: [entry] }); + entries.push(entry); + entryRows.push(index); + continue; + } if (item.type === "user_message" || item.type === "assistant_message") { const updatedAt = DateTime.formatIso(item.updatedAt); const entry: RawThreadFeedEntry = { diff --git a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts index 309bb6a2b0a76..0d7bfdc3e8c7a 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.permissions.test.ts @@ -10,7 +10,7 @@ import { import * as Cause from "effect/Cause"; import { AsyncResult, type Atom } from "effect/reactivity"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; -import type { QueuedThreadMessage } from "./thread-outbox-model"; +import { threadOutboxRetryDelayMs, type QueuedThreadMessage } from "./thread-outbox-model"; const state = vi.hoisted(() => ({ draftText: "Keep this draft separate", @@ -501,6 +501,108 @@ describe("queued task operation access", () => { ); }); +describe("queued task whose launch reply is lost", () => { + const queuedTask = (creation: Partial> = {}) => + message({ + threadId: ThreadId.make("new-thread"), + text: "My dictated idea", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + creation: { + projectId: ProjectId.make("project"), + projectCwd: "/repo", + workspaceMode: "local", + branch: null, + worktreePath: null, + ...creation, + }, + }); + + /** The server creates the thread, but the launch reply is lost; the thread then shows up. */ + async function loseLaunchReply(queued: QueuedThreadMessage, edit?: string): Promise { + setOperateGrant("secondary", true); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + state.cleanups.push(() => vi.useRealTimers()); + await state.manager.enqueue(queued); + state.start.mockImplementationOnce(async () => { + if (edit !== undefined) await state.manager.update({ ...queued, text: edit }); + return AsyncResult.failure(Cause.fail(new Error("Socket is not connected"))); + }); + await runDrain(); + expect(remaining()).toHaveLength(1); + appAtomRegistry.set(state.threadShells, [state.thread, { ...state.thread, id: "new-thread" }]); + } + + async function fireRetry(): Promise { + const settled = Promise.withResolvers(); + const release = appAtomRegistry.subscribe(dispatchingQueuedMessageIdAtom, (id) => { + if (id === null) settled.resolve(); + }); + vi.advanceTimersByTime(threadOutboxRetryDelayMs(1)); + await settled.promise.finally(release); + } + + it("resends an unedited launch instead of handing its text back", async () => { + await loseLaunchReply(queuedTask()); + await fireRetry(); + + expect(state.draftText).toBe("Keep this draft separate"); + // The resend reuses the launch's command and message ids, so the server replays it. + const [first, resent] = state.start.mock.calls.map(([call]) => call.input); + expect(state.start).toHaveBeenCalledTimes(2); + expect(resent.commandId).toBe(first.commandId); + expect(resent.message.messageId).toBe(first.message.messageId); + expect(remaining()).toEqual([]); + }); + + it("hands back a task edited while its launch was in flight", async () => { + await loseLaunchReply(queuedTask(), "Edited idea"); + await fireRetry(); + + expect(state.draftText).toBe("Keep this draft separate\nEdited idea"); + expect(state.start).toHaveBeenCalledOnce(); + expect(remaining()).toEqual([]); + }); + + it("holds the resend while operation access is missing", async () => { + await loseLaunchReply(queuedTask()); + setOperateGrant("secondary", false); + vi.advanceTimersByTime(threadOutboxRetryDelayMs(1)); + expect(appAtomRegistry.get(dispatchingQueuedMessageIdAtom)).toBeNull(); + expect(state.start).toHaveBeenCalledOnce(); + expect(remaining()).toHaveLength(1); + + setOperateGrant("secondary", true); + await runDrain(); + expect(state.start).toHaveBeenCalledTimes(2); + expect(state.draftText).toBe("Keep this draft separate"); + expect(remaining()).toEqual([]); + }); + + it("resends a pull request task in its launched worktree without checking out again", async () => { + state.checkout.mockResolvedValueOnce( + AsyncResult.success({ + branch: "pr-123", + worktreePath: "/repo/.t3/worktrees/pr-123", + isOnPullRequestHead: true, + }), + ); + await loseLaunchReply( + queuedTask({ + workspaceMode: "worktree", + branch: "fork/feature", + pullRequestReference: "https://github.com/acme/repo/pull/123", + }), + ); + await fireRetry(); + + expect(state.checkout).toHaveBeenCalledOnce(); + const [first, resent] = state.start.mock.calls.map(([call]) => call.input); + expect(resent.bootstrap.createThread.worktreePath).toBe("/repo/.t3/worktrees/pr-123"); + expect(resent.bootstrap).toEqual(first.bootstrap); + expect(remaining()).toEqual([]); + }); +}); + describe("compaction before a queued send", () => { const compactTurn = { commandId: "command:compact", diff --git a/apps/mobile/src/state/threadOutboxDelivery.ts b/apps/mobile/src/state/threadOutboxDelivery.ts index c64215ed26cd3..ed9c33719a4d8 100644 --- a/apps/mobile/src/state/threadOutboxDelivery.ts +++ b/apps/mobile/src/state/threadOutboxDelivery.ts @@ -694,6 +694,12 @@ export function createThreadOutboxDelivery(): { // Existing-thread turns the server accepted but whose outbox removal has // not landed; the next pass retries only the removal, never the send. const acknowledgedExistingThreadMessageIds = new Set(); + // Revision and workspace each new task's launch carried. Launch replays by command id, so an + // unedited task whose reply was lost is resent in that workspace, not handed back. + const launchedCreations = new Map< + MessageId, + { readonly revision: number; readonly workspace: QueuedThreadCreation } + >(); // Targets the shell may have left out hold their thread family until they leave the queue, so // the row stays readable through dispatch. const familyMounts = new Map void>(); @@ -1064,7 +1070,10 @@ export function createThreadOutboxDelivery(): { ); if (!hasAccess()) return true; let workspace = creation; - if (creation.pullRequestReference) { + const launched = launchedCreations.get(persistedMessage.messageId); + if (launched?.revision === deliveryRevision) { + workspace = launched.workspace; + } else if (creation.pullRequestReference) { const checkout = await runDeliveryCommand(gitEnvironment.preparePullRequestThread, { environmentId: queuedMessage.environmentId, input: { cwd: projectCwd, reference: creation.pullRequestReference, mode: "worktree" }, @@ -1094,6 +1103,7 @@ export function createThreadOutboxDelivery(): { startFromOrigin: false, }; } + launchedCreations.set(persistedMessage.messageId, { revision: deliveryRevision, workspace }); const deliveryResult = await runDeliveryCommand(threadEnvironment.startTurn, { environmentId: queuedMessage.environmentId, input: buildProjectThreadStartTurnInput({ @@ -1196,6 +1206,11 @@ export function createThreadOutboxDelivery(): { acknowledgedExistingThreadMessageIds.delete(messageId); } } + for (const messageId of launchedCreations.keys()) { + if (!queuedMessageIds.has(messageId)) { + launchedCreations.delete(messageId); + } + } for (const [messageId, release] of familyMounts) { if (!queuedMessageIds.has(messageId)) { release(); @@ -1290,9 +1305,13 @@ export function createThreadOutboxDelivery(): { ); } } + const resendLaunch = + creation !== undefined && + launchedCreations.get(messageId)?.revision === threadOutboxRevision(messageId); const deliveryAction = resolveThreadOutboxDeliveryAction({ isCreation: creation !== undefined, - threadExists: thread !== undefined, + // A resend goes through the same gates as the first launch. + threadExists: thread !== undefined && !resendLaunch, shellStatus, environmentConnected: environment?.connectionState === "connected", ...(familyRead === undefined ? {} : { familyRead }), @@ -1387,7 +1406,7 @@ export function createThreadOutboxDelivery(): { ); const liveDeliveryAction = resolveThreadOutboxDeliveryAction({ isCreation: creation !== undefined, - threadExists: liveThread !== undefined, + threadExists: liveThread !== undefined && !resendLaunch, shellStatus, environmentConnected: environment?.connectionState === "connected", }); @@ -1397,7 +1416,7 @@ export function createThreadOutboxDelivery(): { } return deliveryAction === "remove" ? creation !== undefined - ? // After restart, always recover delivered creations; lost in-memory state cannot distinguish edits from duplicate payloads. + ? // Edited since launch, or launched before a restart that lost the revision: hand it back. recoverEditedCreationAfterDelivery(nextQueuedMessage) : removeQueuedMessage("[thread-outbox] failed to remove message for a missing thread") : creation !== undefined diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts index 087d9039c4ac2..0e0b8b62da275 100644 --- a/apps/mobile/src/state/use-composer-drafts.test.ts +++ b/apps/mobile/src/state/use-composer-drafts.test.ts @@ -1923,7 +1923,7 @@ describe("mobile composer drafts", () => { expect(getComposerDraftSnapshot(second).text).toBe("second idea"); }); - it("retargets a new-task draft to another project without losing its text", () => { + it("retargets a new-task draft to another project, keeping only a pull request workspace", () => { const from = { environmentId: EnvironmentId.make("environment-1"), projectId: ProjectId.make("project-1"), @@ -1944,7 +1944,7 @@ describe("mobile composer drafts", () => { }); const createdAt = getComposerDraftSnapshot(key).project?.createdAt; - retargetNewTaskDraft(key, to); + retargetNewTaskDraft(key, to, { keepPullRequestWorkspace: true }); const moved = getComposerDraftSnapshot(key); expect(moved.text).toBe("moving house"); @@ -1954,6 +1954,22 @@ describe("mobile composer drafts", () => { expect(moved.project).toEqual({ ...to, createdAt }); expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), from)).toEqual([]); expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), to)).toEqual([key]); + + const pullRequestSelection = { + mode: "worktree" as const, + branch: "feature/pr-head", + worktreePath: "/old-machine/worktrees/pr-42", + startFromOrigin: false, + pullRequestReference: "https://github.com/acme/repo/pull/42", + }; + updateComposerDraftSettings(key, { workspaceSelection: pullRequestSelection }); + retargetNewTaskDraft(key, from, { keepPullRequestWorkspace: true }); + expect(getComposerDraftSnapshot(key).workspaceSelection).toEqual({ + ...pullRequestSelection, + worktreePath: null, + }); + retargetNewTaskDraft(key, to); + expect(getComposerDraftSnapshot(key).workspaceSelection).toBeUndefined(); }); it("retargets a saved new-task draft only after drafts load", async () => { diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts index c6804afcde8cc..0f195cf213f06 100644 --- a/apps/mobile/src/state/use-composer-drafts.ts +++ b/apps/mobile/src/state/use-composer-drafts.ts @@ -2041,10 +2041,8 @@ export function createNewTaskDraft(project: { } export function retargetNewTaskDraft( draftKey: string, - project: { - readonly environmentId: EnvironmentId; - readonly projectId: ProjectId; - }, + project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }, + options?: { readonly keepPullRequestWorkspace?: boolean }, ): void { updateComposerDrafts((current) => { const existing = current[draftKey]; @@ -2056,7 +2054,12 @@ export function retargetNewTaskDraft( ) { return current; } - const { workspaceSelection: _workspaceSelection, ...retained } = normalizeDraft(existing); + const { workspaceSelection, ...retained } = normalizeDraft(existing); + // The PR checkout is recreated on the target machine, so only the old local path is dropped. + const keptWorkspaceSelection = + options?.keepPullRequestWorkspace && workspaceSelection?.pullRequestReference !== undefined + ? { ...workspaceSelection, worktreePath: null } + : undefined; // Keep bytes across environment moves but drop server-specific upload stamps. const attachments = retained.attachments.map((attachment) => attachment.uploadEnvironmentId !== undefined && @@ -2068,6 +2071,7 @@ export function retargetNewTaskDraft( ...current, [draftKey]: { ...retained, + ...(keptWorkspaceSelection ? { workspaceSelection: keptWorkspaceSelection } : {}), attachments, project: { environmentId: project.environmentId, diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index c75456461bf64..a1488220d6952 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -100,7 +100,7 @@ const EMPTY_RUNTIME_STATE_ATOM = Atom.make(null) Atom.withLabel("mobile:environment-runtime-state:empty"), ); -const savedConnectionsByIdAtom = Atom.make((get) => { +export const savedConnectionsByIdAtom = Atom.make((get) => { const catalog = get(environmentCatalog.catalogValueAtom); return Object.fromEntries( [...catalog.entries.keys()].flatMap((environmentId) => { diff --git a/apps/mobile/src/state/use-terminal-session.ts b/apps/mobile/src/state/use-terminal-session.ts index 34567cc2b2c6b..a01f1e9d82da8 100644 --- a/apps/mobile/src/state/use-terminal-session.ts +++ b/apps/mobile/src/state/use-terminal-session.ts @@ -2,7 +2,7 @@ import { combineTerminalSessionState, EMPTY_TERMINAL_BUFFER_STATE, EMPTY_TERMINAL_SESSION_STATE, - terminalOutputText, + terminalOutputReplay, type KnownTerminalSession, type TerminalSessionState, } from "@t3tools/client-runtime/state/terminal"; @@ -57,8 +57,8 @@ export function useAttachedTerminalSession(input: { ); const output = attach.data?.output ?? EMPTY_TERMINAL_BUFFER_STATE.output; const materializeBuffer = input.materializeBuffer ?? true; - // Older installed binaries and the text fallback still need initialBuffer. - const buffer = materializeBuffer ? terminalOutputText(output) : ""; + // Older installed binaries are fed this as initialBuffer; clearing it would recreate their emulator. + const buffer = materializeBuffer ? terminalOutputReplay(output) : ""; return useMemo(() => { if (input.environmentId === null || input.terminal === null) { diff --git a/apps/server/src/auth/dpop.ts b/apps/server/src/auth/dpop.ts index 7cae6bee393c9..1793e87d00a48 100644 --- a/apps/server/src/auth/dpop.ts +++ b/apps/server/src/auth/dpop.ts @@ -53,7 +53,8 @@ export const mapDpopReplayStoreError = ( cause: error, }); -export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* (input: { +/** Checks a proof without recording it; `consume` records its jti so it cannot be replayed. */ +export const checkRequestDpopProof = Effect.fn("dpop.checkRequestDpopProof")(function* (input: { readonly request: HttpServerRequest.HttpServerRequest; /** Overrides the `DPoP` header for requests that cannot carry one, such as a WebSocket upgrade. */ readonly proof?: string; @@ -86,42 +87,53 @@ export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(f }); } const secretStore = yield* ServerSecretStore.ServerSecretStore; - const replayKey = yield* Digest.Digest.pipe( - Effect.flatMap((digest) => - digest.digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)), - ), - Effect.map(Base64Url.encode), - Effect.mapError( - (cause) => - new ServerAuthDpopReplayKeyCalculationError({ - cause, - }), - ), - ); - yield* secretStore - .create( - `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`, - new TextEncoder().encode( - [ - `thumbprint=${result.thumbprint}`, - `jti=${result.jti}`, - `iat=${result.iat}`, - `consumedAt=${DateTime.formatIso(now)}`, - ].join("\n"), - ), - ) - .pipe( - Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) => - Effect.gen(function* () { - const mapped = mapDpopReplayStoreError(error); - if (mapped._tag === "ServerAuthInvalidCredentialError") { - yield* Effect.annotateCurrentSpan({ - "environment.dpop.failure_code": mapped.dpopFailureReason, - }); - } - return yield* mapped; - }), - ), - ); - return result.thumbprint; + const digest = yield* Digest.Digest; + const consume: Effect.Effect = + Effect.gen(function* () { + const replayKey = yield* digest + .digest(Digest.sha256, new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)) + .pipe( + Effect.map(Base64Url.encode), + Effect.mapError( + (cause) => + new ServerAuthDpopReplayKeyCalculationError({ + cause, + }), + ), + ); + yield* secretStore + .create( + `${DPOP_REPLAY_MARKER_PREFIX}${replayKey}`, + new TextEncoder().encode( + [ + `thumbprint=${result.thumbprint}`, + `jti=${result.jti}`, + `iat=${result.iat}`, + `consumedAt=${DateTime.formatIso(now)}`, + ].join("\n"), + ), + ) + .pipe( + Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) => + Effect.gen(function* () { + const mapped = mapDpopReplayStoreError(error); + if (mapped._tag === "ServerAuthInvalidCredentialError") { + yield* Effect.annotateCurrentSpan({ + "environment.dpop.failure_code": mapped.dpopFailureReason, + }); + } + return yield* mapped; + }), + ), + ); + }); + return { thumbprint: result.thumbprint, consume }; +}); + +export const verifyRequestDpopProof = Effect.fn("dpop.verifyRequestDpopProof")(function* ( + input: Parameters[0], +) { + const proof = yield* checkRequestDpopProof(input); + yield* proof.consume; + return proof.thumbprint; }); diff --git a/apps/server/src/auth/http.test.ts b/apps/server/src/auth/http.test.ts index 14003a36b64d6..3a27fa9baba6b 100644 --- a/apps/server/src/auth/http.test.ts +++ b/apps/server/src/auth/http.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -23,6 +24,7 @@ import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as EnvironmentAuth from "./EnvironmentAuth.ts"; +import { makeDpopKey } from "./dpop.testkit.ts"; import * as ServerSecretStore from "./ServerSecretStore.ts"; import * as AuthHttp from "./http.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; @@ -191,3 +193,63 @@ it.effect.each(["DPoP", "dpop"])("challenges a refused %s request with DPoP", (s ); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + +// The web handler runs on its own runtime, so proofs need wall-clock time. +it.live("checks token-endpoint DPoP proofs without writing replay state", () => + Effect.gen(function* () { + const random = yield* SecureRandom.SecureRandom; + const written: Array = []; + const recordingSecretStore = ServerSecretStore.ServerSecretStore.of({ + get: () => Effect.succeedNone, + set: () => Effect.void, + create: (name) => Effect.sync(() => void written.push(name)), + getOrCreateRandom: () => Effect.die("Not used by these routes."), + remove: () => Effect.void, + }); + const requestContext = Context.make(SecureRandom.SecureRandom, random).pipe( + Context.add(ServerSecretStore.ServerSecretStore, recordingSecretStore), + ); + const url = "http://127.0.0.1/oauth/token"; + const key = makeDpopKey(); + const iat = Math.floor((yield* DateTime.now).epochMilliseconds / 1_000); + const tokenRequest = (subjectToken: string, proof: string) => + new Request(url, { + method: "POST", + headers: { host: "127.0.0.1", dpop: proof }, + body: new URLSearchParams({ + grant_type: AuthTokenExchangeGrantType, + subject_token: subjectToken, + subject_token_type: AuthEnvironmentBootstrapTokenType, + requested_token_type: AuthAccessTokenType, + }), + }); + return yield* Effect.acquireUseRelease( + Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })), + (environment) => + Effect.promise(async () => { + const unknownToken = await environment.handler( + tokenRequest("not-a-pairing-token", key.sign({ method: "POST", url, token: "", iat })), + requestContext, + ); + expect(unknownToken.status).toBe(401); + expect(await unknownToken.json()).not.toHaveProperty("dpopFailureReason"); + + const accepted = await environment.handler( + tokenRequest(DEV_TOKEN, key.sign({ method: "POST", url, token: "", iat })), + requestContext, + ); + expect(accepted.status).toBe(200); + expect(await accepted.json()).toMatchObject({ token_type: "DPoP" }); + + const badProof = await environment.handler( + tokenRequest(DEV_TOKEN, "not-a-proof"), + requestContext, + ); + expect(badProof.status).toBe(401); + expect(badProof.headers.get("www-authenticate")).toBe("DPoP"); + expect(written).toEqual([]); + }), + (environment) => Effect.promise(() => environment.dispose()), + ); + }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts index c2a99533fb147..a25242aaff89f 100644 --- a/apps/server/src/auth/http.ts +++ b/apps/server/src/auth/http.ts @@ -36,7 +36,7 @@ import * as EnvironmentAuth from "./EnvironmentAuth.ts"; import * as SessionStore from "./SessionStore.ts"; import { traceAuthenticatedRelayRequest, traceRelayRequest } from "../cloud/traceRelayRequest.ts"; import { deriveAuthClientMetadata } from "./utils.ts"; -import { verifyRequestDpopProof } from "./dpop.ts"; +import { checkRequestDpopProof } from "./dpop.ts"; import { requestUrl } from "../requestUrl.ts"; const CREDENTIAL_RESPONSE_HEADERS = { @@ -364,8 +364,10 @@ export const layer = HttpApiBuilder.group( if (requestedScopes === null || requestedScopes?.length === 0) { return yield* failEnvironmentInvalidRequest("invalid_scope"); } - const proofKeyThumbprint = args.headers.dpop - ? yield* verifyRequestDpopProof({ request }).pipe( + // Not recorded: a replayer also holds the subject token and could sign its own proof. + // Recording would let anyone write replay state to disk. + const proof = args.headers.dpop + ? yield* checkRequestDpopProof({ request }).pipe( Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) => appendDpopChallengeHeader.pipe( Effect.andThen( @@ -395,7 +397,7 @@ export const layer = HttpApiBuilder.group( ...(args.payload.client_os ? { os: args.payload.client_os } : {}), }, }), - proofKeyThumbprint ? { proofKeyThumbprint } : undefined, + proof ? { proofKeyThumbprint: proof.thumbprint } : undefined, ); }, traceRelayRequest, diff --git a/apps/server/src/checkpointing/CheckpointStore.test.ts b/apps/server/src/checkpointing/CheckpointStore.test.ts index 62c764b537a80..15fa9205dee21 100644 --- a/apps/server/src/checkpointing/CheckpointStore.test.ts +++ b/apps/server/src/checkpointing/CheckpointStore.test.ts @@ -546,6 +546,123 @@ it.layer(layerTest)("CheckpointStore.layer", (it) => { }), ); + it.effect("leaves out fetched commits newer than the checkpoint, keeping local ones", () => + Effect.gen(function* () { + const root = yield* makeTmpDir(); + const upstream = NodePath.join(root, "upstream"); + const primary = NodePath.join(root, "primary"); + const cwd = NodePath.join(root, "turn"); + yield* (yield* FileSystem.FileSystem).makeDirectory(upstream); + yield* initRepoWithCommit(upstream); + yield* git(root, ["clone", upstream, primary]); + yield* git(primary, ["config", "user.email", "test@test.com"]); + yield* git(primary, ["config", "user.name", "Test"]); + yield* git(primary, ["worktree", "add", cwd, "-b", "turn"]); + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const threadId = ThreadId.make("checkpoint-authored-paths-fetched"); + const refs = { + cwd, + fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0), + toCheckpointRef: checkpointRefForThreadTurn(threadId, 1), + }; + yield* checkpointStore.captureCheckpoint({ cwd, checkpointRef: refs.fromCheckpointRef }); + + const commitFile = (repo: string, file: string) => + Effect.gen(function* () { + yield* writeTextFile(NodePath.join(repo, file), `${file}\n`); + yield* git(repo, ["add", "."]); + yield* git(repo, ["commit", "-m", file]); + }); + + yield* git(upstream, ["checkout", "-b", "release"]); + yield* commitFile(upstream, "first.txt"); + yield* git(cwd, ["fetch", "origin"]); + yield* commitFile(upstream, "second.txt"); + // The primary worktree's HEAD reflog is the only record that this commit was made here. + yield* git(primary, ["checkout", "--detach"]); + yield* commitFile(primary, "own.txt"); + yield* git(primary, ["push", "origin", "HEAD:refs/heads/pushed"]); + yield* git(upstream, ["merge", "pushed", "--no-edit"]); + + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["merge", "--ff-only", "origin/release"]); + yield* commitFile(cwd, "local.txt"); + // Pushing imported commits to another branch must not make them look local. + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/mirror"]); + yield* checkpointStore.captureCheckpoint({ cwd, checkpointRef: refs.toCheckpointRef }); + + expect(yield* checkpointStore.listAuthoredPaths(refs)).toEqual( + new Set(["local.txt", "own.txt"]), + ); + }), + ); + + it.effect.each([{ committed: "before the turn" }, { committed: "during the turn" }])( + "starts a turn that switched branches from the branch it landed on (committed $committed)", + ({ committed }) => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const checkpointStore = yield* CheckpointStore.CheckpointStore; + const threadId = ThreadId.make("checkpoint-branch-switch"); + const [first, second, third] = [0, 1, 2].map((turn) => + checkpointRefForThreadTurn(threadId, turn), + ) as [CheckpointRef, CheckpointRef, CheckpointRef]; + const changedSince = (fromCheckpointRef: CheckpointRef, toCheckpointRef: CheckpointRef) => + Effect.gen(function* () { + const refs = { cwd: tmp, fromCheckpointRef, toCheckpointRef }; + return { + patch: yield* checkpointStore.diffCheckpoints({ ...refs, ignoreWhitespace: false }), + authored: yield* checkpointStore.listAuthoredPaths(refs), + }; + }); + const commitOnA = git(tmp, ["commit", "-am", "work on a"]); + + yield* git(tmp, ["branch", "b"]); + yield* git(tmp, ["checkout", "-b", "a"]); + yield* writeTextFile(NodePath.join(tmp, "a.txt"), "a\n"); + yield* writeTextFile(NodePath.join(tmp, "README.md"), "# on a\n"); + yield* git(tmp, ["add", "."]); + if (committed === "before the turn") yield* commitOnA; + yield* checkpointStore.captureCheckpoint({ cwd: tmp, checkpointRef: first }); + + if (committed === "during the turn") yield* commitOnA; + yield* git(tmp, ["checkout", "b"]); + yield* writeTextFile(NodePath.join(tmp, "README.md"), "# on b\n"); + yield* writeTextFile(NodePath.join(tmp, "b.txt"), "b\n"); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: second, + previousCheckpointRef: first, + }); + + const switched = yield* changedSince(first, second); + expect(switched.patch).not.toContain("a.txt"); + expect(switched.patch).toContain("-# test\n+# on b\n"); + expect(switched.patch).toContain("b/b.txt"); + expect(switched.authored).toBeNull(); + + // A reset also moves HEAD off a commit, and what it removed is the turn's doing. + yield* git(tmp, ["add", "."]); + yield* git(tmp, ["commit", "-m", "work on b"]); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: second, + previousCheckpointRef: first, + }); + yield* git(tmp, ["reset", "--hard", "HEAD~1"]); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: third, + previousCheckpointRef: second, + }); + + const reset = yield* changedSince(second, third); + expect(reset.patch).toContain("--- a/b.txt\n+++ /dev/null"); + expect(reset.authored).toEqual(new Set(["README.md", "b.txt"])); + }), + ); + it.effect("keeps paths from signed commits under log.showSignature", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); diff --git a/apps/server/src/checkpointing/CheckpointStore.ts b/apps/server/src/checkpointing/CheckpointStore.ts index e5d3006568a67..8eadf2b5342af 100644 --- a/apps/server/src/checkpointing/CheckpointStore.ts +++ b/apps/server/src/checkpointing/CheckpointStore.ts @@ -10,6 +10,8 @@ import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; export interface CaptureCheckpointInput { readonly cwd: string; readonly checkpointRef: CheckpointRef; + /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */ + readonly previousCheckpointRef?: CheckpointRef; } export interface RestoreCheckpointInput { diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index a521f7a85f3a6..0a5c16cff7847 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -219,6 +219,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( lingerStartsManager: boolean; enabled: boolean; active: boolean; + /** systemd refuses starts until `reset-failed`, as after `StartLimitBurst` trips. */ + startLimitHit: boolean; /** A Windows launcher: it holds its lock until its task ends. */ launcher?: { readonly close: () => void }; /** Task Scheduler's own copy of the task. */ @@ -233,6 +235,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( lingerStartsManager: true, enabled: true, active: true, + startLimitHit: false, }; const runner = ProcessRunner.ProcessRunner.of({ run: Effect.fn("test.run_boot_service_command")(function* ( @@ -245,7 +248,12 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( if (control.executeLauncher && input.command === desktopLauncherPath) { return yield* realRunner.run(input); } - const failed = command === control.failCommand; + if (command === "systemctl --user reset-failed t3code.service") control.startLimitHit = false; + const refusedStart = control.startLimitHit && command.startsWith("systemctl --user restart "); + // `--no-block` only queues the job, so systemd reports success even when it refuses it. + const failed = + command === control.failCommand || + (refusedStart && command === "systemctl --user restart t3code.service"); if (!failed && command.startsWith("loginctl enable-linger --no-ask-password ")) { control.linger = "yes"; control.managerReachable ||= control.lingerStartsManager; @@ -264,7 +272,8 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( if (input.args[0] === "/Delete") delete control.task; if (input.args[0] === "/End") control.launcher?.close(); } - if (!failed && command === "systemctl --user restart t3code.service") control.active = true; + if (!refusedStart && !failed && command.startsWith("systemctl --user restart ")) + control.active = true; // The manager loads units only from its own unit directory. const unitOutsideManager = command === "systemctl --user enable t3code.service" && @@ -1088,7 +1097,11 @@ it.layer(NodeServices.layer)("boot service install", (it) => { ), ).toEqual( platform === "linux" - ? ["systemctl --user stop t3code.service", "systemctl --user restart t3code.service"] + ? [ + "systemctl --user stop t3code.service", + "systemctl --user reset-failed t3code.service", + "systemctl --user restart t3code.service", + ] : [ "launchctl bootout --wait gui/501/com.t3tools.t3code.service", `launchctl bootstrap gui/501 ${plan.unitPath}`, @@ -1417,6 +1430,7 @@ process.disconnect(); "systemctl --user is-active t3code.service", "systemctl --user stop t3code.service", "repair", + "systemctl --user reset-failed t3code.service", "systemctl --user restart t3code.service", ]); expect(control.active).toBe(true); @@ -1487,6 +1501,7 @@ process.disconnect(); ).toEqual([ "systemctl --user stop t3code.service", "systemctl --user daemon-reload", + "systemctl --user reset-failed t3code.service", "systemctl --user restart t3code.service", ]); }), @@ -1585,6 +1600,7 @@ process.disconnect(); expect(commands).toEqual([ "systemctl --user daemon-reload", "systemctl --user enable t3code.service", + "systemctl --user reset-failed t3code.service", "systemctl --user restart --no-block t3code.service", ]); expect(outcome).toBe("queued"); @@ -1594,6 +1610,25 @@ process.disconnect(); }), ); + // regression: #36319 + it.effect("starts a service whose systemd start limit tripped after repairing it", () => + Effect.gen(function* () { + const { service, control, makeService } = yield* makeHarness(); + yield* service.install(); + control.active = false; + control.startLimitHit = true; + + yield* service.install(); + expect(control.active).toBe(true); + + control.active = false; + control.startLimitHit = true; + const inside = yield* makeService(undefined, "1.2.3", undefined, false, undefined, true); + expect(yield* inside.restart).toBe("queued"); + expect(control.active).toBe(true); + }), + ); + it.effect("restarts an installed service when repair fails", () => Effect.gen(function* () { const { service, commands, control } = yield* makeHarness(); @@ -1610,6 +1645,7 @@ process.disconnect(); ).toEqual([ "systemctl --user stop t3code.service", "systemctl --user daemon-reload", + "systemctl --user reset-failed t3code.service", "systemctl --user restart t3code.service", ]); }), @@ -1643,6 +1679,7 @@ process.disconnect(); ), ).toEqual([ "systemctl --user stop t3code.service", + "systemctl --user reset-failed t3code.service", "systemctl --user restart t3code.service", ]); } diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index 65de3fe5a5e36..be4587426a9f6 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -318,6 +318,13 @@ function systemdManager(input: { readonly unitDir: string; }): BootServiceManager { const unitPath = input.path.join(input.unitDir, BOOT_SERVICE_UNIT_FILE); + // Once StartLimitBurst trips, systemd refuses every start until the failed state is cleared. + const resetFailed = { + step: "clearing the service's failed state", + optional: true, + command: "systemctl", + args: ["--user", "reset-failed", BOOT_SERVICE_UNIT_FILE], + }; const prepareActivation = [ { step: "reloading systemd user units", @@ -329,6 +336,7 @@ function systemdManager(input: { command: "systemctl", args: ["--user", "enable", BOOT_SERVICE_UNIT_FILE], }, + resetFailed, ]; return { kind: "systemd", @@ -351,6 +359,7 @@ function systemdManager(input: { }, ], restart: [ + resetFailed, { step: "restarting the service after a failed update", command: "systemctl", diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts index e133b4f9db36c..5f7cef54f5277 100644 --- a/apps/server/src/device/LocalDeviceHost.test.ts +++ b/apps/server/src/device/LocalDeviceHost.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "@effect/vitest"; import * as NodePath from "@effect/platform-node/NodePath"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -45,7 +47,8 @@ const agentFixture = Effect.fn("agentFixture")(function* ( const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-agent-start-" }); - const hub = { running: true, spawnFails: false }; + const hub = { running: true, spawnFails: false, cleanup: Effect.void }; + const daemonStopRequested = yield* Deferred.make>(); const stateDir = agentDeviceStateDir(path, path.join(baseDir, "userdata")); const daemonHealthy = yield* Ref.make(true); const runs: Array = []; @@ -80,20 +83,22 @@ const agentFixture = Effect.fn("agentFixture")(function* ( description: "Hub entry missing", }), ) - : Effect.succeed( - ChildProcessSpawner.makeHandle({ - pid: ChildProcessSpawner.ProcessId(123), - stdout: Stream.empty, - stderr: Stream.empty, - all: Stream.empty, - exitCode: Effect.never, - isRunning: Effect.sync(() => hub.running), - kill: () => Effect.void, - stdin: Sink.drain, - getInputFd: () => Sink.drain, - getOutputFd: () => Stream.empty, - unref: Effect.succeed(Effect.void), - }), + : Effect.addFinalizer(() => hub.cleanup).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(123), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.never, + isRunning: Effect.sync(() => hub.running), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), ), ), ), @@ -102,7 +107,9 @@ const agentFixture = Effect.fn("agentFixture")(function* ( runs.push(input); return input.args.includes("devices") ? startup(stateDir) - : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)); + : input.args.includes("daemon") + ? Deferred.succeed(daemonStopRequested, input.args).pipe(Effect.as(processOutput(0))) + : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)); }, }), Effect.provideService( @@ -122,7 +129,7 @@ const agentFixture = Effect.fn("agentFixture")(function* ( ), ); yield* host.ensureReady(() => Effect.void); - return { host, fs, baseDir, stateDir, hub, daemonHealthy, runs }; + return { host, fs, baseDir, stateDir, hub, daemonHealthy, daemonStopRequested, runs }; }); describe("AgentDevice startup", () => { @@ -353,6 +360,33 @@ describe("AgentDevice startup", () => { expect(yield* fs.exists(path.join(stateDir, "daemon.json"))).toBe(false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.effect("stops the agent daemon while the hub is still shutting down", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { host, hub, stateDir, daemonStopRequested } = yield* agentFixture((stateDir) => + fs + .writeFileString( + `${stateDir}/daemon.json`, + JSON.stringify({ httpPort: 12345, token: "test-token" }), + ) + .pipe(Effect.orDie, Effect.as(processOutput(0))), + ); + yield* host.ensureAgentReady(() => Effect.void); + const hubExited = yield* Deferred.make(); + hub.cleanup = Deferred.await(hubExited); + const stopping = yield* Effect.forkChild(host.stop); + expect((yield* Deferred.await(daemonStopRequested)).slice(1)).toEqual([ + "daemon", + "stop", + "--state-dir", + stateDir, + ]); + yield* Deferred.succeed(hubExited, undefined); + yield* Fiber.join(stopping); + expect(yield* fs.exists(`${stateDir}/hub.json`)).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); const diagnose = ( diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index c5097509dcade..e657d0dcdfc13 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -870,9 +870,16 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const stop: DeviceHost.DeviceHost["Service"]["stop"] = startLock.withPermits(1)( Effect.gen(function* () { const running = yield* Ref.getAndSet(runningRef, null); - yield* stopHub(running?.hub); - yield* fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore); - yield* stopAgentDeviceDaemon; + // Hub cleanup waits for its exit unbounded; it must not strand the detached agent daemon. + yield* Effect.all( + [ + stopHub(running?.hub).pipe( + Effect.andThen(fs.remove(hubStatePath(), { force: true }).pipe(Effect.ignore)), + ), + stopAgentDeviceDaemon, + ], + { concurrency: "unbounded", discard: true }, + ); }), ); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index e1ea941b360f1..9645b69d72ad4 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -275,6 +275,7 @@ export const make = Effect.gen(function* () { projectCloneTracking: true, projectOrganization: true, ignoredFileListing: true, + ignoredFileSearch: true, triage: true, oneTimeSchedules: true, freshContext: true, diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 04d825385edbb..d3e0d49bdbe53 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -2606,6 +2606,91 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("branch PR lookup in a fork checkout follows the branch's own published ref", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const forkDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", forkDir]); + yield* runGit(repoDir, [ + "remote", + "add", + "upstream", + "git@github.com:pingdotgg/codething-mvp.git", + ]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["remote", "set-head", "origin", "main"]); + // What a new worktree thread gets: its start point as upstream, nothing published. + yield* runGit(repoDir, ["branch", "--track", "t3code/new-thread", "origin/main"]); + yield* runGit(repoDir, ["branch", "--track", "feature/published", "origin/main"]); + yield* runGit(repoDir, ["branch", "--track", "t3code/pr-300/main", "origin/main"]); + yield* runGit(repoDir, ["push", "origin", "feature/published"]); + yield* configureVisibleRemoteUrlWithLocalRewrite( + repoDir, + "origin", + "git@github.com:contributor/codething-mvp.git", + forkDir, + ); + + const forkPullRequest = { + baseRefName: "main", + isCrossRepository: true, + headRepositoryNameWithOwner: "contributor/codething-mvp", + headRepositoryOwnerLogin: "contributor", + } as const; + const { service, calls } = createFakeSourceControlProvider({ + prListByHeadSelector: { + "contributor:main": [ + { + ...forkPullRequest, + number: 300, + title: "Fork main", + url: "https://github.com/pingdotgg/codething-mvp/pull/300", + headRefName: "main", + state: "merged", + }, + ], + "feature/published": [ + { + ...forkPullRequest, + number: 224, + title: "Fork feature", + url: "https://github.com/pingdotgg/codething-mvp/pull/224", + headRefName: "feature/published", + state: "open", + }, + ], + }, + }); + const { manager } = yield* makeManager({ + sourceControlProvider: { + ...service, + createsChangeRequestsIn: ({ repository }) => + Effect.succeed(repository === "pingdotgg/codething-mvp"), + }, + }); + + const unpublished = yield* manager.branchPullRequest({ + cwd: repoDir, + branch: "t3code/new-thread", + }); + expect(unpublished).toBeNull(); + expect(listedSelectors(calls)).toEqual([]); + + const published = yield* manager.branchPullRequest({ + cwd: repoDir, + branch: "feature/published", + }); + expect(published?.number).toBe(224); + + const pullRequestWorktree = yield* manager.branchPullRequest({ + cwd: repoDir, + branch: "t3code/pr-300/main", + }); + expect(pullRequestWorktree?.number).toBe(300); + }), + ); + it.effect("branch PR lookup ignores the PR of a local branch the branch tracks", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index aa06c85ad420f..af56b1b65b511 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -272,6 +272,11 @@ function resolveHeadRepositoryNameWithOwner(pullRequest: PullRequestHeadRemoteIn return normalizeOptionalString(pullRequest.headRepositoryNameWithOwner); } +// Both names `resolvePullRequestWorktreeLocalBranchName` gives a fork pull request's branch. +function isPullRequestWorktreeLocalBranchName(branch: string): boolean { + return /^t3code[/-]pr-\d+[/-]/u.test(branch); +} + function resolvePullRequestWorktreeLocalBranchName( pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, localBranches: ReadonlySet, @@ -1848,7 +1853,12 @@ export const make = Effect.gen(function* () { }; } } - if (headContext.headBranch === details.branch || headContext.isCrossRepository) { + // A fork's default branch can be a PR head. When that fork is origin it is also where new + // branches start, so only a branch made for a pull request takes it as its head. + const tracksForkHead = + headContext.isCrossRepository && + (headContext.remoteName !== "origin" || isPullRequestWorktreeLocalBranchName(details.branch)); + if (headContext.headBranch === details.branch || tracksForkHead) { return { headContext, lookup: true }; } const upstreamHeadIsBase = diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts index 5f7df20c738c8..d03d7cb6f8daa 100644 --- a/apps/server/src/http.test.ts +++ b/apps/server/src/http.test.ts @@ -399,6 +399,8 @@ it.layer( expect(response.status).toBe(200); expect(yield* response.text).toBe(nextHtml); expect(response.headers["cache-control"]).toBe("no-cache"); + expect(response.headers["content-security-policy"]).toBe("frame-ancestors 'none'"); + expect(response.headers["x-frame-options"]).toBe("DENY"); expect(response.headers["etag"]).toBeUndefined(); expect(response.headers["last-modified"]).toBeUndefined(); } diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index ec717a32e423a..b18188f7de24c 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -569,6 +569,12 @@ const streamStaticFile = (file: FileSystem.File, size: bigint) => }), ); +// The app can approve agents and start threads in one click, so no other site may frame it. +const SPA_FRAME_HEADERS = { + "Content-Security-Policy": "frame-ancestors 'none'", + "X-Frame-Options": "DENY", +}; + const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( function* (immutableBuildAssets: ReadonlySet) { const request = yield* HttpServerRequest.HttpServerRequest; @@ -669,6 +675,7 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( }; const headers: Record = { "Cache-Control": cacheControl, + ...(isHtml ? SPA_FRAME_HEADERS : {}), ...validators(fileInfo), }; const etag = headers.ETag; @@ -705,6 +712,7 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")( return HttpServerResponse.uint8Array(bytes, { headers: { "Cache-Control": cacheControl, + ...(isHtml ? SPA_FRAME_HEADERS : {}), ...validators({ ...info, size: ByteSize.bytes(bytes.byteLength) }), }, contentType, diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index eaf54214ba07b..597e78d810084 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -84,6 +84,8 @@ import { DeviceStandardToolkit, } from "./toolkits/device/tools.ts"; import * as HtmlHandlers from "./toolkits/html/handlers.ts"; +import { MessageToolkit } from "./toolkits/message/tools.ts"; +import * as MessageHandlers from "./toolkits/message/handlers.ts"; import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts"; import { requestUrl } from "../requestUrl.ts"; @@ -1239,6 +1241,8 @@ export const layerOrchestratorToolkit = toolkitRegistration( export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer); +const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer); + const layerWorktreeToolkitRegistration = toolkitRegistration( WorktreeToolkit, WorktreeHandlers.layer, @@ -1324,6 +1328,7 @@ export const layerTools = Layer.mergeAll( layerPullRequestsToolkit, layerDeviceToolkit, layerHtmlToolkit, + layerMessageToolkit, ); const layerToolExposure = Layer.effect( diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c52716f2ba2d4..e3cbb4aca9417 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -101,7 +101,12 @@ import type { ProjectionRecordField, ProjectionRecordFilter, } from "../orchestration-v2/ProjectionStore.ts"; -import { delegatedTaskResultRun, runOutcome } from "../orchestration-v2/RestartBackgroundNote.ts"; +import { + delegatedTaskAwaitsSubagents, + delegatedTaskResultRun, + delegatedTaskRuns, + runOutcome, +} from "../orchestration-v2/RestartBackgroundNote.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; @@ -246,6 +251,7 @@ function threadManagementFailure(error: unknown): OrchestratorMcpFailure { return failure("run_not_found", error.message); case "ThreadManagementThreadArchivedError": case "ThreadManagementNoSteerableRunError": + case "ThreadManagementWorktreeRestoreError": return failure("thread_not_sendable", error.message); case "ThreadManagementThreadNotInterruptibleError": return failure("thread_not_interruptible", error.message); @@ -1625,16 +1631,18 @@ const make = Effect.gen(function* () { const childRun = delegatedTaskRun(childControls, task); const terminalRun = latestTerminalResultRun(childControls, childRun); const progress = delegatedTaskProgress(childControls); + const followupRuns = + childRun?.delegatedTaskId === task.id ? delegatedTaskRuns(childControls, task.id) : undefined; const taskResultRun = - childRun?.delegatedTaskId === task.id - ? delegatedTaskResultRun(childControls.runs, task.id) - : progress.resultRun; + followupRuns === undefined ? progress.resultRun : delegatedTaskResultRun(followupRuns); const taskWorkState = - childRun?.delegatedTaskId === task.id - ? isTerminalTaskStatus(taskStatusForRun(taskResultRun)) - ? "result_available" - : "working" - : progress.state; + followupRuns === undefined + ? progress.state + : !isTerminalTaskStatus(taskStatusForRun(taskResultRun)) + ? "working" + : delegatedTaskAwaitsSubagents(followupRuns, childControls.subagents) + ? "waiting_for_children" + : "result_available"; const resultRunIds = [ ...new Set( [taskResultRun?.id, terminalRun?.id].filter((id): id is RunId => id !== undefined), diff --git a/apps/server/src/mcp/PreviewAutomationBroker.test.ts b/apps/server/src/mcp/PreviewAutomationBroker.test.ts index e800570b8ba57..dac5153acee6b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.test.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.test.ts @@ -18,8 +18,10 @@ import { import * as Effect from "effect/Effect"; import * as Deferred from "effect/Deferred"; import * as Fiber from "effect/Fiber"; +import * as Queue from "effect/Queue"; import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { PreviewBrowserRootError } from "../preview/PreviewBrowserHost.ts"; import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts"; @@ -950,6 +952,54 @@ it.effect("fails requests assigned to the stream that is replaced", () => }), ); +it.effect( + "keeps another thread's request alive when one request times out on the shared server browser", + () => + Effect.gen(function* () { + const broker = yield* makeBroker; + const clientId = SERVER_BROWSER_AUTOMATION_CLIENT_ID; + const delivered = yield* Queue.unbounded(); + const requests = requestsFrom( + yield* broker.connect(makeHost({ clientId }), { preferred: true }), + ); + yield* Stream.runForEach(requests, (request) => Queue.offer(delivered, request)).pipe( + Effect.forkScoped, + ); + yield* Effect.yieldNow; + const otherScope = { + ...scope, + requestNamespace: "provider-session-2", + thread: { + threadId: ThreadId.make("thread-2"), + providerSessionId: "provider-session-2", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + }; + + const otherWait = yield* broker + .invoke({ scope: otherScope, operation: "waitFor", input: {}, timeoutMs: 40_000 }) + .pipe(Effect.result, Effect.forkScoped); + const otherRequest = yield* Queue.take(delivered); + // The browser never answers this one, as when it waits behind the thread's own running action. + const stalled = yield* broker + .invoke({ scope, operation: "evaluate", input: {} }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Queue.take(delivered); + + yield* TestClock.adjust("16 seconds"); + expect((yield* Fiber.join(stalled))._tag).toBe("PreviewAutomationTimeoutError"); + + yield* broker.respond({ + clientId, + connectionId: otherRequest.connectionId, + requestId: otherRequest.requestId, + ok: true, + result: "ready", + }); + expect(yield* Fiber.join(otherWait)).toEqual(Result.succeed("ready")); + }), +); + it.effect("accepts responses only from the host that received the request", () => Effect.gen(function* () { const broker = yield* makeBroker; diff --git a/apps/server/src/mcp/PreviewAutomationBroker.ts b/apps/server/src/mcp/PreviewAutomationBroker.ts index 85646d387160d..073cecced051b 100644 --- a/apps/server/src/mcp/PreviewAutomationBroker.ts +++ b/apps/server/src/mcp/PreviewAutomationBroker.ts @@ -662,7 +662,11 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() { // The enclosing operation owns the span for this inline handler. onNone: Effect.fnUntraced(function* () { // Never replay possibly applied actions; slow metadata reads must not evict the host. - if (input.updateCurrentTab !== false) { + // The in-process server browser is shared by every thread and cannot hang its stream. + if ( + input.updateCurrentTab !== false && + connection.clientId !== SERVER_BROWSER_AUTOMATION_CLIENT_ID + ) { yield* disconnect(connection.clientId, connection.queue, true); } return yield* new PreviewAutomationTimeoutError(requestContext); diff --git a/apps/server/src/mcp/WorktreeMcpService.test.ts b/apps/server/src/mcp/WorktreeMcpService.test.ts index 90cf3c7f8401a..3dc7cc2bcc77a 100644 --- a/apps/server/src/mcp/WorktreeMcpService.test.ts +++ b/apps/server/src/mcp/WorktreeMcpService.test.ts @@ -106,7 +106,6 @@ interface HarnessOptions { readonly threadAttachedOnRecheck?: boolean; readonly threadArchivedOnRecheck?: boolean; readonly threadReadFailsOnRecheck?: boolean; - readonly continuation?: "queued" | "fails" | "dies"; readonly projectMissing?: boolean; readonly projectReadFails?: boolean; readonly existingBranchWorktreePath?: string | null; @@ -179,22 +178,6 @@ const makeHarness = (options: HarnessOptions = {}) => { ? Effect.succeed(makeProjection(thread)) : Effect.fail(new OrchestratorProjectionError({ threadId: id })); }); - const sendToThread = vi.fn((_: unknown) => { - switch (options.continuation ?? "queued") { - case "fails": - return Effect.fail( - new ThreadManagementService.ThreadManagementThreadArchivedError({ - threadId, - }), - ); - case "dies": - return Effect.die(new Error("send defect")); - default: - return Effect.succeed({ - delivery: "queued", - } as ThreadManagementService.ThreadManagementSendResult); - } - }); const getById = vi.fn((id: ProjectId) => options.projectReadFails ? (Effect.fail("simulated project read failure") as never) @@ -298,7 +281,6 @@ const makeHarness = (options: HarnessOptions = {}) => { Layer.mock(ThreadManagementService.ThreadManagementService)({ dispatch, getThreadRecords, - sendToThread, } satisfies Partial), Layer.mock(ProjectService.ProjectService)({ getById, @@ -355,7 +337,6 @@ const makeHarness = (options: HarnessOptions = {}) => { scope, listRefs, dispatch, - sendToThread, fetchWorktreeBaseCommit, createWorktree, removeWorktree, @@ -398,30 +379,23 @@ const runStatus = (harness: ReturnType) => const decodeHandoffInput = Schema.decodeUnknownEffect(WorktreeMcpHandoffInput); describe("t3_worktree_handoff", () => { - it.effect("reports a continuation failure without failing the handoff", () => { - const harness = makeHarness({ continuation: "fails" }); + // regression: #22971 a separate send let the detach settle the run before its follow-up existed + it.effect("commits the continuation with the thread binding", () => { + const harness = makeHarness(); return Effect.gen(function* () { const result = yield* runHandoff(harness, { - branch: "feature/continue-fails", + branch: "feature/continue", continuationPrompt: "Keep going.", }); - expect(result.continuation).toMatchObject({ status: "failed" }); - expect(result.worktreePath).toBe("/worktrees/project/feature/continue-fails"); - expect(harness.dispatch).toHaveBeenCalled(); - }); - }); - - it.effect("does not queue a continuation when the thread update fails", () => { - const harness = makeHarness({ dispatchFails: true }); - return Effect.gen(function* () { - const exit = yield* Effect.exit( - runHandoff(harness, { - branch: "feature/dispatch-fails-continue", - continuationPrompt: "Keep going.", + expect(result.continuation).toEqual({ status: "scheduled", delivery: "queued" }); + expect(harness.dispatch).toHaveBeenCalledTimes(1); + expect(harness.dispatch).toHaveBeenCalledWith( + expect.objectContaining({ + type: "thread.metadata.update", + worktreePath: "/worktrees/project/feature/continue", + continuation: expect.objectContaining({ text: "Keep going." }), }), ); - expectTypedFailure(exit, { _tag: "WorktreeMcpFailure", code: "operation_failed" }); - expect(harness.sendToThread).not.toHaveBeenCalled(); }); }); @@ -618,7 +592,7 @@ describe("t3_worktree_handoff", () => { }); }); - it.effect("queues the continuation even when interrupted during the binding dispatch", () => + it.effect("runs the setup script even when interrupted during the binding dispatch", () => Effect.gen(function* () { const gate = yield* Deferred.make(); const harness = makeHarness({ dispatchGate: Deferred.await(gate) }); @@ -637,7 +611,6 @@ describe("t3_worktree_handoff", () => { yield* Fiber.join(interruption); expect(harness.dispatch).toHaveBeenCalledTimes(1); - expect(harness.sendToThread).toHaveBeenCalledTimes(1); expect(harness.runForThread).toHaveBeenCalledTimes(1); }), ); diff --git a/apps/server/src/mcp/WorktreeMcpService.ts b/apps/server/src/mcp/WorktreeMcpService.ts index 0ee45bb7f8bb3..5d73b864d356b 100644 --- a/apps/server/src/mcp/WorktreeMcpService.ts +++ b/apps/server/src/mcp/WorktreeMcpService.ts @@ -147,7 +147,6 @@ const make = Effect.gen(function* () { ); return { commandId: CommandId.make(part("command", "worktree-handoff")), - continuationCommandId: CommandId.make(part("command", "worktree-continuation")), continuationMessageId: MessageId.make(part("message", "worktree-continuation")), }; }), @@ -293,7 +292,7 @@ const make = Effect.gen(function* () { `Thread '${scope.thread.threadId}' was archived while the worktree was being created; the handoff was rolled back.`, ); } - yield* threadManagement + return yield* threadManagement .dispatch({ type: "thread.metadata.update", commandId: ids.commandId, @@ -301,6 +300,15 @@ const make = Effect.gen(function* () { branch: worktree.worktree.refName, worktreePath, expectedWorktreePath: null, + // Binding detaches the session and ends the caller; a later send could lose the race. + ...(input.continuationPrompt === undefined + ? {} + : { + continuation: { + messageId: ids.continuationMessageId, + text: input.continuationPrompt, + }, + }), }) .pipe( Effect.catchCause((cause) => @@ -321,33 +329,18 @@ const make = Effect.gen(function* () { ), ); - // Queue continuation immediately after binding; detachment terminates the caller, so relaunch needs a durable message. - const queueContinuation: Effect.Effect = - Effect.suspend(() => - input.continuationPrompt === undefined - ? Effect.succeed({ status: "skipped" }) - : threadManagement - .sendToThread({ - projectId: projection.thread.projectId, - commandId: ids.continuationCommandId, - threadId: scope.thread.threadId, - messageId: ids.continuationMessageId, - text: input.continuationPrompt, - attachments: [], - mode: "queue", - createdBy: "agent", - creationSource: "mcp", - }) - .pipe( - Effect.map((sendResult): WorktreeMcpContinuationStatus => ({ - status: "scheduled", - delivery: sendResult.delivery, - })), - reportFailed("worktree handoff continuation failed to queue"), - ), - ); - - const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation)); + const bound = yield* recheckAndBind; + const continuation: WorktreeMcpContinuationStatus = + input.continuationPrompt === undefined + ? { status: "skipped" } + : { + status: "scheduled", + delivery: bound.storedEvents.some( + ({ event }) => event.type === "run.created" && event.payload.status !== "queued", + ) + ? "started" + : "queued", + }; yield* vcsStatusBroadcaster .refreshStatus(worktreePath) diff --git a/apps/server/src/mcp/toolkits/message/handlers.ts b/apps/server/src/mcp/toolkits/message/handlers.ts new file mode 100644 index 0000000000000..defe3609f08ca --- /dev/null +++ b/apps/server/src/mcp/toolkits/message/handlers.ts @@ -0,0 +1,15 @@ +import * as Effect from "effect/Effect"; + +import * as McpToolAccess from "../../McpToolAccess.ts"; +import { MessageToolkit } from "./tools.ts"; + +const handlers = { + send_to_user: McpToolAccess.actsAsCaller((input) => + Effect.succeed({ + sentMessage: input.message, + message: "Shown to the user. Don't repeat it.", + }), + ), +} satisfies McpToolAccess.Handlers; + +export const layer = McpToolAccess.toLayer(MessageToolkit, handlers); diff --git a/apps/server/src/mcp/toolkits/message/tools.ts b/apps/server/src/mcp/toolkits/message/tools.ts new file mode 100644 index 0000000000000..848cfa46976fb --- /dev/null +++ b/apps/server/src/mcp/toolkits/message/tools.ts @@ -0,0 +1,39 @@ +import { OrchestratorMcpFailure } from "@t3tools/contracts"; +import { SEND_TO_USER_MAX_LENGTH, SEND_TO_USER_TOOL_NAME } from "@t3tools/shared/toolOutput"; +import * as Schema from "effect/Schema"; +import { Tool, Toolkit } from "effect/ai"; + +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts"; +import * as McpInvocationContext from "../../McpInvocationContext.ts"; + +// Claude 5.1+ returns text written before a tool call only as a short summary; tool input arrives intact. +// It affects only the caller's thread, so read-only sandboxes and plan mode may use it. +const SendToUserTool = Tool.make(SEND_TO_USER_TOOL_NAME, { + description: + "Show the user a Markdown message in this thread, exactly as written, before your turn ends. Use it for content the user must read in full mid-turn, such as a draft, a code block, or what a question you are about to ask refers to. Don't repeat it in your reply.", + parameters: Schema.Struct({ + message: Schema.String.check( + Schema.isMinLength(1), + Schema.isMaxLength(SEND_TO_USER_MAX_LENGTH), + ).annotate({ description: "Markdown, shown verbatim." }), + }), + success: Schema.Struct({ + sentMessage: Schema.String, + message: Schema.String, + }), + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + McpInvocationContext.McpInvocationContext, + ThreadManagementService.ThreadManagementService, + ], +}) + .annotate(Tool.Title, "Send a message to the user") + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, false) + .annotate(Tool.OpenWorld, false) + // Claude Code defers MCP tools behind ToolSearch; Anthropic says to declare this from the first request. + .annotate(Tool.Meta, { "anthropic/alwaysLoad": true }); + +export const MessageToolkit = Toolkit.make(SendToUserTool); diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index b2ba460d0c8b7..6e649222854ba 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -788,6 +788,7 @@ it.effect("an agent's clone is not cut off while git is still transferring", () ), Layer.provide( Layer.mock(GitVcsDriver.GitVcsDriver)({ + invalidateRefs: () => Effect.void, // Like the real driver, the clone fails once it outlives the deadline it was given. execute: (input) => Deferred.succeed(started, undefined).pipe( diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 2ad7161cb630b..ddbfc575030f1 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -65,7 +65,7 @@ function worktreeCheckHint( } return `Pass a branch, tag, or commit that exists there${ strategy.startFromOrigin === true - ? "; the project has no usable remote to fetch it from." + ? "; no remote of the project has it either." : ", or set startFromOrigin:true if it exists only on a remote." }`; } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ca38b7af08f9a..ac2d9e039943d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -90,6 +90,7 @@ import { T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH } from "@t3tools/prov import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts"; import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts"; +import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts"; import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts"; import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts"; import { WorktreeToolkit } from "../../mcp/toolkits/worktree/tools.ts"; @@ -109,6 +110,7 @@ import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; import { ClaudeOrchestratorReplayHarness } from "./ClaudeAdapterV2.testkit.ts"; +import { withInlineContext } from "../ContextHandoffDelivery.ts"; import { provideDeterministicTestRuntime } from "../testkit/DeterministicRuntime.ts"; import { runOrchestratorV2Scenario } from "../testkit/OrchestratorScenario.ts"; import { layerProviderReplay } from "../testkit/ProviderReplayHarness.ts"; @@ -662,6 +664,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => { ...Object.values(EnvironmentToolkit.tools), ...Object.values(PreviewControlsToolkit.tools), ...Object.values(HtmlToolkit.tools), + ...Object.values(MessageToolkit.tools), ] .filter((tool) => Context.get(tool.annotations, Tool.Readonly)) .map((tool) => `mcp__t3-code__${tool.name}`) @@ -5540,6 +5543,55 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #34393 a provider switch replayed a $skill from the handoff history + it.effect("dispatches only skills from the user's text, not from inline handoff history", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const homePath = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-skill-handoff-" }); + const directory = path.join(homePath, "skills", "review"); + yield* fs.makeDirectory(directory, { recursive: true }); + yield* fs.writeFileString( + path.join(directory, "SKILL.md"), + "---\nname: review\n---\nFollow the review instructions.\n", + ); + const harness = yield* makeWakeHarnessWithOptions({ + settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath }, + }); + const history = "Context handoff:\n[Historical user; user_message]\n$review the diff"; + const text = withInlineContext(history, "continue"); + yield* harness.runtime.startTurn({ + ...makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("skill-handoff"), + text, + attachments: [], + runtimePolicy: { ...CLAUDE_TEST_RUNTIME_POLICY, cwd: homePath }, + }), + inlineContextLength: text.length - "continue".length, + }); + + const content = harness.offeredMessages[0]?.message.content; + const blocks = + typeof content === "string" + ? [content] + : (content ?? []).map((block) => (block.type === "text" ? block.text : "")); + assert.isFalse(blocks.some((text) => text.startsWith("/review"))); + assert.include(blocks.join("\n"), "$review the diff"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #15475 MCP title arriving after the tool starts must survive to completion it.effect.each([ { isError: false, title: "Check weather" }, @@ -11614,6 +11666,201 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // Claude 2.1.323 wakes a session per Monitor event with only init, assistant and a + // task-notification result; just the Monitor's end sends a task_notification frame. + it.effect.each([ + { monitorWake: "ends with its own result", laterWake: "ends with its own result" }, + { monitorWake: "ends with its own result", laterWake: "is absorbed by a user turn" }, + { monitorWake: "is absorbed by a user turn", laterWake: "is absorbed by a user turn" }, + ] as const)( + "tags a Claude Monitor event wake as a monitor update (it $monitorWake, later wake $laterWake)", + ({ monitorWake, laterWake }) => + Effect.gen(function* () { + const absorbed = laterWake === "is absorbed by a user turn"; + const monitorWakeAbsorbed = monitorWake === "is absorbed by a user turn"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + const taskId = "bi5kfx7xp"; + const toolUseId = "toolu_monitor_events"; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-monitor-event"), + text: "Watch the mutation run and report each survivor.", + attachments: [], + }), + ); + for (const frame of [ + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_monitor_events", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: toolUseId, + name: "Monitor", + input: { description: "line monitor", command: "./mutate.sh" }, + }, + ], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000901", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: taskId, + tool_use_id: toolUseId, + description: "line monitor", + is_backgrounded: true, + task_type: "local_bash", + uuid: "00000000-0000-4000-8000-000000000902", + session_id: WAKE_NATIVE_SESSION, + }), + claudeSdkFrame({ + type: "user", + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: toolUseId, + content: `Monitor started (task ${taskId}). You will be notified on each event.`, + }, + ], + }, + parent_tool_use_id: null, + uuid: "00000000-0000-4000-8000-000000000903", + session_id: WAKE_NATIVE_SESSION, + tool_use_result: { taskId, persistent: false }, + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000904", result: "STARTED" }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000905", + text: "Covered. Waiting for the rest.", + }), + ); + yield* harness.awaitContinuation(1); + + const notification = harness.continuationRequests[0]?.notification; + assert.deepEqual( + { source: notification?.source, outcome: notification?.outcome }, + { source: { kind: "monitor" }, outcome: "updated" }, + ); + + let settled = 1; + // Claude folds a prompt into the wake turn it already opened, so one result ends both. + const absorbWithUserTurn = Effect.fnUntraced(function* (result: SDKMessage) { + settled += 1; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-claude-monitor-event-user-${settled}`), + text: "Any survivors yet?", + attachments: [], + providerTurnOrdinal: settled, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === settled); + yield* Queue.offer(harness.sdkMessages, result); + yield* harness.awaitTerminal(settled); + }); + const monitorWakeResult = makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000906", + result: "Covered. Waiting for the rest.", + ...(monitorWakeAbsorbed ? {} : { origin: { kind: "task-notification" } as const }), + }); + if (monitorWakeAbsorbed) yield* absorbWithUserTurn(monitorWakeResult); + else yield* harness.offerAndWait(monitorWakeResult); + + // A wake buffered behind the queued Monitor continuation must not run under its tag. + for (const frame of [ + claudeSdkFrame({ + type: "system", + subtype: "init", + uuid: "00000000-0000-4000-8000-000000000907", + session_id: WAKE_NATIVE_SESSION, + }), + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000908", + text: "Scheduled answer.", + }), + ]) { + yield* harness.offerAndWait(frame); + } + const laterResult = makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000909", + result: absorbed ? "No survivors yet." : "Scheduled answer.", + }); + if (absorbed) yield* absorbWithUserTurn(laterResult); + else yield* harness.offerAndWait(laterResult); + const assistantTexts = () => + harness.events.flatMap((event) => + event.type === "message.updated" && event.message.role === "assistant" + ? [event.message.text] + : [], + ); + const startContinuation = (attempt: string, providerTurnOrdinal: number) => + harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(attempt), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* startContinuation("attempt-claude-monitor-event-2", settled + 1); + yield* harness.awaitTerminal(settled + 1); + assert.notInclude(assistantTexts(), "Scheduled answer."); + yield* harness.awaitContinuation(2); + // With no result of its own in the buffer, the later wake reads as another Monitor event. + assert.equal( + harness.continuationRequests[1]?.notification?.source.kind, + absorbed ? "monitor" : undefined, + ); + + yield* startContinuation("attempt-claude-monitor-event-3", settled + 2); + yield* harness.awaitTerminal(settled + 2); + assert.equal(harness.terminalEvents()[settled + 1]?.status, "completed"); + assert.include(assistantTexts(), "Scheduled answer."); + assert.lengthOf(harness.continuationRequests, 2); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + const scheduleWakeupFrames = (input: { readonly toolUseId: string; readonly uuids: readonly [string, string]; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 03bcff7ad9927..60e63c3edb3da 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -385,10 +385,13 @@ const CLAUDE_ROOT_REFUSAL = "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons"; // fd 4 gates the launch until the server has recorded the process it is about to become. +// The shell enters the cwd itself: as a native cwd, a mount that hangs chdir freezes the server. const CLAUDE_GROUP_WATCH_SCRIPT = [ "read -r _ <&4 || exit 1", "exec 4<&-", "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", + 'cd -P -- "$1" || exit 125', + "shift", 'exec "$@" 3<&-', ].join("\n"); @@ -405,11 +408,19 @@ export function spawnClaudeProcessGroup( onStderrClose: () => void = () => {}, register?: (pid: number) => () => void, ): ClaudeSpawnedProcess & Pick { + // Relative to the server's cwd, as a native cwd is; the `./` keeps CDPATH out of it. + const cwd = options.cwd ?? "."; const child = NodeChildProcess.spawn( "/bin/sh", - ["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args], + [ + "-c", + CLAUDE_GROUP_WATCH_SCRIPT, + "t3-claude", + cwd.startsWith("/") ? cwd : `./${cwd}`, + options.command, + ...options.args, + ], { - cwd: options.cwd, env: options.env, signal: options.signal, stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"], @@ -1965,6 +1976,14 @@ const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = ` To wait for a background command or Monitor you started (tests, a build), call \`t3_background_wait\` with its task ID before you end your turn. Do not mark work you leave running, or PRs. T3 MCP tools are deferred: load one with ToolSearch before you call it. `; +// Claude 5.1+ returns text written before a tool call as a progress update, which the API +// returns only as a summary. +const CLAUDE_SEND_TO_USER_INSTRUCTIONS = ` +### Text the user must read mid-turn + +Text you write before a tool call may reach the user only as a one-line summary. When the user must read something in full before your turn ends, such as a draft, a code block, or what a question you're about to ask refers to, send it with \`send_to_user\`. Put everything else in your final reply. +`; + // Native subagents start from their task, not this session's system prompt. const subagentDeviceInstructions: HookCallback = () => Promise.resolve({ @@ -2143,6 +2162,7 @@ export function makeClaudeQueryOptions(input: { ? "" : T3_CODE_ORCHESTRATION_INSTRUCTIONS + CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS + + CLAUDE_SEND_TO_USER_INSTRUCTIONS + (deviceInstructions ? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n` : "")), @@ -2263,6 +2283,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray = [ "mcp__t3-code__t3_environment_links", "mcp__t3-code__html_preview", "mcp__t3-code__html_render", + "mcp__t3-code__send_to_user", ]; // T3 waits can block for an hour; exceed Claude's default 60 s timeout. @@ -2642,12 +2663,15 @@ export function makeClaudeUserMessage(input: { readonly text: string; readonly priority?: SDKUserMessage["priority"]; readonly skills?: ReadonlyMap; + readonly skillMentionsFrom?: number; readonly uuid?: SDKUserMessage["uuid"]; }): SDKUserMessage { // Claude expands a skill only when `/name` starts the last text block. // Keep the whole request before that block; see ClaudeSkillDispatch. const dispatch = - input.skills === undefined ? undefined : planClaudeSkillDispatch(input.text, input.skills); + input.skills === undefined + ? undefined + : planClaudeSkillDispatch(input.text, input.skills, input.skillMentionsFrom); // Claude runs `/goal` only when it opens the prompt, so a goal stays one block. const isGoalCommand = parseGoalCommand({ text: input.text }) !== null; return { @@ -2812,11 +2836,15 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: readonly fileSystem: FileSystem.FileSystem; readonly pdfReservation: Effect.Success>; readonly skills?: ReadonlyMap; + readonly skillMentionsFrom?: number; }) { if (input.attachments.length === 0) { const message = makeClaudeUserMessage({ text: input.text, ...(input.skills === undefined ? {} : { skills: input.skills }), + ...(input.skillMentionsFrom === undefined + ? {} + : { skillMentionsFrom: input.skillMentionsFrom }), ...(input.priority === undefined ? {} : { priority: input.priority }), ...(input.uuid === undefined ? {} : { uuid: input.uuid }), }); @@ -2840,7 +2868,7 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: const dispatch = input.skills === undefined ? undefined - : planClaudeSkillDispatch(textWithAttachmentPaths, input.skills); + : planClaudeSkillDispatch(textWithAttachmentPaths, input.skills, input.skillMentionsFrom); const content: Array = []; // Base64 adds a third to the payload. Leave room below Anthropic's 32 MB // request limit for text, instructions, and SDK framing. The SDK does not @@ -5789,6 +5817,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const scheduledWakeupsByNativeThread = new Map(); // Native threads whose current turn Claude started by itself inside the early-fire margin. const possibleEarlyWakeNativeThreads = new Set(); + // Turn starts a due or nearly due ScheduleWakeup may have caused. + const possibleScheduledWakeStarts = new WeakSet(); + // A Monitor event wakes Claude with a bare turn and no task_notification frame, so the + // only evidence is a turn start while a Monitor runs that no ScheduleWakeup explains. + const monitorEventWakeStarts = new WeakSet(); const trackClaudeScheduledWakeup = Effect.fnUntraced(function* ( nativeThreadId: string, message: SDKMessage, @@ -5797,6 +5830,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const scheduledFor = scheduledWakeupsByNativeThread.get(nativeThreadId); if (scheduledFor === undefined) return; const now = DateTime.toEpochMillis(yield* DateTime.now); + if (now >= scheduledFor - CLAUDE_SCHEDULED_WAKEUP_EARLY_FIRE_MARGIN_MS) { + possibleScheduledWakeStarts.add(message); + } if (now >= scheduledFor) { scheduledWakeupsByNativeThread.delete(nativeThreadId); } else if ( @@ -5878,6 +5914,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( for (const [taskId] of endedIds) tasks.delete(taskId); return [tasks, { ...current, tasks }] as const; }); + const hasRunningClaudeMonitor = (nativeThreadId: string) => + Ref.get(claudeMonitors).pipe( + Effect.map((current) => + [...current.tasks.values()].some((task) => task.nativeThreadId === nativeThreadId), + ), + ); + // The buffer's first wake is a Monitor event: its result, once known, is a task notification's. + const isClaudeMonitorEventWake = (messages: ReadonlyArray) => { + const startIndex = messages.findIndex(isClaudeTurnStartMessage); + const start = messages[startIndex]; + if (start === undefined || !monitorEventWakeStarts.has(start)) return false; + const result = messages + .slice(startIndex + 1) + .find( + (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry), + ); + return result === undefined || isClaudeTaskNotificationOriginResult(result); + }; const claudeTaskOutcome = (status: "completed" | "failed" | "stopped") => status === "completed" ? "completed" : status === "stopped" ? "cancelled" : "failed"; // Reads the roster, so call it before the notification clears the task from it. @@ -5919,6 +5973,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly token: symbol; readonly end: SDKMessage | undefined; readonly retired: "unopened" | "opened" | null; + // Offered as Monitor progress, which starts no delegated follow-up. + readonly monitorEvent: boolean; } >(), ); @@ -9447,6 +9503,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (isClaudeRootTurnFrame(message)) { yield* forgetAbsorbedWake(wakeInput.nativeThreadId); } + if ( + isWakeTurnStart && + !possibleScheduledWakeStarts.has(message) && + (yield* hasRunningClaudeMonitor(wakeInput.nativeThreadId)) + ) { + monitorEventWakeStarts.add(message); + } yield* Ref.update(wakeBuffers, (current) => { const existing = current.get(wakeInput.nativeThreadId); const updated = new Map(current); @@ -9504,6 +9567,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId); const token = Symbol(nativeThreadId); + // A recorded report names finished work, which outranks Monitor progress. + const monitorEvent = + ((yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId)?.size ?? 0) === + 0 && isClaudeMonitorEventWake(buffered?.messages ?? []); const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => { if (current.has(nativeThreadId)) { return [false, current] as const; @@ -9515,6 +9582,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry), ), retired: null, + monitorEvent, }); return [true, updated] as const; }); @@ -9523,7 +9591,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } const reports = yield* takeWakeReports(nativeThreadId); const notification = backgroundWorkNotification( - [...(reports?.values() ?? [])].map((entry) => entry.report), + monitorEvent + ? [{ kind: "monitor", outcome: "updated" }] + : [...(reports?.values() ?? [])].map((entry) => entry.report), ); yield* Effect.logInfo("orchestration-v2.claude-wake-turn-detected", { providerSessionId: input.providerSessionId, @@ -9679,9 +9749,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // After a retired wake releases its latch, a wake buffered behind it has had no offer of its own. const offerBufferedWake = Effect.fnUntraced(function* (nativeThreadId: string) { const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; + if (yield* holdsBufferedWake(nativeThreadId, messages)) + yield* offerWakeContinuation(nativeThreadId); + }); + + const holdsBufferedWake = Effect.fnUntraced(function* ( + nativeThreadId: string, + messages: ReadonlyArray, + ) { const reports = (yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId); // A lifecycle result ends no turn, and closes the root frames before it. - const hasWake = + return ( messages .slice(messages.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1) .some(isClaudeRootTurnFrame) || @@ -9691,8 +9769,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (entry.type === "system" && entry.subtype === "task_notification" && reports?.get(entry.task_id)?.report.kind === "subagent"), - ); - if (hasWake) yield* offerWakeContinuation(nativeThreadId); + ) + ); }); // Untraced like the roster message handling: it runs for every streamed roster change. @@ -12538,15 +12616,24 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( pdfBudgets.get(nativeThreadId)!, persistAttachmentBudget(nativeThreadId), ); + const promptText = applyClaudePromptEffortPrefix( + turnInput.message.text, + compileClaudeModelSelection(turnInput.modelSelection, modelCatalog).promptEffort, + ); const userMessage = promptUuid === null ? null : yield* makeClaudeUserMessageWithAttachments({ - text: applyClaudePromptEffortPrefix( - turnInput.message.text, - compileClaudeModelSelection(turnInput.modelSelection, modelCatalog) - .promptEffort, - ), + text: promptText, + // Mentions in inline handoff history are history, not this turn's skill. + ...(turnInput.inlineContextLength === undefined + ? {} + : { + skillMentionsFrom: + promptText.length - + turnInput.message.text.slice(turnInput.inlineContextLength).trimEnd() + .length, + }), attachments: turnInput.message.attachments, attachmentsDir, fileSystem, @@ -12716,14 +12803,29 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* sdkMessageLock.withPermits(1)( Effect.gen(function* () { yield* attachTurn; - const drained = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; + const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; + const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId); + // This run carries the Monitor tag, which starts no delegated follow-up, so a wake + // buffered behind the Monitor event is left for a continuation of its own. + const ownEndIndex = + latch?.monitorEvent === true && latch.end !== undefined + ? buffered.indexOf(latch.end) + : -1; + const leavesLaterWake = + ownEndIndex !== -1 && + (yield* holdsBufferedWake(nativeThreadId, buffered.slice(ownEndIndex + 1))); + const drained = leavesLaterWake ? buffered.slice(0, ownEndIndex + 1) : buffered; yield* Ref.update(requestedContinuations, (current) => { const updated = new Map(current); updated.delete(nativeThreadId); return updated; }); - const wakeAbsorbed = (yield* Ref.get(absorbedWakes)).has(nativeThreadId); - yield* forgetAbsorbedWake(nativeThreadId); + // A root frame clears the absorbed marker, so behind a split it is the later wake's + // and stays; the split wake was absorbed when its end is not a result. + const wakeAbsorbed = leavesLaterWake + ? latch?.end?.type !== "result" + : (yield* Ref.get(absorbedWakes)).has(nativeThreadId); + if (!leavesLaterWake) yield* forgetAbsorbedWake(nativeThreadId); if (drained.length === 0) { const completedAt = yield* DateTime.now; yield* finalizeActiveTurn({ context, status: "completed", completedAt }); @@ -12784,6 +12886,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } if (lastResult !== undefined && !emptyTurnBeforeNextTurn) { yield* handleSdkMessage({ query: querySession.query, message: lastResult }); + if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId); return; } if ( @@ -12794,6 +12897,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { const completedAt = yield* DateTime.now; yield* finalizeActiveTurn({ context, status: "completed", completedAt }); + if (leavesLaterWake) yield* offerBufferedWake(nativeThreadId); } else if (!context.nativeWakeStarted) { yield* Effect.sleep(CLAUDE_WAKE_TURN_START_DEADLINE).pipe( Effect.andThen( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts index 3aca32bf41f90..4a87c04043029 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAgentSdkQueryRunner.test.ts @@ -748,6 +748,38 @@ describe.skipIf(HostProcess.Platform.defaultValue() === "win32")("Claude CLI pro }), ); + // A native cwd makes libuv wait for chdir, which a hung mount stalls with the whole server. + it.effect("enters the cwd in the child, so a missing one fails the CLI and not the spawn", () => + Effect.gen(function* () { + const cli = fakeClaudeCli('pwd -P > "$(dirname "$0")/cwd"'); + const dir = NodePath.dirname(cli); + const workspace = NodePath.join(dir, "work space"); + NodeFS.mkdirSync(workspace); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeFS.rmSync(dir, { recursive: true, force: true })), + ); + const exitCode = (cwd: string) => + Effect.promise( + () => + new Promise((resolve) => + spawnClaudeProcessGroup({ + command: cli, + args: [], + cwd, + env: process.env, + signal: new AbortController().signal, + }).once("exit", resolve), + ), + ); + assert.equal(yield* exitCode(workspace), 0); + assert.equal( + NodeFS.readFileSync(NodePath.join(dir, "cwd"), "utf8"), + `${NodeFS.realpathSync(workspace)}\n`, + ); + assert.equal(yield* exitCode(NodePath.join(dir, "missing")), 125); + }), + ); + // A restarted server reaps recorded CLIs, so a CLI must never run before its record exists. it.effect("records the CLI before it runs and forgets it once it exits", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index a94546e44b419..64c82e835c507 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -10326,6 +10326,187 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each([ + "Codex completes it later", + "its thread is unloaded", + "Codex completes it after the session's Stop deadline", + "Codex completes it after a second Stop fails", + ] as const)("keeps a turn open after an unconfirmed Stop until %s", (ending) => + Effect.gen(function* () { + const nativeThreadId = "unconfirmed-stop-thread"; + const nativeTurnId = "unconfirmed-stop-turn"; + const usage = { + totalTokens: 15, + inputTokens: 10, + cachedInputTokens: 2, + outputTokens: 5, + reasoningOutputTokens: 1, + }; + const pastDeadline = ending === "Codex completes it after the session's Stop deadline"; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: `unconfirmed-stop-${ending.length}`, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }), + { + type: "expect_outbound", + label: "turn/interrupt", + frame: { + id: 4, + method: "turn/interrupt", + params: { threadId: nativeThreadId, turnId: nativeTurnId }, + }, + }, + { + type: "emit_inbound", + label: "still working", + frame: { + method: "thread/tokenUsage/updated", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + tokenUsage: { total: usage, last: usage, modelContextWindow: 200_000 }, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/interrupt", + // A slow acknowledgement leaves the adapter's own wait running past the deadline. + ...(pastDeadline ? { afterMs: 6_000 } : {}), + frame: { id: 4, result: {} }, + }, + ...(ending === "its thread is unloaded" + ? ([ + { + type: "expect_outbound", + label: "thread/unsubscribe", + frame: { + id: 5, + method: "thread/unsubscribe", + params: { threadId: nativeThreadId }, + }, + }, + { + type: "emit_inbound", + label: "thread/unsubscribe", + frame: { id: 5, result: { status: "unsubscribed" } }, + }, + ] satisfies Array) + : ([ + ...(ending === "Codex completes it after a second Stop fails" + ? ([ + { + type: "expect_outbound", + label: "turn/interrupt/second", + frame: { + id: 5, + method: "turn/interrupt", + params: { threadId: nativeThreadId, turnId: nativeTurnId }, + }, + }, + { + type: "emit_inbound", + label: "turn/interrupt/second", + frame: { id: 5, error: { code: -32603, message: "internal error" } }, + }, + ] satisfies Array) + : []), + { + type: "emit_inbound", + label: "turn/completed", + afterMs: 20_000, + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ] satisfies Array)), + ], + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-unconfirmed-stop"), + text: "work", + }), + ); + const stopping = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeTurnId, + }), + }) + .pipe( + // The session manager bounds every Stop the same way. + Effect.timeoutOrElse({ + duration: "15 seconds", + orElse: () => Effect.fail({ _tag: "SessionStopDeadline" } as const), + }), + Effect.result, + Effect.forkScoped, + ); + // Codex received the interrupt and kept reporting work on the turn. + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && + event.providerTurn.tokenUsage?.usedTokens === usage.totalTokens, + ), + ); + yield* TestClock.adjust(pastDeadline ? "15 seconds" : "10 seconds"); + + const stopped = yield* Fiber.join(stopping); + assert.equal( + stopped._tag === "Failure" ? stopped.failure._tag : "confirmed", + pastDeadline ? "SessionStopDeadline" : "ProviderAdapterInterruptTimeoutError", + ); + assert.deepEqual(harness.terminalEvents(), []); + + if (ending === "Codex completes it after a second Stop fails") { + const second = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + nativeTurnId, + }), + }) + .pipe(Effect.result); + assert.equal(second._tag, "Failure"); + assert.deepEqual(harness.terminalEvents(), []); + } + if (ending === "its thread is unloaded") { + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread }); + } else { + yield* TestClock.adjust("20 seconds"); + } + yield* harness.awaitTerminal(1); + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["interrupted"], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + describe("native goals", () => { const nativeThreadId = "goal-thread"; const objective = "Ship the feature"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 2a385e1be6d08..7051e36cc0e79 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -89,6 +89,7 @@ import * as Digest from "effect/crypto/Digest"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Function from "effect/Function"; @@ -158,6 +159,8 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; const CODEX_PROVIDER = ProviderDriverKind.make("codex"); +// How long Stop waits for Codex to end the turn before the user is offered Force stop. +const CODEX_STOP_CONFIRM_TIMEOUT_MS = 10_000; // Codex can announce a retry and never resume. Recovered retries resume model output within ~75s. const CODEX_PROVIDER_RETRY_STALL_TIMEOUT = "10 minutes"; export const CODEX_DRIVER_KIND = CODEX_PROVIDER; @@ -7919,13 +7922,30 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // unarchives it on the next turn. if (unloadInput.archive === true) { yield* client.request("thread/archive", { threadId: nativeThreadId }); - return; + } else { + // A resume may already wait on the pending entry; replacing it would strand that wait. + if (!threadClosings.has(nativeThreadId)) { + threadClosings.set(nativeThreadId, yield* Deferred.make()); + } + yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); } - // A resume may already wait on the pending entry; replacing it would strand that wait. - if (!threadClosings.has(nativeThreadId)) { - threadClosings.set(nativeThreadId, yield* Deferred.make()); + // No turn/completed arrives for an unloaded thread, so a Stop Codex never + // confirmed would otherwise keep its turn open for the life of the session. + const interrupting = yield* Ref.get(interruptingNativeTurns); + const completedAt = yield* DateTime.now; + for (const context of (yield* Ref.get(activeTurns)).values()) { + if ( + context.providerThread.id !== unloadInput.providerThread.id || + !interrupting.has(context.nativeTurnId) + ) + continue; + yield* finalizeCodexTurn({ + context, + nativeTurnId: context.nativeTurnId, + status: "interrupted", + completedAt, + }); } - yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); }, (effect, unloadInput) => effect.pipe( @@ -8013,23 +8033,30 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( readonly context: ActiveCodexTurnContext; readonly completion: Deferred.Deferred; }> = []; + const trackedInterruptNativeTurnIds = new Set(); + let joinedPendingStop = false; + // Untraced: runs once per lineage turn inside the interruptTurn span. + const trackInterruptTarget = Effect.fnUntraced(function* ( + context: ActiveCodexTurnContext, + ) { + const fresh = yield* Deferred.make(); + // An earlier Stop may still wait on this turn; replacing its waiter would strand it. + const completion = yield* Ref.modify(turnWaiters, (current) => { + const pending = current.get(context.nativeTurnId); + return pending === undefined + ? [fresh, new Map(current).set(context.nativeTurnId, fresh)] + : [pending, current]; + }); + joinedPendingStop ||= completion !== fresh; + yield* Ref.update(interruptingNativeTurns, (current) => + new Set(current).add(context.nativeTurnId), + ); + interruptTargets.push({ context, completion }); + trackedInterruptNativeTurnIds.add(context.nativeTurnId); + }); for (const context of interruptTargetContexts) { - interruptTargets.push({ context, completion: yield* Deferred.make() }); + yield* trackInterruptTarget(context); } - yield* Ref.update(turnWaiters, (current) => { - const updated = new Map(current); - for (const target of interruptTargets) { - updated.set(target.context.nativeTurnId, target.completion); - } - return updated; - }); - yield* Ref.update(interruptingNativeTurns, (current) => { - const updated = new Set(current); - for (const target of interruptTargets) { - updated.add(target.context.nativeTurnId); - } - return updated; - }); const registeredActiveTurns = yield* Ref.get(activeTurns); for (const target of interruptTargets) { if (registeredActiveTurns.get(target.context.nativeTurnId) !== target.context) { @@ -8062,9 +8089,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); }); - const trackedInterruptNativeTurnIds = new Set( - interruptTargets.map((target) => target.context.nativeTurnId), - ); const finalizeRemainingInterruptLineage = Effect.gen(function* () { while (true) { const newlyDiscovered: Array = []; @@ -8077,20 +8101,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( if (trackedInterruptNativeTurnIds.has(context.nativeTurnId)) { continue; } - const completion = yield* Deferred.make(); - interruptTargets.push({ context, completion }); - trackedInterruptNativeTurnIds.add(context.nativeTurnId); + yield* trackInterruptTarget(context); newlyDiscovered.push(context); - yield* Ref.update(turnWaiters, (current) => { - const updated = new Map(current); - updated.set(context.nativeTurnId, completion); - return updated; - }); - yield* Ref.update(interruptingNativeTurns, (current) => { - const updated = new Set(current); - updated.add(context.nativeTurnId); - return updated; - }); } return lineage; }), @@ -8153,19 +8165,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( !trackedInterruptNativeTurnIds.has(context.nativeTurnId), ); for (const context of lineage) { - const completion = yield* Deferred.make(); - interruptTargets.push({ context, completion }); - trackedInterruptNativeTurnIds.add(context.nativeTurnId); - yield* Ref.update(turnWaiters, (current) => { - const updated = new Map(current); - updated.set(context.nativeTurnId, completion); - return updated; - }); - yield* Ref.update(interruptingNativeTurns, (current) => { - const updated = new Set(current); - updated.add(context.nativeTurnId); - return updated; - }); + yield* trackInterruptTarget(context); } return lineage; }), @@ -8192,114 +8192,55 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } }); - yield* Effect.gen(function* () { - for (const target of interruptTargets) { - const context = target.context; - if (context.capacityRetryPending !== undefined) { - yield* finalizeCodexTurn({ - context, - nativeTurnId: context.nativeTurnId, - status: "interrupted", - completedAt: yield* DateTime.now, - }); - continue; - } - // Null start timestamps ACK queued turns; interruption must wait for turn/started. - if (context.nativeStartReady !== undefined) { - const ready = yield* Deferred.await(context.nativeStartReady).pipe( - Effect.timeoutOption("10 seconds"), - ); - if (Option.isNone(ready)) { - return yield* toProtocolError( - "Codex did not start the queued turn within 10 seconds; Stop could not be delivered.", - ); - } - } - if ((yield* Ref.get(activeTurns)).get(context.nativeTurnId) !== context) { - continue; - } - yield* client.request("turn/interrupt", { - threadId: yield* getNativeThreadId(context.providerThread), - turnId: context.nativeTurnId, - }); - } - const containedTerminalKeys = new Set(); - const attemptedTerminalKeys = new Set(); - const collectTrackedTerminals = Effect.fn("CodexAdapterV2.collectTrackedTerminals")( - function* (targets: typeof interruptTargets) { - const trackedTerminals = new Map< - string, - { readonly nativeThreadId: string; readonly processId: string } - >(); - const runningItems = yield* Ref.get(runningCommandItemsByTurn); - for (const target of targets) { - const nativeThreadId = yield* getNativeThreadId( - target.context.providerThread, - ); - const items = runningItems.get(target.context.nativeTurnId); - for (const item of items?.values() ?? []) { - if (item.processId !== undefined) { - trackedTerminals.set(`${nativeThreadId}:${item.processId}`, { - nativeThreadId, - processId: item.processId, - }); - } + const containedTerminalKeys = new Set(); + const attemptedTerminalKeys = new Set(); + const collectTrackedTerminals = Effect.fn("CodexAdapterV2.collectTrackedTerminals")( + function* (targets: typeof interruptTargets) { + const trackedTerminals = new Map< + string, + { readonly nativeThreadId: string; readonly processId: string } + >(); + const runningItems = yield* Ref.get(runningCommandItemsByTurn); + for (const target of targets) { + const nativeThreadId = yield* getNativeThreadId(target.context.providerThread); + const items = runningItems.get(target.context.nativeTurnId); + for (const item of items?.values() ?? []) { + if (item.processId !== undefined) { + trackedTerminals.set(`${nativeThreadId}:${item.processId}`, { + nativeThreadId, + processId: item.processId, + }); } } - return trackedTerminals; - }, - ); - const terminateTrackedTerminals = Effect.fn( - "CodexAdapterV2.terminateTrackedTerminals", - )(function* (targets: typeof interruptTargets) { - const trackedTerminals = yield* collectTrackedTerminals(targets); - const pendingTerminals = Array.from(trackedTerminals.entries()) - .filter(([key]) => !containedTerminalKeys.has(key)) - .sort( - ([leftKey], [rightKey]) => - Number(attemptedTerminalKeys.has(leftKey)) - - Number(attemptedTerminalKeys.has(rightKey)), - ); - return yield* Effect.forEach( - pendingTerminals, - ([key, { nativeThreadId, processId }]) => - Effect.gen(function* () { - attemptedTerminalKeys.add(key); - yield* terminateBackgroundTerminal(nativeThreadId, processId); - containedTerminalKeys.add(key); - }).pipe( - Effect.as({ success: true as const }), - Effect.catch((error) => Effect.succeed({ success: false as const, error })), - ), + } + return trackedTerminals; + }, + ); + const terminateTrackedTerminals = Effect.fn( + "CodexAdapterV2.terminateTrackedTerminals", + )(function* (targets: typeof interruptTargets) { + const trackedTerminals = yield* collectTrackedTerminals(targets); + const pendingTerminals = Array.from(trackedTerminals.entries()) + .filter(([key]) => !containedTerminalKeys.has(key)) + .sort( + ([leftKey], [rightKey]) => + Number(attemptedTerminalKeys.has(leftKey)) - + Number(attemptedTerminalKeys.has(rightKey)), ); - }); - - const [, completed] = yield* Effect.all( - [ - terminateTrackedTerminals(interruptTargets), - Effect.forEach( - interruptTargets, - (target) => Deferred.await(target.completion), - { concurrency: "unbounded", discard: true }, - ).pipe(Effect.timeoutOption("10 seconds")), - ], - { concurrency: "unbounded" }, + return yield* Effect.forEach( + pendingTerminals, + ([key, { nativeThreadId, processId }]) => + Effect.gen(function* () { + attemptedTerminalKeys.add(key); + yield* terminateBackgroundTerminal(nativeThreadId, processId); + containedTerminalKeys.add(key); + }).pipe( + Effect.as({ success: true as const }), + Effect.catch((error) => Effect.succeed({ success: false as const, error })), + ), ); - if (Option.isNone(completed)) { - for (const target of interruptTargets) { - const context = target.context; - if ((yield* Ref.get(activeTurns)).get(context.nativeTurnId) !== context) { - continue; - } - yield* Effect.logWarning("orchestration-v2.codex-interrupt-timeout", { - providerSessionId: input.providerSessionId, - providerThreadId: context.providerThread.id, - providerTurnId: context.providerTurnId, - nativeTurnId: context.nativeTurnId, - }); - } - } - + }); + const settleInterruptedLineage = Effect.gen(function* () { yield* interruptLateDescendants; yield* finalizeRemainingInterruptLineage; @@ -8339,10 +8280,114 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } }), ); + }); + // Codex may still be working, so a root stays open and marked interrupting. + // Whatever ends it later (Codex, Force stop) settles the rest of this Stop. + const deferToActiveRoots = Effect.gen(function* () { + const registered = yield* Ref.get(activeTurns); + const roots = interruptTargets.filter( + ({ context }) => + lineageRoots.includes(context) && + registered.get(context.nativeTurnId) === context, + ); + if (roots.length === 0) return false; + for (const { context } of roots) { + yield* Effect.logWarning("orchestration-v2.codex-interrupt-timeout", { + providerSessionId: input.providerSessionId, + providerThreadId: context.providerThread.id, + providerTurnId: context.providerTurnId, + nativeTurnId: context.nativeTurnId, + }); + } + yield* Effect.forEach(roots, (target) => Deferred.await(target.completion), { + concurrency: "unbounded", + discard: true, + }).pipe( + Effect.andThen(settleInterruptedLineage), + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.logWarning("orchestration-v2.codex-late-stop-settle-failed", { + providerSessionId: input.providerSessionId, + cause, + }), + ), + Effect.ensuring(cleanupInterruptState), + Effect.forkIn(scope), + ); + return true; + }); + + const unconfirmed = yield* Effect.gen(function* () { + for (const target of interruptTargets) { + const context = target.context; + if (context.capacityRetryPending !== undefined) { + yield* finalizeCodexTurn({ + context, + nativeTurnId: context.nativeTurnId, + status: "interrupted", + completedAt: yield* DateTime.now, + }); + continue; + } + // Null start timestamps ACK queued turns; interruption must wait for turn/started. + if (context.nativeStartReady !== undefined) { + const ready = yield* Deferred.await(context.nativeStartReady).pipe( + Effect.timeoutOption("10 seconds"), + ); + if (Option.isNone(ready)) { + return yield* toProtocolError( + "Codex did not start the queued turn within 10 seconds; Stop could not be delivered.", + ); + } + } + if ((yield* Ref.get(activeTurns)).get(context.nativeTurnId) !== context) { + continue; + } + yield* client.request("turn/interrupt", { + threadId: yield* getNativeThreadId(context.providerThread), + turnId: context.nativeTurnId, + }); + } + const [, completed] = yield* Effect.all( + [ + terminateTrackedTerminals(interruptTargets), + Effect.forEach( + interruptTargets, + (target) => Deferred.await(target.completion), + { concurrency: "unbounded", discard: true }, + ).pipe(Effect.timeoutOption(CODEX_STOP_CONFIRM_TIMEOUT_MS)), + ], + { concurrency: "unbounded" }, + ); + if (Option.isSome(completed) || !(yield* deferToActiveRoots)) { + yield* settleInterruptedLineage; + return false; + } + return true; }).pipe( - Effect.onError(() => finalizeRemainingInterruptLineage), - Effect.ensuring(cleanupInterruptState), + Effect.onExit((exit) => { + if (Exit.isSuccess(exit)) return exit.value ? Effect.void : cleanupInterruptState; + const abandon = finalizeRemainingInterruptLineage.pipe( + Effect.ensuring(cleanupInterruptState), + ); + // Neither a caller's deadline nor a failed retry of a pending Stop confirms + // that the turn ended. + return Cause.hasInterruptsOnly(exit.cause) || joinedPendingStop + ? Effect.flatMap(deferToActiveRoots, (deferred) => + deferred ? Effect.void : abandon, + ) + : abandon; + }), ); + if (unconfirmed) { + return yield* new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ + driver: CODEX_PROVIDER, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + timeoutMs: CODEX_STOP_CONFIRM_TIMEOUT_MS, + }); + } }, (effect, requestedInput) => Effect.acquireUseRelease( @@ -8361,14 +8406,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( else goalStops.delete(nativeThreadId); }), ).pipe( - Effect.mapError( - (cause) => - new ProviderAdapter.ProviderAdapterInterruptError({ - driver: CODEX_PROVIDER, - providerThreadId: requestedInput.providerThread.id, - providerTurnId: requestedInput.providerTurnId, - cause, - }), + Effect.mapError((cause) => + cause._tag === "ProviderAdapterInterruptTimeoutError" + ? cause + : new ProviderAdapter.ProviderAdapterInterruptError({ + driver: CODEX_PROVIDER, + providerThreadId: requestedInput.providerThread.id, + providerTurnId: requestedInput.providerTurnId, + cause, + }), ), ), ), diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index d469ad6c81089..4cbdbf78b00ee 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -1561,8 +1561,11 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, }, }); - const callAgain = (input: Record): ReadonlyArray => { - const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-again" }; + const callAgain = ( + input: Record, + { id = "call-again", writesRules = true } = {}, + ): ReadonlyArray => { + const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id }; return [ event("session.tool.input.started", { ...tool, name: "subagent" }), event("session.tool.called", { @@ -1575,20 +1578,25 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...tool, metadata: { sessionID: CHILD, status: "running" }, }), - out("session.update", { sessionID: CHILD, permissions: "" }), - reply("session.update", null), + // The adapter writes a child's rules only when they changed. + ...(writesRules + ? [ + out("session.update", { sessionID: CHILD, permissions: "" }), + reply("session.update", null), + ] + : []), returnedRunning(tool.id), ]; }; - const childReport = (inboxID: string, text: string) => + const childReport = (inboxID: string, text: string, description = "Sleep") => event("session.inbox.enqueued", { inboxID, sessionID: SESSION, item: { type: "synthetic", payload: { - text: `\n${text}\n`, - description: "Sleep", + text: `\n${text}\n`, + description, metadata: { source: "subagent", childID: CHILD, agent: "General", state: "completed" }, }, delivery: "steer", @@ -1600,6 +1608,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ) => Effect.gen(function* () { const calls = new Map(); + const callsById = new Map(); const childTurns = new Map(); const callsAtChildTurnStart = new Map< string, @@ -1610,6 +1619,12 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* runtime.events.pipe( Stream.tap((event) => Effect.gen(function* () { + if (event.type === "subagent.updated") { + callsById.set(event.subagent.nativeTaskRef?.nativeId ?? "", { + status: event.subagent.status, + result: event.subagent.result, + }); + } if (event.type === "subagent.updated" && event.subagent.title !== null) { calls.set(event.subagent.title, { status: event.subagent.status, @@ -1648,7 +1663,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { yield* until(check); }); }); - return { calls, callsAtChildTurnStart, childTurns, state, until }; + return { calls, callsById, callsAtChildTurnStart, childTurns, state, until }; }); const launchedAndRunning = [ ...backgroundLaunch(CHILD), @@ -1861,6 +1876,119 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + const childSaid = (text: string, run = 1) => + event("session.text.ended", { + sessionID: CHILD, + assistantMessageID: `msg_child_${run}`, + ordinal: 0, + text, + }); + it.effect.each([ + { + // regression: #26319 the report settled the older run and left the resumed call running + name: "an earlier run's report never arrived", + replay: [ + ...launchedAndRunning, + ...callAgain({ background: true }), + childSaid("FIRST_OK"), + event("session.execution.succeeded", { sessionID: CHILD }), + ...callAgain({ background: true }, { id: "call-later", writesRules: false }), + event("session.execution.started", { sessionID: CHILD }), + childSaid("SECOND_OK", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_2", "SECOND_OK", "Again"), + ], + expected: { + "call-background": { status: "completed", result: "FIRST_OK" }, + "call-again": { status: "completed", result: "FIRST_OK" }, + "call-later": { status: "completed", result: "SECOND_OK" }, + }, + }, + { + name: "both runs' reports arrive after the runs ended", + replay: [ + ...launchedAndRunning, + event("session.execution.succeeded", { sessionID: CHILD }), + ...callAgain({ background: true, description: "Sleep" }), + event("session.execution.started", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_1", "FIRST_OK"), + childReport("msg_report_2", "SECOND_OK"), + event("session.execution.succeeded", { sessionID: SESSION }), + ], + expected: { + "call-background": { status: "completed", result: "FIRST_OK" }, + "call-again": { status: "completed", result: "SECOND_OK" }, + }, + }, + { + name: "two runs with the same answer report late", + replay: [ + ...launchedAndRunning, + childSaid("DONE"), + event("session.execution.succeeded", { sessionID: CHILD }), + ...callAgain({ background: true }), + event("session.execution.started", { sessionID: CHILD }), + childSaid("DONE", 2), + event("session.execution.succeeded", { sessionID: CHILD }), + childReport("msg_report_1", "DONE"), + ...callAgain({ background: true }, { id: "call-later", writesRules: false }), + event("session.execution.started", { sessionID: CHILD }), + childReport("msg_report_2", "DONE", "Again"), + childSaid("THIRD_OK", 3), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report_3", "THIRD_OK", "Again"), + ], + expected: { + "call-background": { status: "completed", result: "DONE" }, + "call-again": { status: "completed", result: "DONE" }, + "call-later": { status: "completed", result: "THIRD_OK" }, + }, + }, + { + name: "the call it joined already returned", + replay: [ + ...backgroundLaunch(CHILD), + event("session.execution.started", { sessionID: CHILD }), + ...callAgain({ background: true }), + event("session.execution.succeeded", { sessionID: CHILD }), + event( + "session.tool.success", + { + sessionID: SESSION, + assistantMessageID: "msg_assistant", + id: "call-background", + content: [{ type: "text", text: "FIRST_OK" }], + metadata: { sessionID: CHILD, status: "completed" }, + executed: true, + }, + undefined, + 2, + ), + event("session.execution.succeeded", { sessionID: SESSION }), + childReport("msg_report", "CHILD_OK", "Again"), + ], + expected: { + "call-background": { status: "completed", result: "FIRST_OK" }, + "call-again": { status: "completed", result: "CHILD_OK" }, + }, + }, + ])("settles a resumed subagent's calls when $name", ({ replay, expected }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed(replay); + const watch = yield* watchCalls(runtime, thread); + yield* runtime.startTurn(withLineage(thread)); + yield* watch.until( + () => + watch.state.roster?.length === 0 && + Object.keys(expected).every((id) => watch.callsById.get(id)?.status === "completed"), + ); + assert.deepEqual(Object.fromEntries(watch.callsById), expected); + }), + ); + const MIDDLE = "ses_middle0000000000000000000"; const DEEP = "ses_grandchild00000000000000"; const toolOf = (session: string, id: string) => ({ diff --git a/apps/server/src/orchestration-v2/CheckpointService.ts b/apps/server/src/orchestration-v2/CheckpointService.ts index c37b206f35a87..3e0fbe95e8aa4 100644 --- a/apps/server/src/orchestration-v2/CheckpointService.ts +++ b/apps/server/src/orchestration-v2/CheckpointService.ts @@ -410,6 +410,7 @@ export const layer: Layer.Layer< .captureCheckpoint({ cwd: input.scope.cwd, checkpointRef, + ...(input.ordinalWithinScope > 0 ? { previousCheckpointRef } : {}), }) .pipe( Effect.as("ready" as const), diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 426da22121e36..b0886435d0b5d 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -2635,11 +2635,19 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( threadId: child.childThreadId, messageId: wakeMessageId, text: "Background activity updated", - notification: { - source: { kind: "command" }, - outcome: "completed", - summary: 'Command "sleep 60" finished', - }, + // A monitor that ends is finished work too; only its per-line updates are progress. + notification: + delivery === "live" + ? { + source: { kind: "monitor" }, + outcome: "completed", + summary: 'Monitor "sleep 60" finished', + } + : { + source: { kind: "command" }, + outcome: "completed", + summary: 'Command "sleep 60" finished', + }, attachments: [], dispatchMode: { type: "queue_after_active" }, }); @@ -2937,6 +2945,251 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( }; }); + it.effect("holds a follow-up open while the child's own subagent still runs", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread:followup-grandchild-parent"); + const projectId = ProjectId.make("project:followup-grandchild"); + const parentRunId = RunId.make("run:followup-grandchild-parent"); + const rootNodeId = NodeId.make("node:followup-grandchild-parent"); + yield* seedParentWithTerminalTask({ + threadId: parentThreadId, + projectId, + runId: parentRunId, + rootNodeId, + taskId: NodeId.make("node:followup-grandchild-seed"), + deliveryState: "acknowledged", + now, + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId, + projectId, + parentRunId, + rootNodeId, + name: "followup-grandchild-child", + completionWake: "always", + continuationPending: false, + runStatus: "completed", + now, + }); + yield* orchestrator.recoverDelegatedTasks; + assert.equal( + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === child.taskId, + )?.status, + "completed", + ); + + const followupMessageId = MessageId.make("message:followup-grandchild-send"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "agent", + creationSource: "mcp", + commandId: CommandId.make("command:followup-grandchild-send"), + threadId: child.childThreadId, + senderThreadId: parentThreadId, + messageId: followupMessageId, + text: "Now delegate the next step.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + }); + const followupRun = (yield* orchestrator.getThreadProjection( + child.childThreadId, + )).runs.find((run) => run.userMessageId === followupMessageId)!; + assert.isDefined(followupRun.delegatedTaskId); + const followupTaskId = followupRun.delegatedTaskId!; + + const grandchildId = NodeId.make("node:followup-grandchild-grandchild"); + const grandchild = { + id: grandchildId, + threadId: child.childThreadId, + runId: followupRun.id, + parentNodeId: NodeId.make("node:followup-grandchild-child-root"), + origin: "app_owned" as const, + createdBy: "agent" as const, + driver, + providerInstanceId: modelSelection.instanceId, + providerThreadId: null, + childThreadId: ThreadId.make("thread:followup-grandchild-grandchild"), + nativeTaskRef: null, + prompt: "Do the next step.", + title: null, + model: null, + completionWake: "always" as const, + status: "running" as const, + result: null, + startedAt: now, + completedAt: null, + updatedAt: now, + }; + yield* eventSink.write({ + commandId: reconcileCommandId("followup-grandchild-turn-ended"), + events: [ + { + id: EventId.make("event:followup-grandchild-started"), + type: "subagent.updated", + threadId: child.childThreadId, + runId: followupRun.id, + nodeId: grandchildId, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: grandchild, + }, + { + id: EventId.make("event:followup-grandchild-run-completed"), + type: "run.updated", + threadId: child.childThreadId, + runId: followupRun.id, + occurredAt: now, + payload: { ...followupRun, status: "completed", startedAt: now, completedAt: now }, + }, + ], + }); + yield* orchestrator.recoverDelegatedTasks; + + const waiting = yield* orchestrator.getThreadProjection(parentThreadId); + const heldFollowup = waiting.subagents.find((task) => task.id === followupTaskId); + assert.isNull( + heldFollowup?.result ?? null, + "the follow-up closed while the child's own subagent was still running", + ); + assert.equal(heldFollowup?.status, "running"); + assert.equal( + waiting.contextTransfers.filter( + (transfer) => + transfer.type === "subagent_result" && + transfer.sourceThreadId === child.childThreadId, + ).length, + 1, + ); + + // Another turn in the child does not release the hold while the grandchild runs. + for (const status of ["running", "completed"] as const) { + yield* eventSink.write({ + commandId: reconcileCommandId(`followup-grandchild-user-${status}`), + events: [ + runEvent({ + threadId: child.childThreadId, + runId: RunId.make("run:followup-grandchild-user"), + ordinal: followupRun.ordinal + 1, + status, + now, + }), + ], + }); + yield* orchestrator.recoverDelegatedTasks; + assert.isNull( + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === followupTaskId, + )?.result ?? null, + `the follow-up closed while another child run was ${status}`, + ); + } + + // The grandchild's completion wakes the child in a run without a delegatedTaskId. + const wakeRunId = RunId.make("run:followup-grandchild-wake"); + const wakeRun = (status: "running" | "completed") => + runEvent({ + threadId: child.childThreadId, + runId: wakeRunId, + ordinal: followupRun.ordinal + 2, + status, + now, + }); + yield* eventSink.write({ + commandId: reconcileCommandId("followup-grandchild-settled"), + events: [ + { + id: EventId.make("event:followup-grandchild-completed"), + type: "subagent.updated", + threadId: child.childThreadId, + runId: followupRun.id, + nodeId: grandchildId, + driver, + providerInstanceId: modelSelection.instanceId, + occurredAt: now, + payload: { + ...grandchild, + status: "completed", + result: "grandchild finished", + completionDelivery: { state: "acknowledged", observedByRunId: wakeRunId }, + completedAt: now, + }, + }, + { + id: EventId.make("event:followup-grandchild-wake-message"), + type: "message.updated", + threadId: child.childThreadId, + runId: wakeRunId, + occurredAt: now, + payload: { + id: MessageId.make(`message:${wakeRunId}`), + threadId: child.childThreadId, + runId: wakeRunId, + nodeId: null, + role: "user", + text: "Delegated task finished.", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + delegatedCompletion: { + parentRunId: followupRun.id, + generation: 1, + taskIds: [grandchildId], + }, + createdAt: now, + updatedAt: now, + }, + }, + wakeRun("running"), + ], + }); + yield* orchestrator.recoverDelegatedTasks; + const waking = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === followupTaskId, + ); + assert.isNull(waking?.result ?? null, "the follow-up closed before the child's wake ended"); + + yield* eventSink.write({ + commandId: reconcileCommandId("followup-grandchild-wake-finished"), + events: [ + { + id: EventId.make("event:followup-grandchild-wake-result"), + type: "message.updated", + threadId: child.childThreadId, + runId: wakeRunId, + occurredAt: now, + payload: { + id: MessageId.make("message:followup-grandchild-wake-result"), + threadId: child.childThreadId, + runId: wakeRunId, + nodeId: null, + role: "assistant", + text: "The grandchild finished the next step.", + attachments: [], + streaming: false, + createdBy: "agent", + creationSource: "server", + createdAt: now, + updatedAt: now, + }, + }, + wakeRun("completed"), + ], + }); + yield* orchestrator.recoverDelegatedTasks; + const settled = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === followupTaskId, + ); + assert.equal(settled?.status, "completed"); + assert.equal(settled?.result, "The grandchild finished the next step."); + }), + ); + it.effect("waits for a run the follow-up's child queued on its own thread", () => Effect.gen(function* () { const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b657139cde6c6..89d36ce8bbcbb 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -129,7 +129,9 @@ import { cancelledBeforeStart, continuationFailedBeforePrompt, continuationStartRetryDelayMs, + delegatedTaskAwaitsSubagents, delegatedTaskResultRun, + delegatedTaskRuns, isRestartContinuationSource, runOutcome, } from "./RestartBackgroundNote.ts"; @@ -757,6 +759,26 @@ function cancelledAppOwnedTask( }; } +// A workspace change detaches the session, which can settle the calling run at once. Queuing its +// follow-up in a later command would let a delegated task report its result before that exists. +function metadataUpdateContinuation( + command: Extract, +): Extract | undefined { + return command.continuation === undefined + ? undefined + : { + type: "message.dispatch", + commandId: command.commandId, + threadId: command.threadId, + messageId: command.continuation.messageId, + text: command.continuation.text, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }; +} + // Provider wakes can start follow-up work; monitor updates only report progress. // Dispatch takes the parent's lock for follow-ups because intake writes the parent. function mayStartSubagentFollowup( @@ -764,7 +786,10 @@ function mayStartSubagentFollowup( ): boolean { if (command.scheduledTaskId !== undefined || command.restartContinuationOfRunId !== undefined) return false; - if (command.notification !== undefined) return command.notification.source.kind !== "monitor"; + if (command.notification !== undefined) + return ( + command.notification.source.kind !== "monitor" || command.notification.outcome !== "updated" + ); return ( command.createdBy === "user" || command.creationSource === "mcp" || @@ -910,16 +935,23 @@ function nextQueuedRun( return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); } +// Delegated completions, monitor notifications and unpinned scheduled deliveries never choose a +// model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. function followsCurrentConversation( message: | Pick< OrchestrationV2ConversationMessage, - "createdBy" | "creationSource" | "notification" | "delegatedCompletion" + | "createdBy" + | "creationSource" + | "notification" + | "delegatedCompletion" + | "followsThreadSelection" > | undefined, ): boolean { return ( message?.delegatedCompletion !== undefined || + message?.followsThreadSelection === true || (message?.notification?.source.kind === "monitor" && !isBufferedProviderNotification(message)) ); } @@ -1446,6 +1478,21 @@ function lastDeliveredRunForProviderThread( ); } +type DyingNativeSubagent = { + readonly projection: Pick; + readonly subagent: Pick< + Extract, + "subagentId" | "origin" | "childThreadId" | "providerInstanceId" + >; +}; + +const nativeSubagentRef = (subagent: OrchestrationV2Subagent): DyingNativeSubagent["subagent"] => ({ + subagentId: subagent.id, + origin: subagent.origin, + childThreadId: subagent.childThreadId, + providerInstanceId: subagent.providerInstanceId, +}); + const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(function* () { const checkpointService = yield* CheckpointServiceV2; const commandPolicy = yield* CommandPolicyV2; @@ -1495,7 +1542,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio /** The driver when this provider runs `/goal` natively, else undefined. */ const goalDriverFor = Effect.fn("Orchestrator.goalDriverFor")(function* ( - command: OrchestrationV2ServerCommand, + command: Pick, providerInstanceId: ProviderInstanceId, ) { const adapter = yield* providerAdapters.get(providerInstanceId).pipe(mapDispatchError(command)); @@ -1510,7 +1557,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio /** Unsupported goal controls can become new objectives in native providers. */ const ensureGoalCommandSupported = Effect.fn("Orchestrator.ensureGoalCommandSupported")( function* ( - command: OrchestrationV2ServerCommand, + command: Pick, message: { readonly text: string; readonly attachments: ReadonlyArray }, providerInstanceId: ProviderInstanceId, ) { @@ -1536,7 +1583,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); const mapDispatchError = - (command: OrchestrationV2ServerCommand) => + (command: Pick) => (effect: Effect.Effect): Effect.Effect => effect.pipe( Effect.mapError( @@ -2477,6 +2524,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Queued run ${queuedRun.id} is missing projection state.`, }); } + // A scheduled delivery starts on the thread's current pick, so /goal must suit that provider. + yield* ensureGoalCommandSupported( + { commandId, type: "message.dispatch" }, + queuedMessage, + queuedRun.providerInstanceId, + ); const now = yield* DateTime.now; const targetAdapter = yield* providerAdapters.get(queuedRun.providerInstanceId).pipe( @@ -2503,7 +2556,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? activeProviderThread : rootProviderThreadsForProvider(projection, queuedRun.providerInstanceId)[0] : freshContext && - (storedProviderThread.firstRunOrdinal !== null || + // The reserved row belongs to the instance the run queued on, which may have changed. + (storedProviderThread.providerInstanceId !== queuedRun.providerInstanceId || + storedProviderThread.firstRunOrdinal !== null || storedProviderThread.nativeThreadRef !== null) ? undefined : storedProviderThread; @@ -3751,19 +3806,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.searchQuery, ) : null; - // Viewing a thread changes read state only. Loading its transcript (or - // bumping updatedAt) makes a routine read receipt scale with its history. + if (!movesForward && opens === null) return; + // Viewing a thread changes read state only. Loading its transcript, bumping + // updatedAt, or copying the thread into the event makes a read receipt scale with it. yield* emit( events, command, )({ - type: "thread.visited", + type: "thread.visit-recorded", threadId: command.threadId, providerInstanceId: thread.providerInstanceId, occurredAt, payload: { - ...thread, - ...(movesForward ? { lastVisitedAt: visitedAt.value } : {}), + lastVisitedAt: movesForward ? visitedAt.value : thread.lastVisitedAt, ...(opens ? { opens } : {}), }, }); @@ -4528,7 +4583,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) .map((message) => message.id), ); - if (queuedRuns.some((run) => !automaticMessageIds.has(run.userMessageId))) { + const userRuns = queuedRuns.filter((run) => !automaticMessageIds.has(run.userMessageId)); + // User work waiting behind a usage limit cannot start until the reset or the user acts. + const latest = latestExecutedRun(projection.runs); + const limitRecords = + userRuns.length === 0 || latest?.status !== "failed" + ? null + : yield* loadProjectionForCommand(command, ["turnItems", "providerSessions"], { + turnItemTypes: ["error"], + turnItemRunIds: [latest.id], + }); + const heldBehindLimit = + limitRecords !== null && + userRuns.every((run) => + usageLimitHoldsQueue({ ...limitRecords, runs: projection.runs }, run.providerInstanceId), + ); + if (userRuns.length > 0 && !heldBehindLimit) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, @@ -6577,6 +6647,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ]); }); + // Providers own native subagent conversations; messages cannot target them, and adapters ask questions on the parent. + const refuseNativeSubagentMessage = Effect.fnUntraced(function* ( + command: Pick & { readonly threadId: ThreadId }, + ) { + const thread = yield* projectionStore + .getThread(command.threadId) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + if (isProviderNativeSubagentThread(thread)) { + return yield* new OrchestratorSubagentThreadReadOnlyError({ + commandId: command.commandId, + threadId: command.threadId, + }); + } + return thread; + }); + const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* ( command: Extract, events: Ref.Ref>, @@ -7536,6 +7626,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), + ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined + ? { followsThreadSelection: true as const } + : {}), id: command.messageId, threadId: command.threadId, runId, @@ -7948,6 +8041,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.senderThreadId === undefined ? {} : { senderThreadId: command.senderThreadId }), ...(command.linkedSender === undefined ? {} : { linkedSender: command.linkedSender }), ...(command.idleCompaction === undefined ? {} : { idleCompaction: command.idleCompaction }), + ...(command.scheduledTaskId !== undefined && command.modelSelection === undefined + ? { followsThreadSelection: true as const } + : {}), id: command.messageId, threadId: command.threadId, runId, @@ -11085,10 +11181,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const emitEvent = emit(events, command); + // A scheduled delivery steers on the thread's current pick, so /goal must suit that provider. + const modelSelection = queuedRunModelSelection(projection, queuedRun); const parsedGoalCommand = parseGoalCommand(queuedMessage); const goalCommand = parsedGoalCommand === null || - (yield* goalDriverFor(command, queuedRun.providerInstanceId)) === undefined + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined ? null : parsedGoalCommand; const target = projection.runs.find((run) => run.id === command.targetRunId); @@ -11102,7 +11200,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio isCompactionCommandMessage(targetMessage) ) { if (goalCommand !== null) { - yield* ensureGoalCommandSupported(command, queuedMessage, queuedRun.providerInstanceId); + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); } yield* emitEvent({ type: "run.updated", @@ -11135,7 +11233,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } if (goalCommand !== null) { - yield* ensureGoalCommandSupported(command, queuedMessage, queuedRun.providerInstanceId); + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); const goal = projection.providerThreads.find( (candidate) => candidate.id === target?.providerThreadId, )?.goal; @@ -11244,7 +11342,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events, effects, projection, - modelSelection: queuedRun.modelSelection, + modelSelection, targetRunId: command.targetRunId, messageId: queuedMessage.id, text: queuedMessage.text, @@ -11468,7 +11566,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* ensureGoalCommandSupported( command, { text: command.text, attachments: command.attachments ?? queuedMessage.attachments }, - queuedRun.providerInstanceId, + queuedRunModelSelection(projection, queuedRun).instanceId, ); const queuedTurnItem = projection.turnItems.find( (candidate) => candidate.type === "user_message" && candidate.messageId === queuedMessage.id, @@ -11900,6 +11998,78 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + // Ends each native subagent's record, its own thread's runless root turns, and the + // subagents it started there, which a provider can record on that thread rather than its parent's. + const endNativeSubagentTrees = Effect.fn("Orchestrator.endNativeSubagentTrees")( + function* (input: { + readonly command: Extract< + OrchestrationV2ServerCommand, + { readonly type: "run.interrupt" | "thread.background-work.settle" | "thread.stop" } + >; + readonly events: Ref.Ref>; + readonly dying: ReadonlyArray; + readonly childThreadIds: Set; + readonly now: DateTime.Utc; + }) { + const allocateEventId = () => + idAllocator.allocate.event({ + threadId: input.command.threadId, + commandId: input.command.commandId, + }); + const dying = [...input.dying]; + const { childThreadIds } = input; + for (const { projection, subagent } of dying) { + const ended = yield* endOrphanedNativeSubagent({ + projection, + subagentId: subagent.subagentId, + status: "interrupted", + now: input.now, + emitted: yield* Ref.get(input.events), + allocateEventId, + }).pipe(mapDispatchError(input.command)); + yield* Ref.update(input.events, (events) => [...events, ...ended]); + const childThreadId = subagent.childThreadId; + if ( + subagent.origin !== "provider_native" || + childThreadId === null || + childThreadIds.has(childThreadId) + ) { + continue; + } + childThreadIds.add(childThreadId); + const child = yield* projectionStore + .getThreadRecords(childThreadId, ["nodes", "providerTurns", "subagents", "turnItems"], { + // Runless items are the subagent's; any run there is the user's own. + turnItemRunIds: [null], + turnItemStatuses: ["pending", "running", "waiting"], + }) + .pipe( + Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), + mapDispatchError(input.command), + ); + if (child === null) continue; + const childEnded = yield* endRunlessRootTurns({ + threadId: childThreadId, + providerInstanceId: subagent.providerInstanceId, + projection: child, + status: "interrupted", + now: input.now, + emitted: yield* Ref.get(input.events), + allocateEventId, + }).pipe(mapDispatchError(input.command)); + yield* Ref.update(input.events, (events) => [...events, ...childEnded]); + for (const nested of child.turnItems) { + if (nested.type === "subagent") dying.push({ projection: child, subagent: nested }); + } + for (const nested of child.subagents) { + if (nested.origin === "provider_native" && nested.runId === null) { + dying.push({ projection: child, subagent: nativeSubagentRef(nested) }); + } + } + } + }, + ); + const settleBackgroundWork = Effect.fn("Orchestrator.settleBackgroundWork")(function* (input: { readonly command: Extract< OrchestrationV2ServerCommand, @@ -11916,11 +12086,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }) { const emitEvent = emit(input.events, input.command); const runOrdinals = new Map(input.projection.runs.map((run) => [run.id, run.ordinal])); - const allocateEventId = () => - idAllocator.allocate.event({ - threadId: input.command.threadId, - commandId: input.command.commandId, - }); const childThreadIds = new Set(); const liveness = new Map(); const hasLiveSession = Effect.fn("Orchestrator.hasLiveSession")(function* ( @@ -11985,76 +12150,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, }); if (item.type !== "subagent") continue; - // A native subagent died with the process too: end its record, its own - // thread's runless root turn, and the subagents it started there, which - // a provider can record on that thread rather than this one. - const dying: Array<{ - readonly projection: Pick< - OrchestrationV2ThreadProjection, - "nodes" | "subagents" | "turnItems" - >; - readonly subagent: Pick< - Extract, - "subagentId" | "origin" | "childThreadId" | "providerInstanceId" - >; - }> = [{ projection: input.projection, subagent: item }]; - for (const { projection, subagent } of dying) { - const ended = yield* endOrphanedNativeSubagent({ - projection, - subagentId: subagent.subagentId, - status: "interrupted", - now: input.now, - emitted: yield* Ref.get(input.events), - allocateEventId, - }).pipe(mapDispatchError(input.command)); - yield* Ref.update(input.events, (events) => [...events, ...ended]); - const childThreadId = subagent.childThreadId; - if ( - subagent.origin !== "provider_native" || - childThreadId === null || - childThreadIds.has(childThreadId) - ) { - continue; - } - childThreadIds.add(childThreadId); - const child = yield* projectionStore - .getThreadRecords(childThreadId, ["nodes", "providerTurns", "subagents", "turnItems"], { - // Runless items are the subagent's; any run there is the user's own. - turnItemRunIds: [null], - turnItemStatuses: ["pending", "running", "waiting"], - }) - .pipe( - Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }), - mapDispatchError(input.command), - ); - if (child === null) continue; - const childEnded = yield* endRunlessRootTurns({ - threadId: childThreadId, - providerInstanceId: subagent.providerInstanceId, - projection: child, - status: "interrupted", - now: input.now, - emitted: yield* Ref.get(input.events), - allocateEventId, - }).pipe(mapDispatchError(input.command)); - yield* Ref.update(input.events, (events) => [...events, ...childEnded]); - for (const nested of child.turnItems) { - if (nested.type === "subagent") dying.push({ projection: child, subagent: nested }); - } - for (const nested of child.subagents) { - if (nested.origin === "provider_native" && nested.runId === null) { - dying.push({ - projection: child, - subagent: { - subagentId: nested.id, - origin: nested.origin, - childThreadId: nested.childThreadId, - providerInstanceId: nested.providerInstanceId, - }, - }); - } - } - } + // A native subagent died with the process too. + yield* endNativeSubagentTrees({ + command: input.command, + events: input.events, + dying: [{ projection: input.projection, subagent: item }], + childThreadIds, + now: input.now, + }); } for (const providerThread of input.projection.providerThreads) { if ((providerThread.pendingBackgroundTasks?.length ?? 0) === 0) continue; @@ -13530,6 +13633,36 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio for (const run of reached.values()) { yield* markStoppedRun({ command, events, thread: projection.thread, run, now }); } + // Record and item are written together, so an active record without a live item lost its end. + const staleNative = (target === undefined ? projection.subagents : []).filter( + (subagent) => + subagent.origin === "provider_native" && + subagent.runId !== null && + isOrchestrationV2WorkActive(subagent.status) && + !projection.turnItems.some( + (item) => item.type === "subagent" && item.subagentId === subagent.id, + ), + ); + if (staleNative.length > 0) { + const { nodes } = yield* projectionStore + .getThreadRecords(command.threadId, ["nodes"]) + .pipe(mapDispatchError(command)); + const threadProjection = { + nodes, + subagents: projection.subagents, + turnItems: projection.turnItems, + }; + yield* endNativeSubagentTrees({ + command, + events, + dying: staleNative.map((subagent) => ({ + projection: threadProjection, + subagent: nativeSubagentRef(subagent), + })), + childThreadIds: new Set(), + now, + }); + } yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now }); yield* cancelIdleOrphans({ command, events, projection }); yield* stopDelegatedTasks; @@ -14047,13 +14180,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { return; } - const taskRuns = childControls.runs.filter((run) => run.delegatedTaskId === options.task.id); + const taskRuns = delegatedTaskRuns(childControls, options.task.id); const childRun = taskRuns.length === 0 ? options.task.id === forkedFrom.nodeId ? options.resultRun : undefined - : delegatedTaskResultRun(taskRuns, options.task.id); + : delegatedTaskResultRun(taskRuns); if (childRun === undefined) return; let outcome = runOutcome(childRun); let terminalStatus = delegatedTaskTerminalStatus(outcome); @@ -14113,6 +14246,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ]); return; } + // A follow-up ends with the subagents its turns started, as the original task does. + if (delegatedTaskAwaitsSubagents(taskRuns, childControls.subagents)) return; if ( yield* childAwaitsRestartContinuation( taskRuns.length === 0 ? childControls.runs : taskRuns, @@ -14755,7 +14890,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "thread.active.reorder": case "thread.tag.set": case "thread.mark-unread": - case "thread.metadata.update": case "thread.pull-request.link": case "thread.pull-request.unlink": case "thread.pull-request-link.sync": @@ -14768,6 +14902,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "provider.switch": yield* dispatchThreadMutation(command, events, effects); break; + case "thread.metadata.update": { + const continuation = metadataUpdateContinuation(command); + if (continuation !== undefined) yield* refuseNativeSubagentMessage(command); + yield* dispatchThreadMutation(command, events, effects); + if (continuation !== undefined) { + cancelUnsettledEffects = yield* dispatchMessage(continuation, events, effects); + yield* recordSubagentFollowup(continuation, events).pipe(mapDispatchError(command)); + } + break; + } case "thread.pull-request-watch.checks-reopen": yield* dispatchThreadMutation(command, events, effects); break; @@ -14788,20 +14932,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* dispatchThreadProjectAdoptFolder(command, events); break; case "message.dispatch": { - // Providers own native subagent conversations; messages cannot target them, and adapters ask questions on the parent. - const thread = yield* projectionStore - .getThread(command.threadId) - .pipe( - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), - ), - ); - if (isProviderNativeSubagentThread(thread)) { - return yield* new OrchestratorSubagentThreadReadOnlyError({ - commandId: command.commandId, - threadId: command.threadId, - }); - } + const thread = yield* refuseNativeSubagentMessage(command); const guestSend = command.guestMessageId === undefined ? undefined @@ -15132,6 +15263,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio planned.events.length > 0 || isUnobservedAcknowledgement(command) || command.type === "thread.background-work.settle" || + // A stale visit changes no read state. + command.type === "thread.visit" || // A read can answer a watch again before a push's reopen lands; nothing is left to clear. command.type === "thread.pull-request-watch.checks-reopen" || command.type === "thread.interrupt.unresponsive" || @@ -15387,11 +15520,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); // Taken before the lineage read, so a message whose read yields keeps its // place ahead of later messages to the same thread. - if (command.type === "message.dispatch") + const message = + command.type === "thread.metadata.update" ? metadataUpdateContinuation(command) : command; + if (message?.type === "message.dispatch") return yield* messageIntake.withLock( - command.threadId, - mayStartSubagentFollowup(command) - ? withSubagentParentLock(command.threadId, dispatch) + message.threadId, + mayStartSubagentFollowup(message) + ? withSubagentParentLock(message.threadId, dispatch) : dispatch, ); // Answering a message-mode question can also start a follow-up. @@ -15785,9 +15920,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio { messageRoles: ["user"] }, ); if (taskId !== undefined) { - const runs = child.runs.filter((run) => run.delegatedTaskId === taskId); - const run = delegatedTaskResultRun(runs, taskId); - if (run === undefined || delegatedTaskTerminalStatus(run.status) === null) return true; + const runs = delegatedTaskRuns(child, taskId); + const run = delegatedTaskResultRun(runs); + if ( + run === undefined || + delegatedTaskTerminalStatus(run.status) === null || + delegatedTaskAwaitsSubagents(runs, child.subagents) + ) + return true; return yield* childAwaitsRestartContinuation(runs, run); } const progress = delegatedTaskProgress(child); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index fb2dbb0bfe4c9..d2b8b2145c62f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -4333,9 +4333,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { workCursor = page.nextCursor; } assert.strictEqual(workIds.size, 999); - for (const toolName of ["t3-code.delegate_task", "mcp__t3_code__delegate_task"]) { + for (const [toolName, output] of [ + ["t3-code.delegate_task", null], + ["mcp__t3_code__delegate_task", null], + ["mcp__t3-code__send_to_user", null], + // OpenCode Code Mode reports a nested send_to_user call as one `execute` item. + ["execute", JSON.stringify({ sentMessage: "Draft" })], + ] as const) { yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', - payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', ${toolName}) + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', ${toolName}, + '$.output', ${output}) WHERE thread_id = ${threadId} AND ordinal = 2`; const window = yield* projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: sqlPageLimit, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index c4480d5bc6796..45b98911433cf 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,5 +1,5 @@ import type { ProjectThreadAwarenessV2Input } from "@t3tools/shared/agentAwareness"; -import { pendingGuestMessageCount } from "@t3tools/contracts"; +import { applyOrchestrationV2ThreadVisit, pendingGuestMessageCount } from "@t3tools/contracts"; import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts"; import { projectTurnItemForWire } from "./WireProjection.ts"; import * as Stream from "effect/Stream"; @@ -932,6 +932,11 @@ export function applyToProjection( ...projection, thread: event.payload, }; + case "thread.visit-recorded": + return { + ...projection, + thread: applyOrchestrationV2ThreadVisit(projection.thread, event.payload), + }; case "run.created": case "run.updated": return withLocalVisibleTurnItems({ @@ -2137,7 +2142,9 @@ export const layer: Layer.Layer = const inlineWorkOutput = sql`item.type = 'dynamic_tool' AND ( item.payload_json LIKE '%htmlRender%' OR item.payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`} OR item.payload_json LIKE '%"viewedImagePath"%' - OR item.payload_json LIKE '%"toolName":"%delegate_task"%')`; + OR item.payload_json LIKE '%"toolName":"%delegate_task"%' + OR item.payload_json LIKE '%"toolName":"%send_to_user"%' + OR item.payload_json LIKE '%sentMessage%')`; // SQLite uses the partial conversation index of migration 082 only for this exact predicate. const CONVERSATION_INDEX_EXCLUDED_TYPES = sql.literal( @@ -2256,6 +2263,15 @@ export const layer: Layer.Layer = }); break; } + case "thread.visit-recorded": { + const thread = yield* getThread(event.threadId); + yield* apply({ + ...event, + type: "thread.visited", + payload: applyOrchestrationV2ThreadVisit(thread, event.payload), + }); + break; + } case "thread.created": case "thread.archived": case "thread.unarchived": @@ -3088,6 +3104,7 @@ export const layer: Layer.Layer = event.type !== "thread.active-reordered" && event.type !== "thread.tags-updated" && event.type !== "thread.visited" && + event.type !== "thread.visit-recorded" && event.type !== "thread.marked-unread" && event.type !== "thread.metadata-updated" && event.type !== "thread.pull-request-synced" && diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index bd13d2a3c1ff3..4626e5a0a735a 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -49,8 +49,10 @@ import * as ProviderEventIngestor from "./ProviderEventIngestor.ts"; import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import { UsageLimitResetFallback } from "../usage/UsageLimitSources.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; +import type { ServerProvider } from "@t3tools/contracts"; import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import { makeProviderEventRoutingState, @@ -230,7 +232,7 @@ function threadCreatedEvent( const layer = it.layer(layerTest); -it.effect("refreshes the failing instance snapshot after a committed usage_limit terminal", () => +it.effect("takes a hub's reset for an unreset usage_limit, then refreshes the snapshot", () => Effect.gen(function* () { const refreshed = yield* Deferred.make(); const adapter = yield* ProviderAdapter.ProviderAdapterV2.pipe( @@ -261,7 +263,9 @@ it.effect("refreshes the failing instance snapshot after a committed usage_limit }, snapshot: { refreshUsage: Deferred.succeed(refreshed, undefined).pipe(Effect.asVoid), - getSnapshot: Effect.die("unused"), + getSnapshot: Effect.succeed({ + auth: { status: "authenticated", endpoint: "http://hub.test:8317" }, + } as ServerProvider), refresh: Effect.die("unused"), resolveMaintenance: () => Effect.die("unused"), applyUsageLimits: () => Effect.die("unused"), @@ -269,6 +273,7 @@ it.effect("refreshes the failing instance snapshot after a committed usage_limit }, }; const lookups: ProviderInstanceId[] = []; + const hubLookups: Array<[string, string, string | null]> = []; const instances = Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({ getInstance: (id) => Effect.sync(() => { @@ -317,10 +322,29 @@ it.effect("refreshes the failing instance snapshot after a committed usage_limit }); assert.equal(stored.length, 1); if (failureClass === "validation_error") assert.deepEqual(lookups, []); + else { + const event = stored[0]?.event; + assert.equal( + event?.type === "turn-item.updated" && event.payload.type === "error" + ? event.payload.failure.resetAt + : undefined, + "2026-11-13T18:00:00.000Z", + ); + } } - assert.deepEqual(lookups, [instance.instanceId]); + assert.deepEqual(lookups, [instance.instanceId, instance.instanceId]); + assert.deepEqual(hubLookups, [["cursor", "http://hub.test:8317", "gpt-5.4"]]); yield* Deferred.await(refreshed); - }).pipe(Effect.provide(makeLayerTest(layerTestEventSink, instances))); + }).pipe( + Effect.provide(makeLayerTest(layerTestEventSink, instances)), + Effect.provideService(UsageLimitResetFallback, { + resetAt: (driver, endpoint, model) => + Effect.sync(() => { + hubLookups.push([driver, endpoint, model]); + return "2026-11-13T18:00:00.000Z"; + }), + }), + ); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index b4c20407ce9cd..027c3662cecbd 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -32,6 +32,7 @@ import { } from "../telemetry/ProviderUsageAnalytics.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import { UsageLimitResetFallback } from "../usage/UsageLimitSources.ts"; import * as EventSink from "./EventSink.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -254,6 +255,7 @@ export const layer: Layer.Layer< const analytics = yield* ProviderTurnAnalytics; const agentScope = yield* AgentScope; const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; + const usageLimitResets = yield* UsageLimitResetFallback; const scope = yield* Effect.scope; const completedTurnAnalytics = new Set(); @@ -681,9 +683,39 @@ export const layer: Layer.Layer< return dismissed; } const occurredAt = yield* DateTime.now; - const failure = (yield* agentScope.oomKilled(input.threadId)) + const reported = (yield* agentScope.oomKilled(input.threadId)) ? { ...input.event.failure, message: "Killed: out of memory.", code: "oom_kill" } : input.event.failure; + // A proxied CLI can drop the reset time; the hub still knows when its pool refills. + const endpoint = + reported.class === "usage_limit" && reported.resetAt == null + ? (yield* Effect.flatMap( + instances.getInstance(input.providerInstanceId), + (instance) => instance?.snapshot.getSnapshot ?? Effect.undefined, + ))?.auth.endpoint + : undefined; + const hubResetAt = + endpoint === undefined + ? null + : yield* Effect.gen(function* () { + // The failing run's model, which may differ from a selection changed mid-turn. + const { runs } = + input.runId === undefined + ? { runs: [] } + : yield* projections.getThreadRecords(input.threadId, ["runs"], { + runIds: [input.runId], + }); + return ( + runs[0]?.modelSelection ?? + (yield* projections.getThread(input.threadId)).modelSelection + ).model; + }).pipe( + Effect.orElseSucceed(() => null), + Effect.flatMap((model) => + usageLimitResets.resetAt(input.event.driver, endpoint, model), + ), + ); + const failure = hubResetAt === null ? reported : { ...reported, resetAt: hubResetAt }; return [ ...dismissed, yield* makeDomainEvent(input, { diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index aaadba35cb566..5ddc93cc948be 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3410,10 +3410,19 @@ it.effect.each(["detach", "stream failure", "provider stop", "early close"] as c ); yield* interrupts(1); yield* Deferred.succeed(resume, undefined); + const consumed = yield* Fiber.join(consumer); assert.equal( - Exit.isFailure(yield* Fiber.join(consumer)), + Exit.isFailure(consumed), release !== "provider stop" && release !== "early close", ); + // regression: #22971 only a detach names its thread, so a handoff run can settle on it. + assert.equal( + Exit.isFailure(consumed) + ? (Cause.squash(consumed.cause) as ProviderAdapter.ProviderAdapterEventStreamError) + .detachedThreadId + : undefined, + release === "detach" ? threadId : undefined, + ); yield* interrupts(2); assert.isTrue(Option.isNone(yield* manager.get(providerSessionId))); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index c2f7eb767945d..eb56df9d049ac 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -655,10 +655,12 @@ export const layerWithOptions = ( detail: string, afterDrain: Effect.Effect, cause?: Cause.Cause, + detachedThreadId?: ThreadId, ) { const error = new ProviderAdapter.ProviderAdapterEventStreamError({ driver: entry.runtime.driver, providerSessionId: entry.runtime.providerSessionId, + ...(detachedThreadId === undefined ? {} : { detachedThreadId }), cause: detail, }); const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map()); @@ -1280,6 +1282,7 @@ export const layerWithOptions = ( input.detail ?? `Provider session released: ${input.reason}.`, afterDrain, input.eventStreamCause, + input.detachedThreadId, ); } const closeExit = yield* closeScopeWithin(entry.scope, { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 62f095b6fd913..4bb16d5c6d74f 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -40,6 +40,10 @@ import { withWorkspaceLease, } from "../workspace/workspaceLease.ts"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; +import { + layerThreadWorktreeRestore, + ThreadWorktreeRestore, +} from "../workspace/restoreMissingWorktree.ts"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; import { layerRealGit } from "./ProviderTurnStartService.testkit.ts"; import * as ProjectService from "../project/ProjectService.ts"; @@ -272,6 +276,101 @@ it.each([ expect(harness.createWorktree).toHaveBeenCalledTimes(input.recreated ? 1 : 0); }); +const restoreLeaseExists = vi.fn(() => Effect.succeed(false)); +const restoreLeaseCreateWorktree = vi.fn(() => Effect.succeed({} as never)); +const layerRestoreLeaseTest = layerThreadWorktreeRestore.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(FileSystem.FileSystem, { + exists: restoreLeaseExists, + realPath: (target: string) => Effect.succeed(normalize(target)), + } as never), + layerWorktreeLocation(), + Layer.mock(GitWorkflow.GitWorkflowService)({ + pruneWorktrees: () => Effect.void, + createWorktree: restoreLeaseCreateWorktree, + listLocalBranchNames: () => Effect.succeed(["feature/restore"]), + }), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ workspaceRoot: "/tmp/provider-turn-start-project" } as never), + }), + ), + ), +); + +effectIt.effect("restores a missing worktree before a send only under the workspace lease", () => + Effect.gen(function* () { + const worktreePath = `${managedWorktreesDir}/project/feature-restore`; + const { restore } = yield* ThreadWorktreeRestore; + yield* withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + const restoring = yield* restore({ + id: ThreadId.make("thread_send_restore_lease"), + projectId: ProjectId.make("project_send_restore_lease"), + worktreePath, + branch: "feature/restore", + }).pipe(Effect.forkChild({ startImmediately: true })); + expect(restoreLeaseExists).not.toHaveBeenCalled(); + return restoring; + }), + ).pipe(Effect.flatMap(Fiber.join)); + expect(restoreLeaseCreateWorktree).toHaveBeenCalledTimes(1); + }).pipe(Effect.provide(layerRestoreLeaseTest)), +); + +it.each([ + { label: "directly in the scratch root", folder: "/tmp/t3-home/scratch/notes", recreated: true }, + { label: "below another folder", folder: "/tmp/t3-home/scratch/notes/deep", recreated: false }, + { + label: "in another project", + folder: "/tmp/elsewhere/notes", + workspaceRoot: "/tmp/elsewhere", + recreated: false, + }, +])("recreates a pruned No project folder only $label", async (input) => { + const makeDirectory = vi.fn(() => Effect.void); + await Effect.gen(function* () { + const { restore } = yield* ThreadWorktreeRestore; + yield* restore({ + id: ThreadId.make("thread_scratch_restore"), + projectId: ProjectId.make("project_scratch_restore"), + worktreePath: input.folder, + branch: null, + }); + }).pipe( + Effect.provide( + layerThreadWorktreeRestore.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(FileSystem.FileSystem, { + exists: () => Effect.succeed(false), + realPath: (target: string) => Effect.succeed(target), + makeDirectory, + } as never), + Path.layer, + Layer.mock(ServerConfig.ServerConfig)({ + baseDir: "/tmp/t3-home", + worktreesDir: managedWorktreesDir, + } as ServerConfig.ServerConfig["Service"]), + ServerSettings.layerTest(), + Layer.mock(GitWorkflow.GitWorkflowService)({}), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ + workspaceRoot: input.workspaceRoot ?? "/tmp/t3-home/scratch", + } as never), + }), + ), + ), + ), + ), + Effect.runPromise, + ); + expect(makeDirectory).toHaveBeenCalledTimes(input.recreated ? 1 : 0); +}); + function makeLocalCommandHarness(input: { readonly text: string; readonly nativeGoals?: boolean; @@ -1127,6 +1226,8 @@ effectIt.effect( const expectedTips = { retained: { tip: threadTip, file: "thread.txt", upstream: null, base: "" }, + // A failed removal can leave the folder behind with only dependencies inside. + leftover: { tip: threadTip, file: "thread.txt", upstream: null, base: "" }, deleted: { tip: projectTip, file: "project.txt", upstream: null, base: "project-current" }, pushed: { tip: threadTip, @@ -1171,7 +1272,12 @@ effectIt.effect( yield* git(workspaceRoot, ["remote", "remove", "origin"]); } yield* fileSystem.remove(worktreePath, { recursive: true }); - if (scenario !== "retained") { + if (scenario === "leftover") { + yield* fileSystem.makeDirectory(path.join(worktreePath, "node_modules"), { + recursive: true, + }); + } + if (scenario !== "retained" && scenario !== "leftover") { yield* git(workspaceRoot, ["worktree", "prune"]); yield* git(workspaceRoot, ["branch", "-D", "feature/restore"]); } @@ -1220,6 +1326,27 @@ effectIt.effect( }).pipe(Effect.scoped, Effect.provide(layerRealGit)), ); +effectIt.effect("leaves a managed worktree folder without .git that holds user files", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const worktreesDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-leftover-" }); + const worktreePath = path.join(worktreesDir, "project", "restore"); + yield* fileSystem.makeDirectory(path.join(worktreePath, "node_modules"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(worktreePath, "notes.md"), "keep me"); + const harness = makeLocalCommandHarness({ + text: "Continue", + worktreePath, + worktreesDir, + fileSystem, + failReadsAfterRunning: true, + }); + yield* harness.start; + expect(harness.createWorktree).not.toHaveBeenCalled(); + expect(yield* fileSystem.readFileString(path.join(worktreePath, "notes.md"))).toBe("keep me"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + effectIt.effect( "preserves recreation interrupts and retries, then fails the final attempt before provider start", () => diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 8f01d117e1739..ddb9416682710 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1639,12 +1639,11 @@ export const layer: Layer.Layer< .filter((part) => part !== "") .join("\n\n"); const { restartContinuationOfRunId: _resumedRunId, ...promptedInput } = turnInput; + const text = goalCommand ? userText : withInlineContext(context, userText); yield* start({ ...(noteContinuation ? promptedInput : turnInput), - message: { - ...turnInput.message, - text: goalCommand ? userText : withInlineContext(context, userText), - }, + message: { ...turnInput.message, text }, + ...(text === userText ? {} : { inlineContextLength: text.length - userText.length }), }).pipe( // Clear pending handoff markers for refused prompts so the next turn retains the native session. Effect.tapError((error) => diff --git a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts index 48029bdc75fd1..3de10f4e944ad 100644 --- a/apps/server/src/orchestration-v2/RestartBackgroundNote.ts +++ b/apps/server/src/orchestration-v2/RestartBackgroundNote.ts @@ -1,12 +1,15 @@ import type { NodeId, + OrchestrationV2ConversationMessage, OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderTurn, OrchestrationV2RestartCancelledBackgroundWork, OrchestrationV2Run, OrchestrationV2RunAttempt, + OrchestrationV2Subagent, OrchestrationV2TurnItem, } from "@t3tools/contracts"; +import { subagentHoldsCompletion } from "@t3tools/provider-core/server/subagentProjection"; import { latestRootProviderFailure, runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; type Work = OrchestrationV2RestartCancelledBackgroundWork; @@ -187,14 +190,56 @@ export function cancelledBeforeStart( return run.status === "cancelled" && neverStarted(run); } +/** A follow-up task's runs: those tagged with it, and the untagged wakes for subagents they started. */ +export function delegatedTaskRuns( + projection: { + readonly runs: ReadonlyArray; + readonly messages: ReadonlyArray< + Pick + >; + }, + taskId: NodeId, +): ReadonlyArray { + const owned = new Set( + projection.runs.filter((run) => run.delegatedTaskId === taskId).map((run) => run.id), + ); + const untagged = new Set( + projection.runs.filter((run) => run.delegatedTaskId === undefined).map((run) => run.id), + ); + for (let grew = owned.size > 0; grew;) { + grew = false; + for (const { runId, delegatedCompletion } of projection.messages) { + if ( + runId === null || + !untagged.has(runId) || + owned.has(runId) || + delegatedCompletion === undefined || + !owned.has(delegatedCompletion.parentRunId) + ) + continue; + owned.add(runId); + grew = true; + } + } + return projection.runs.filter((run) => owned.has(run.id)); +} + +/** A follow-up task's runs still owe a subagent they started its result. */ +export function delegatedTaskAwaitsSubagents( + runs: ReadonlyArray, + subagents: ReadonlyArray< + Pick + >, +): boolean { + const runIds = new Set(runs.map((run) => run.id)); + return subagents.some((task) => runIds.has(task.runId) && subagentHoldsCompletion(task)); +} + /** A follow-up task's latest run, passing over queued work it no longer waits on, as the original task does. */ export function delegatedTaskResultRun( runs: ReadonlyArray, - taskId: NodeId, ): OrchestrationV2Run | undefined { - const taskRuns = runs - .filter((run) => run.delegatedTaskId === taskId) - .toSorted((a, b) => b.ordinal - a.ordinal); + const taskRuns = runs.toSorted((a, b) => b.ordinal - a.ordinal); const awaited = taskRuns.filter( (run) => !cancelledBeforeStart(run) && !(run.status === "queued" && run.queueHeld === true), ); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 4f3dcac6c439b..a9ea3b969d5b0 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -546,6 +546,8 @@ export class RunExecutionStartError extends Schema.TaggedError()( "RunExecutionIngestError", { @@ -557,6 +559,7 @@ export class RunExecutionIngestError extends Schema.TaggedError + input.shouldFinalizeRun === undefined || input.hasWorkspaceMoved === undefined + ? Effect.succeed(false) + : input.hasWorkspaceMoved(), + ); const finalizeRootRun = Effect.fn("RunExecutionService.finalizeRootRun")(function* ( terminal: ProviderTerminalEvent, + abandonedProviderTurn?: OrchestrationV2ProviderTurn, ) { if (yield* Ref.get(rootRunFinalized)) { return; @@ -1155,6 +1165,7 @@ export const layer: Layer.Layer< : { loadRunInterruptReason: input.loadRunInterruptReason }), openRunOwnedSubagents: openSubagents, openRunOwnedSubagentsTerminal: terminal, + ...(abandonedProviderTurn === undefined ? {} : { abandonedProviderTurn }), terminal: settledTerminal, completionSilent, failureItemPersisted: settledTerminal.status === "failed", @@ -1168,11 +1179,7 @@ export const layer: Layer.Layer< // for it: the run completes, while its native subagents still settle // as interrupted. The completed write refuses in the same transaction // as a stored Stop request, so a racing Stop stays authoritative. - const handedOff = - terminal.status === "interrupted" && - input.shouldFinalizeRun !== undefined && - input.hasWorkspaceMoved !== undefined && - (yield* input.hasWorkspaceMoved()); + const handedOff = terminal.status === "interrupted" && (yield* workspaceHandedOff); if (!handedOff || !(yield* writeTerminal({ ...terminal, status: "completed" }))) { yield* writeTerminal(terminal); } @@ -1753,14 +1760,51 @@ export const layer: Layer.Layer< (cause) => Effect.gen(function* () { const completedAt = yield* DateTime.now; + const routing = yield* Ref.get(eventRouting); + const rootProviderTurn = yield* Ref.get(latestRootProviderTurn); + const squashed = Cause.squash(cause); + // An exclusive session closes when its thread detaches, and no terminal + // follows. The process is gone, so a handoff settles here with no interrupt. + if ( + isRunExecutionIngestError(squashed) && + isProviderEventStreamError(squashed.cause) && + squashed.cause.detachedThreadId === input.run.threadId && + (yield* workspaceHandedOff) + ) { + const handedOff = yield* finalizeRootRun( + { + type: "turn.terminal", + driver: input.providerThread.driver, + providerThreadId: input.providerThread.id, + providerTurnId: routing.rootProviderTurnId ?? failedProviderTurnId, + runOrdinal: input.run.ordinal, + status: "interrupted", + failure: null, + threadDisposition: "reusable", + }, + rootProviderTurn === null || + isTerminalProviderTurnStatus(rootProviderTurn.status) + ? undefined + : { ...rootProviderTurn, status: "interrupted", completedAt }, + ).pipe( + Effect.as(true), + Effect.catchCauseIf( + (settleCause) => !Cause.hasInterruptsOnly(settleCause), + (settleCause) => + Effect.logWarning( + "orchestration V2 failed to settle a run after its workspace handoff", + { runId: input.run.id, cause: settleCause }, + ).pipe(Effect.as(false)), + ), + ); + if (handedOff) return; + } yield* Effect.logWarning("orchestration V2 provider event ingestion failed", { runId: input.run.id, cause, }); if (yield* Ref.get(rootRunFinalized)) return; const providerThread = yield* Ref.get(latestProviderThread); - const routing = yield* Ref.get(eventRouting); - const rootProviderTurn = yield* Ref.get(latestRootProviderTurn); // Stop background work too; the failed consumer cannot persist terminal events. const abandonedProviderTurn = routing.rootProviderTurnId !== null && !routing.rootTurnEnded @@ -1798,7 +1842,6 @@ export const layer: Layer.Layer< : null; const latestItemOrdinal = yield* Ref.get(latestTurnItemOrdinal); const openSubagents = yield* Ref.get(openRunOwnedSubagents); - const squashed = Cause.squash(cause); let nextRetryWarningAt = completedAt; yield* writeFinalRunEvents({ run: input.run, diff --git a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts index 2dcbbd2ba2e15..7b12f72f4cead 100644 --- a/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts +++ b/apps/server/src/orchestration-v2/SelectionRestart.integration.test.ts @@ -443,114 +443,153 @@ it.live("retries a failed selection restart session open before completing", () }), ); -it.live("a workspace handoff during a run does not leave the run interrupted", () => - Effect.gen(function* () { - const cwd = yield* checkpointWorkspace("workspace-handoff-lifecycle"); - const handoffCwd = yield* checkpointWorkspace("workspace-handoff-lifecycle-target"); - const threadId = ThreadId.make("thread:workspace-handoff-lifecycle"); - const state = yield* Ref.make({ - activeTurn: null, - opened: [], - started: [], - closedSessionCount: 0, - failedReplacementOpen: false, - }); - const layerRegistry = ProviderAdapterRegistry.layerSingle(makeRestartAdapter(state)); +// regression: #22971 an exclusive session closes on detach; that failed the run and held the queue +it.live.each(["pooled", "exclusive"] as const)( + "a workspace handoff on a %s session completes its run and starts the queued continuation", + (mode) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace(`workspace-handoff-${mode}`); + const handoffCwd = yield* checkpointWorkspace(`workspace-handoff-${mode}-target`); + const threadId = ThreadId.make(`thread:workspace-handoff:${mode}`); + const state = yield* Ref.make({ + activeTurn: null, + opened: [], + started: [], + closedSessionCount: 0, + failedReplacementOpen: false, + }); + const base = makeRestartAdapter( + state, + mode === "pooled" ? pooledCapabilities : exclusiveCapabilities, + ); + // A session that closes on detach is never asked to interrupt: Claude's cannot answer. + const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = + mode === "pooled" + ? base + : { + ...base, + openSession: (input) => + base.openSession(input).pipe( + Effect.map((session) => ({ + ...session, + interruptTurn: () => Effect.die("an exclusive handoff must not interrupt"), + })), + ), + }; + const layerRegistry = ProviderAdapterRegistry.layerSingle(adapter); - const projection = yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const eventSink = yield* EventSink.EventSinkV2; + const projection = yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const eventSink = yield* EventSink.EventSinkV2; - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:workspace-handoff:create"), - threadId, - projectId: ProjectId.make("project:workspace-handoff"), - title: "Workspace handoff", - modelSelection: initialSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: cwd, - }); - const running = yield* eventSink - .stream({ + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:workspace-handoff:create"), threadId, - afterSequence: yield* eventSink.latestSequence({ threadId }), - }) - .pipe( - Stream.map((stored) => stored.event), - Stream.filter( - (event) => event.type === "provider-turn.updated" && event.payload.status === "running", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - yield* orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make("command:workspace-handoff:first"), - threadId, - messageId: MessageId.make("message:workspace-handoff:first"), - text: "move to a worktree", - attachments: [], - modelSelection: initialSelection, - dispatchMode: { type: "start_immediately" }, - }); - yield* Fiber.join(running); - yield* worker.drain(); + projectId: ProjectId.make("project:workspace-handoff"), + title: "Workspace handoff", + modelSelection: initialSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + }); + const running = yield* eventSink + .stream({ + threadId, + afterSequence: yield* eventSink.latestSequence({ threadId }), + }) + .pipe( + Stream.map((stored) => stored.event), + Stream.filter( + (event) => + event.type === "provider-turn.updated" && event.payload.status === "running", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:workspace-handoff:first"), + threadId, + messageId: MessageId.make("message:workspace-handoff:first"), + text: "move to a worktree", + attachments: [], + modelSelection: initialSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* Fiber.join(running); + yield* worker.drain(); - const settled = yield* eventSink - .stream({ + const settled = yield* eventSink + .stream({ + threadId, + afterSequence: yield* eventSink.latestSequence({ threadId }), + }) + .pipe( + Stream.map((stored) => stored.event), + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.status !== "running" && + event.payload.status !== "queued" && + event.payload.status !== "starting", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + // What t3_worktree_handoff dispatches while the calling turn is still running. + const bound = yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("command:workspace-handoff:rebind"), threadId, - afterSequence: yield* eventSink.latestSequence({ threadId }), - }) - .pipe( - Stream.map((stored) => stored.event), - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.status !== "running" && - event.payload.status !== "queued" && - event.payload.status !== "starting", + branch: "repro-handoff", + worktreePath: handoffCwd, + continuation: { + messageId: MessageId.make("message:workspace-handoff:continuation"), + text: "continue in the worktree", + }, + }); + // The detach can settle the run at once, so its follow-up must exist in the same commit. + assert.deepEqual( + bound.storedEvents.flatMap(({ event }) => + event.type === "run.created" ? [event.payload.status] : [], ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, + ["queued"], ); - // What t3_worktree_handoff dispatches while the calling turn is still running. - yield* orchestrator.dispatch({ - type: "thread.metadata.update", - commandId: CommandId.make("command:workspace-handoff:rebind"), - threadId, - branch: "repro-handoff", - worktreePath: handoffCwd, - }); - yield* Fiber.join(settled); - yield* worker.drain(); - return yield* orchestrator.getThreadProjection(threadId); - }).pipe( - Effect.provide( - ProviderReplayHarness.layerWithRegistry( - { name: "workspace-handoff-lifecycle" }, - layerRegistry, + yield* Fiber.join(settled); + yield* worker.drain(); + return yield* orchestrator.getThreadProjection(threadId); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: `workspace-handoff-${mode}` }, + layerRegistry, + ), ), - ), - ); + ); - assert.equal(projection.thread.worktreePath, handoffCwd); - assert.equal(projection.runs[0]?.status, "completed"); - assert.isNotNull(projection.runs[0]?.checkpointId ?? null); - assert.isFalse( - projection.turnItems.some((item) => item.type === "run_interrupt_result"), - "an intentional workspace handoff must not project an interrupt result", - ); - }), + assert.equal(projection.thread.worktreePath, handoffCwd); + assert.equal(projection.runs[0]?.status, "completed"); + assert.isNotNull(projection.runs[0]?.checkpointId ?? null); + assert.isFalse( + projection.turnItems.some( + (item) => item.type === "run_interrupt_result" || item.type === "error", + ), + "an intentional workspace handoff must not project an interrupt result or a failure", + ); + assert.deepEqual( + (yield* Ref.get(state)).started.map((turn) => turn.cwd), + [cwd, handoffCwd], + ); + }), ); it.live("Stop during a restart interrupts the turn the restart could not stop", () => diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index c0c8cfae5a804..acfd20af78749 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -11,6 +11,7 @@ import { ProviderInstanceId, ProviderThreadId, ProviderTurnId, + ScheduledTaskId, ThreadId, TurnItemId, type ModelSelection, @@ -511,6 +512,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* onSteer: ( turn: ProviderAdapter.ProviderAdapterV2SteerInput, ) => Effect.Effect = () => Effect.void, + extraAdapters: ReadonlyArray = [], ) { const driver = ProviderDriverKind.make(nativeGoals === undefined ? "codex" : "opencode"); const cwd = yield* checkpointWorkspace(name); @@ -647,7 +649,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* }; const layer = ProviderReplayHarness.layerWithRegistry( { name }, - ProviderAdapterRegistry.layerSingle(adapter), + ProviderAdapterRegistry.layerFromAdapters([adapter, ...extraAdapters]), { runEffectWorker: false }, ); const startFirstTurn = Effect.gen(function* () { @@ -2158,6 +2160,193 @@ it.effect("steers a promoted queued message with the selection it was queued wit }), ); +it.effect("steers a promoted scheduled delivery with the thread's current selection", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "promote-scheduled-selection", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Bound scheduled tasks send like ScheduledTaskService: no model of their own. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("scheduled"), + threadId, + messageId: MessageId.make("message:scheduled"), + scheduledTaskId: ScheduledTaskId.make("task:scheduled"), + text: "scheduled", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + assert.deepEqual(queuedRun.modelSelection, runSelection); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("select-composer"), + threadId, + modelSelection: composerSelection, + }); + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["scheduled"]); + assert.deepEqual(projection.thread.modelSelection, composerSelection); + }).pipe(Effect.provide(layer)); + }), + ), +); + +const claudeSelection = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-test", +}; +const claudeAdapter: ProviderAdapter.ProviderAdapterV2["Service"] = { + instanceId: claudeSelection.instanceId, + driver: ProviderDriverKind.make("claudeAgent"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }), + openSession: () => Effect.die("the Claude instance never starts a turn here"), +}; + +// Queues a scheduled delivery behind the Codex turn, stops that turn (Stop holds the queue), then +// switches the thread to Claude: a thread changes instance only while no run is active. +const scheduledDeliveryAfterClaudeSwitch = (name: string, text: string) => + Effect.gen(function* () { + const harness = yield* nextTurnSelectionHarness( + name, + false, + true, + Effect.void, + true, + undefined, + undefined, + [claudeAdapter], + ); + const queueAndSwitch = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = yield* harness.startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("scheduled"), + threadId, + messageId: MessageId.make("message:scheduled"), + scheduledTaskId: ScheduledTaskId.make("task:scheduled"), + text, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + assert.equal(queuedRun.providerInstanceId, instanceId); + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const first = harness.started[0]!; + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + holdQueue: true, + }); + yield* worker.drain(); + const stopped = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.equal(stopped.find((run) => run.id === first.runId)?.status, "interrupted"); + const held = stopped.find((run) => run.id === queuedRun.id); + assert.equal(held?.status, "queued"); + assert.isTrue(held?.queueHeld); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make("select-claude"), + threadId, + modelSelection: claudeSelection, + }); + return { threadId, queuedRun }; + }); + return { ...harness, queueAndSwitch }; + }); + +it.effect("checks an edited scheduled /goal against the thread's current provider", () => + Effect.scoped( + Effect.gen(function* () { + const { layer, queueAndSwitch } = yield* scheduledDeliveryAfterClaudeSwitch( + "edit-scheduled-goal", + "scheduled", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const { threadId, queuedRun } = yield* queueAndSwitch; + const editError = yield* orchestrator + .dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit"), + threadId, + runId: queuedRun.id, + text: "/goal pause", + }) + .pipe(Effect.flip); + + assert.match(String(editError.cause), /Claude goals cannot be paused or resumed/); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).messages.find( + (message) => message.id === queuedRun.userMessageId, + )?.text, + "scheduled", + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + +it.effect("checks a queued scheduled /goal against the thread's current provider at start", () => + Effect.scoped( + Effect.gen(function* () { + const { started, layer, queueAndSwitch } = yield* scheduledDeliveryAfterClaudeSwitch( + "start-scheduled-goal", + "/goal pause", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const { threadId, queuedRun } = yield* queueAndSwitch; + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make("resume"), + threadId, + }); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + + const projection = yield* orchestrator.getThreadProjection(threadId); + const failure = projection.turnItems.find( + (item) => item.type === "error" && item.runId === queuedRun.id, + ); + assert.equal(started.length, 1); + assert.equal(projection.runs.find((run) => run.id === queuedRun.id)?.status, "failed"); + assert.equal( + failure?.type === "error" ? failure.failure.code : null, + "queued_start_failed", + ); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("marks the model switch on a promoted message that restarts the turn", () => Effect.gen(function* () { const { started, layer, startFirstTurn } = yield* nextTurnSelectionHarness( diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index a798ea62b35fb..d61a220e122aa 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -2806,6 +2806,12 @@ it.effect.each([ startFromOrigin: true, origin: false, }, + { + name: "was deleted on its remote", + baseRef: "origin/development", + startFromOrigin: true, + origin: true, + }, { name: "is a previous checkout there never was", baseRef: "-", @@ -2816,6 +2822,7 @@ it.effect.each([ Effect.gen(function* () { const harness = makeHarness({ hasCommit: ({ refName }) => Effect.succeed(refName === "HEAD"), + fetchWorktreeBaseCommit: () => Effect.succeed(null), git: { resolveWorktreeBaseRemote: () => Effect.succeed(testCase.origin ? { remoteName: "origin", branchName: "main" } : null), diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 5b435627639f8..695d8bb94e490 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -377,11 +377,15 @@ const make = Effect.gen(function* () { // `git worktree add` reads `-` as the previous checkout. if (yield* git.hasCommit({ cwd, refName: baseRef === "-" ? "@{-1}" : baseRef })) return true; - if ( - strategy.startFromOrigin === true && - (yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef })) !== null - ) - return true; + if (strategy.startFromOrigin === true) { + const remote = yield* git.resolveWorktreeBaseRemote({ cwd, refName: baseRef }); + // The remote may have deleted the branch; ask it rather than trusting the name. + if ( + remote !== null && + (yield* git.fetchWorktreeBaseCommit({ cwd, refName: baseRef, remote })) !== null + ) + return true; + } // git worktree add accepts remote-tracking branches; let Git decide when any matching ref exists. if (yield* git.hasRefNamed({ cwd, refName: baseRef })) return true; return !(yield* git.hasCommit({ cwd, refName: "HEAD" })); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 7056e07303c31..c2502902ef8e3 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -38,6 +38,11 @@ import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; +import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; +import { + ThreadWorktreeRestore, + WorktreeRecreateError, +} from "../workspace/restoreMissingWorktree.ts"; it("stamps authoritative provenance on commands that create threads or messages", () => { const command: OrchestrationV2Command = { @@ -199,6 +204,101 @@ it.effect( }, ); +it.effect.each([ + { label: "fails a send that starts a turn", running: false }, + { label: "still steers a running turn", running: true }, +])("sendToThread with a missing worktree that cannot be recreated $label", ({ running }) => { + const projectId = ProjectId.make("project:thread-management:worktree-gone"); + const threadId = ThreadId.make("thread:thread-management:worktree-gone"); + const dispatched: Array = []; + const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe( + Layer.provide( + Layer.succeed(ThreadWorktreeRestore, { + restore: () => + Effect.fail( + new WorktreeRecreateError({ + worktreePath: "/worktrees/gone", + branch: "t3/gone", + cause: new Error("branch_checked_out_in_worktree"), + }), + ), + }), + ), + Layer.provide( + Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({ + ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }), + }), + ), + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadRecords: () => + Effect.succeed({ + thread: { + id: threadId, + projectId, + deletedAt: null, + archivedAt: null, + worktreePath: "/worktrees/gone", + branch: "t3/gone", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" }, + }, + runs: running + ? [ + { + id: RunId.make("run:thread-management:worktree-gone"), + status: "running", + activeAttemptId: "attempt:thread-management:worktree-gone", + }, + ] + : [], + providerTurns: running + ? [ + { + runAttemptId: "attempt:thread-management:worktree-gone", + status: "running", + }, + ] + : [], + messages: [], + turnItems: [], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command.type); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provideMerge(layerReceiptsTest), + ); + + return Effect.gen(function* () { + const threads = yield* ThreadManagementService.ThreadManagementService; + const error = yield* Effect.flip( + threads.sendToThread({ + projectId, + threadId, + commandId: CommandId.make("command:thread-management:worktree-gone"), + messageId: MessageId.make("message:thread-management:worktree-gone"), + text: "Reply with ok.", + attachments: [], + mode: "auto", + createdBy: "agent", + creationSource: "mcp", + }), + ); + // The mock records no message, so a dispatched send ends in the projection read. + expect(error._tag).toBe( + running + ? "ThreadManagementDurableRunProjectionError" + : "ThreadManagementWorktreeRestoreError", + ); + expect(dispatched).toEqual(running ? ["message.dispatch"] : []); + }).pipe(Effect.provide(layerTest)); +}); + it.effect("waitForThread follows a restart continuation instead of the cut run", () => Effect.gen(function* () { const projectId = ProjectId.make("project:thread-management:wait-restart"); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 7450bd6104cfb..d867f0611d2a7 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -69,6 +69,7 @@ import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimi import { projectTurnItemForDetail } from "./WireProjection.ts"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as ServerSettings from "../serverSettings.ts"; +import { ThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts"; export type ThreadManagementSendMode = "auto" | "queue" | "next-tool" | "steer" | "restart"; @@ -316,6 +317,19 @@ export class ThreadManagementDurableRunProjectionError extends Schema.TaggedErro } } +export class ThreadManagementWorktreeRestoreError extends Schema.TaggedError()( + "ThreadManagementWorktreeRestoreError", + { + threadId: ThreadId, + cause: Schema.Defect(), + }, +) { + override get message(): string { + const detail = this.cause instanceof Error ? ` ${this.cause.message}` : ""; + return `Couldn't recreate the missing workspace of thread ${this.threadId}, so the message was not sent.${detail}`; + } +} + export class ThreadManagementProviderInstanceDisabledError extends Schema.TaggedError()( "ThreadManagementProviderInstanceDisabledError", { @@ -360,6 +374,7 @@ export const ThreadManagementError = Schema.Union([ ThreadManagementProjectThreadsListError, ThreadManagementDurableRunProjectionError, ThreadManagementProviderInstanceDisabledError, + ThreadManagementWorktreeRestoreError, ]); export type ThreadManagementError = typeof ThreadManagementError.Type; @@ -592,6 +607,7 @@ const make = Effect.gen(function* () { const legacyImporter = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter; const serverSettings = yield* ServerSettings.ServerSettingsService; const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2; + const worktreeRestore = yield* ThreadWorktreeRestore; const assertProviderInstanceEnabled: ThreadManagementServiceShape["assertProviderInstanceEnabled"] = (input) => @@ -733,6 +749,18 @@ const make = Effect.gen(function* () { const assertDispatchTargetEnabled = (command: OrchestrationV2ServerCommand) => { switch (command.type) { + case "thread.metadata.update": + return command.continuation === undefined + ? Effect.void + : orchestrator.getThreadRecords(command.threadId, []).pipe( + Effect.flatMap((projection) => + assertProviderInstanceEnabled({ + projectId: projection.thread.projectId, + commandId: command.commandId, + instanceId: projection.thread.modelSelection.instanceId, + }), + ), + ); case "message.dispatch": return orchestrator.getThreadRecords(command.threadId, []).pipe( Effect.flatMap((projection) => @@ -874,6 +902,26 @@ const make = Effect.gen(function* () { }; } + // Turn start would fail on its own after the send reported success; a replay keeps its answer. + // A live steer starts no turn, so it needs no workspace. + if (dispatchMode.type !== "steer_active") { + yield* worktreeRestore + .restore(target.thread) + .pipe( + Effect.catch((cause) => + hasReceipt(input.commandId).pipe( + Effect.flatMap((replay) => + replay + ? Effect.void + : Effect.fail( + new ThreadManagementWorktreeRestoreError({ threadId: input.threadId, cause }), + ), + ), + ), + ), + ); + } + const dispatched = yield* dispatch({ type: "message.dispatch", commandId: input.commandId, @@ -1720,6 +1768,12 @@ const make = Effect.gen(function* () { }); }); +const layerThreadWorktreeRestoreNoop = Layer.succeed(ThreadWorktreeRestore, { + restore: Effect.fn("ThreadWorktreeRestore.restore")(function () { + return Effect.void; + }), +}); + const layerLegacyV1ThreadImporterNoop = Layer.succeed( LegacyV1ThreadImporter.LegacyV1ThreadImporter, LegacyV1ThreadImporter.LegacyV1ThreadImporter.of({ @@ -1741,6 +1795,7 @@ export const layer: Layer.Layer< | CommandReceiptStore.CommandReceiptStoreV2 > = Layer.effect(ThreadManagementService, make).pipe( Layer.provide(layerLegacyV1ThreadImporterNoop), + Layer.provide(layerThreadWorktreeRestoreNoop), Layer.provide(ThreadCommandExecutor.layer), ); @@ -1748,6 +1803,7 @@ export const layerWithLegacyImporter: Layer.Layer< ThreadManagementService, never, | LegacyV1ThreadImporter.LegacyV1ThreadImporter + | ThreadWorktreeRestore | Orchestrator.OrchestratorV2 | ProviderSessionManager.ProviderSessionManagerV2 | ServerSettings.ServerSettingsService diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index a48cc3ca7cd90..c6a6cdbf7ac1e 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -27,6 +27,7 @@ function dispatchWasNotAccepted( case "OrchestratorProviderSelectionBusyError": case "OrchestratorRuntimeModeAboveCeilingError": case "ThreadManagementProviderInstanceDisabledError": + case "ThreadManagementWorktreeRestoreError": return true; default: return false; diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index aa847174ac96b..fc52191d32b29 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -1839,6 +1839,154 @@ it.effect.each(["Stop", "Force stop"] as const)( }).pipe(Effect.provide(layerTest)), ); +// A finished delegated child whose native subagent the provider never reported ending, +// with no open turn item, and a nested native subagent on that agent's own thread. +it.effect( + "Stop settles a delegated row whose finished child still records a running native subagent", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const parentThreadId = ThreadId.make("thread:held-row"); + yield* createWatchingThread(parentThreadId, 30); + yield* send(parentThreadId, "parent", "start_immediately"); + const childThreadId = yield* delegate(parentThreadId, "held child"); + const child = yield* orchestrator.getThreadProjection(childThreadId); + const childRun = child.runs[0]!; + const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!; + const now = yield* DateTime.now; + const nativeThreadId = ThreadId.make("thread:held-row-native"); + const nestedThreadId = ThreadId.make("thread:held-row-nested"); + yield* createWatchingThread(nativeThreadId, 31); + yield* createWatchingThread(nestedThreadId, 32); + const nativeProviderThreadId = ProviderThreadId.make("provider-thread:held-row-native"); + const runningRoot = (threadId: ThreadId, id: NodeId) => ({ + ...child.nodes.find((node) => node.id === childRun.rootNodeId)!, + id, + rootNodeId: id, + threadId, + runId: null, + parentNodeId: null, + status: "running" as const, + countsForRun: false, + completedAt: null, + }); + const nativeRoot = runningRoot(nativeThreadId, NodeId.make("node:held-row-native-root")); + const nestedRoot = runningRoot(nestedThreadId, NodeId.make("node:held-row-nested-root")); + for (const root of [nativeRoot, nestedRoot]) { + yield* projections.apply({ + id: EventId.make(`event:held-row:${root.id}`), + type: "node.updated", + threadId: root.threadId, + nodeId: root.id, + occurredAt: now, + payload: root, + }); + } + yield* projections.apply({ + id: EventId.make("event:held-row:native-turn"), + type: "provider-turn.updated", + threadId: nativeThreadId, + nodeId: nativeRoot.id, + occurredAt: now, + payload: { + id: ProviderTurnId.make("turn:held-row-native"), + providerThreadId: nativeProviderThreadId, + nodeId: nativeRoot.id, + runAttemptId: null, + nativeTurnRef: null, + ordinal: 1, + status: "running", + startedAt: now, + completedAt: null, + }, + }); + const native = { + ...task, + id: NodeId.make("node:held-row-native"), + threadId: childThreadId, + runId: childRun.id, + parentNodeId: childRun.rootNodeId!, + origin: "provider_native" as const, + providerThreadId: nativeProviderThreadId, + childThreadId: nativeThreadId, + status: "running" as const, + completionDelivery: undefined, + }; + yield* projections.apply({ + id: EventId.make("event:held-row:native"), + type: "subagent.updated", + threadId: childThreadId, + runId: childRun.id, + occurredAt: now, + payload: native, + }); + yield* projections.apply({ + id: EventId.make("event:held-row:nested"), + type: "subagent.updated", + threadId: nativeThreadId, + occurredAt: now, + payload: { + ...native, + id: NodeId.make("node:held-row-nested"), + threadId: nativeThreadId, + runId: null, + parentNodeId: nativeRoot.id, + childThreadId: nestedThreadId, + }, + }); + yield* projections.apply({ + id: EventId.make("event:held-row:child-completed"), + type: "run.updated", + threadId: childThreadId, + runId: childRun.id, + occurredAt: now, + payload: { ...childRun, status: "completed", startedAt: now, completedAt: now }, + }); + yield* orchestrator.recoverDelegatedTasks; + assert.equal( + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]?.status, + "running", + ); + const statuses = Effect.gen(function* () { + const nativeAfter = yield* orchestrator.getThreadProjection(nativeThreadId); + const nestedAfter = yield* orchestrator.getThreadProjection(nestedThreadId); + return { + row: (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]?.status, + native: (yield* orchestrator.getThreadProjection(childThreadId)).subagents.find( + (subagent) => subagent.id === native.id, + )?.status, + nativeRoot: nativeAfter.nodes.find((node) => node.id === nativeRoot.id)?.status, + nested: nativeAfter.subagents[0]?.status, + nestedRoot: nestedAfter.nodes.find((node) => node.id === nestedRoot.id)?.status, + }; + }); + + // The row's Stop: the parent's task, then the child thread. + yield* orchestrator.dispatch({ + type: "subagent.stop", + commandId: CommandId.make("held-row:stop-task"), + threadId: parentThreadId, + runId: task.runId!, + subagentId: task.id, + }); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("held-row:stop-child"), + threadId: childThreadId, + }); + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + yield* worker.drain(); + assert.deepEqual(yield* statuses, { + row: "completed", + native: "interrupted", + nativeRoot: "interrupted", + nested: "interrupted", + nestedRoot: "interrupted", + }); + }).pipe(Effect.provide(layerTest)), +); + it.effect.each([ { followUp: "started its turn", startedBeforeRelease: true }, { followUp: "was promoted", startedBeforeRelease: false }, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index e081f531770d4..defa30c6dcce9 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -9251,6 +9251,287 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each([ + { ...modelSelection, model: "gpt-5.5", options: [{ id: "reasoningEffort", value: "high" }] }, + { instanceId: alternateInstanceId, model: "gpt-5.5" }, + ])( + "starts a queued scheduled delivery on a selection set while it waited: %j", + (newerSelection) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make( + `runtime-layer-queued-scheduled-selection-${newerSelection.instanceId}-${"options" in newerSelection}`, + ); + const scheduledMessageId = MessageId.make(`${threadId}:scheduled`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Scheduled delivery selection", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "Busy", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + // Bound scheduled tasks send like ScheduledTaskService: no model of their own. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:scheduled`), + threadId, + messageId: scheduledMessageId, + scheduledTaskId: ScheduledTaskId.make(`${threadId}:task`), + text: "Scheduled prompt", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === scheduledMessageId, + )!; + assert.equal(queued.status, "queued"); + assert.deepEqual(queued.modelSelection, modelSelection); + // Stop holds the queue; a thread changes instance only while no run is active. + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make(`${threadId}:stop`), + threadId, + runId: active.id, + holdQueue: true, + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:select-newer`), + threadId, + modelSelection: newerSelection, + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.userMessageId === scheduledMessageId)!; + assert.equal(delivered.status, "starting"); + assert.deepEqual(delivered.modelSelection, newerSelection); + assert.equal( + after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId) + ?.providerInstanceId, + newerSelection.instanceId, + ); + assert.deepEqual(after.thread.modelSelection, newerSelection); + assert.equal(after.thread.providerInstanceId, newerSelection.instanceId); + }), + ); + + it.effect( + "starts a queued scheduled delivery that pinned a model on its pin after the thread moved", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-queued-scheduled-pinned-selection"); + const scheduledMessageId = MessageId.make(`${threadId}:scheduled`); + const pinnedSelection = { instanceId: modelSelection.instanceId, model: "gpt-5.5" }; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Pinned scheduled selection", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "Busy", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + // A task that pins a model names it on the delivery, as a fresh-thread launch seeds it. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:scheduled`), + threadId, + messageId: scheduledMessageId, + scheduledTaskId: ScheduledTaskId.make(`${threadId}:task`), + modelSelection: pinnedSelection, + text: "Pinned scheduled prompt", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === scheduledMessageId, + )!; + assert.equal(queued.status, "queued"); + assert.deepEqual(queued.modelSelection, pinnedSelection); + // Stop holds the queue; a thread changes instance only while no run is active. + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make(`${threadId}:stop`), + threadId, + runId: active.id, + holdQueue: true, + }); + // The user moves the thread off the pinned model while the delivery is held. + const movedSelection = { instanceId: alternateInstanceId, model: "gpt-5.5" }; + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:select-moved`), + threadId, + modelSelection: movedSelection, + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.userMessageId === scheduledMessageId)!; + assert.equal(delivered.status, "starting"); + // The pin wins: the run starts on the selection the delivery named, not the thread's later pick. + assert.deepEqual(delivered.modelSelection, pinnedSelection); + assert.equal( + after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId) + ?.providerInstanceId, + pinnedSelection.instanceId, + ); + // Pinned tasks keep today's behaviour: the thread follows the run's selection back. + assert.deepEqual(after.thread.modelSelection, pinnedSelection); + }), + ); + + it.effect( + "starts a fresh scheduled delivery on a new provider thread after a provider switch", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-fresh-scheduled-provider-thread"); + const switchedSelection = { instanceId: alternateInstanceId, model: "gpt-5.5" }; + const scheduledMessageId = MessageId.make(`${threadId}:scheduled`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Fresh scheduled provider thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "Busy", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:scheduled`), + threadId, + messageId: scheduledMessageId, + scheduledTaskId: ScheduledTaskId.make(`${threadId}:task`), + text: "Scheduled prompt", + attachments: [], + freshContext: true, + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queuedProjection = yield* orchestrator.getThreadProjection(threadId); + const queued = queuedProjection.runs.find( + (run) => run.userMessageId === scheduledMessageId, + )!; + // The queue reserved an unused provider thread on the original instance. + const reserved = queuedProjection.providerThreads.find( + (providerThread) => providerThread.id === queued.providerThreadId, + )!; + assert.equal(reserved.providerInstanceId, modelSelection.instanceId); + assert.isNull(reserved.firstRunOrdinal); + assert.isNull(reserved.nativeThreadRef); + // Stop holds the queue; a thread changes instance only while no run is active. + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make(`${threadId}:stop`), + threadId, + runId: active.id, + holdQueue: true, + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:select-switched`), + threadId, + modelSelection: switchedSelection, + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`${threadId}:resume`), + threadId, + }); + yield* orchestrator.resumeQueuedRuns; + + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.userMessageId === scheduledMessageId)!; + assert.equal(delivered.status, "starting"); + assert.isTrue(delivered.freshContext === true); + assert.notEqual(delivered.providerThreadId, reserved.id); + assert.equal( + after.providerThreads.find( + (providerThread) => providerThread.id === delivered.providerThreadId, + )?.providerInstanceId, + switchedSelection.instanceId, + ); + assert.equal( + after.providerThreads.find((providerThread) => providerThread.id === reserved.id) + ?.providerInstanceId, + modelSelection.instanceId, + ); + }), + ); + it.effect("keeps the queue after a user interrupts the active run", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -10134,8 +10415,8 @@ it.layer(layerSharedApplicationDataPlaneTest)("pending provider interruption", ( }); it.layer(layerTest)("snooze queued runs", (it) => { - it.effect.each(["notification", "delegated-completion", "user"] as const)( - "only user messages block snooze with a held %s run", + it.effect.each(["notification", "delegated-completion", "user", "limited-user"] as const)( + "only user messages block snooze with a queued %s run, unless a usage limit holds them", (kind) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -10204,8 +10485,8 @@ it.layer(layerTest)("snooze queued runs", (it) => { attachments: [], modelSelection, dispatchMode: { type: "queue_after_active" }, - createdBy: kind === "user" ? "user" : "agent", - creationSource: kind === "user" ? "web" : "server", + createdBy: kind === "user" || kind === "limited-user" ? "user" : "agent", + creationSource: kind === "user" || kind === "limited-user" ? "web" : "server", ...(kind === "notification" ? { notification: { @@ -10224,6 +10505,43 @@ it.layer(layerTest)("snooze queued runs", (it) => { } : {}), }); + if (kind === "limited-user") { + yield* eventSink.write({ + events: [ + { + id: EventId.make(`limited:${threadId}`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`limited:${threadId}`), + type: "error", + threadId, + runId: activeRun.id, + nodeId: activeRun.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Usage limit reached", + startedAt: now, + completedAt: now, + updatedAt: now, + // A proxied provider can report no reset time. + failure: { + class: "usage_limit", + message: "Claude API rate limit reached. Try again later.", + code: "api_error_429", + retryable: true, + resetAt: null, + }, + }, + }, + ], + }); + } const beforeRecovery = yield* orchestrator.getThreadProjection(threadId); yield* eventSink.commitCommand({ commandId: CommandId.make(`recovery:${threadId}`), @@ -10238,13 +10556,24 @@ it.layer(layerTest)("snooze queued runs", (it) => { occurredAt: now, payload: run.status === "queued" - ? { ...run, queueHeld: true } - : { ...run, status: "cancelled" as const, completedAt: now }, + ? // A usage limit stops the queue from starting without marking it held. + kind === "limited-user" + ? run + : { ...run, queueHeld: true } + : { + ...run, + status: kind === "limited-user" ? ("failed" as const) : ("cancelled" as const), + completedAt: now, + }, })), effects: [], }); const beforeSnooze = yield* orchestrator.getThreadProjection(threadId); - assert.isTrue(beforeSnooze.runs.some((run) => run.status === "queued" && run.queueHeld)); + assert.isTrue( + beforeSnooze.runs.some( + (run) => run.status === "queued" && (kind === "limited-user" || run.queueHeld), + ), + ); const snooze = orchestrator.dispatch({ type: "thread.snooze", commandId: CommandId.make(`snooze:${threadId}`), @@ -10760,6 +11089,19 @@ it.layer(layerSharedApplicationDataPlaneTest)("visited projection", (it) => { assert.isNotNull(visited.thread.lastVisitedAt); assert.equal(DateTime.formatIso(visited.thread.lastVisitedAt!), visitedAt); assert.deepEqual(visited.thread.updatedAt, createdUpdatedAt); + const sql = yield* SqlClient.SqlClient; + const visitPayloadKeys = (commandId: string) => + sql<{ readonly payload_json: string }>` + SELECT payload_json FROM orchestration_events WHERE command_id = ${commandId} + `.pipe( + Effect.map((rows) => + rows.map((row) => Object.keys(JSON.parse(row.payload_json)).toSorted()), + ), + ); + // A visit stores read state, not a copy of the thread. + for (const keys of yield* visitPayloadKeys("runtime-layer-visited-thread-visit")) { + assert.includeMembers(["lastVisitedAt", "opens", "threadId"], keys); + } yield* orchestrator.dispatch({ type: "thread.visit", @@ -10769,6 +11111,8 @@ it.layer(layerSharedApplicationDataPlaneTest)("visited projection", (it) => { }); const afterStaleVisit = yield* orchestrator.getThreadProjection(threadId); assert.equal(DateTime.formatIso(afterStaleVisit.thread.lastVisitedAt!), visitedAt); + // A stale visit with no open changes nothing, so it stores nothing. + assert.deepEqual(yield* visitPayloadKeys("runtime-layer-visited-thread-visit-stale"), []); const shell = yield* orchestrator.getShellSnapshot(); const thread = shell.threads.find((candidate) => candidate.id === threadId); @@ -10785,7 +11129,6 @@ it.layer(layerSharedApplicationDataPlaneTest)("visited projection", (it) => { .pipe(Effect.flip); assert.instanceOf(markUnread, Orchestrator.OrchestratorDispatchError); - const sql = yield* SqlClient.SqlClient; yield* sql`INSERT INTO orchestration_v2_projection_turn_items ( turn_item_id, thread_id, ordinal, type, status, updated_at, payload_json ) VALUES ( diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index 0cfa599ed5486..6866633397168 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -47,6 +47,7 @@ import * as ProviderRuntimeRecoveryService from "./ProviderRuntimeRecoveryServic import * as ProviderSwitchService from "./ProviderSwitchService.ts"; import * as ProviderTurnControlService from "./ProviderTurnControlService.ts"; import * as ProviderTurnStartService from "./ProviderTurnStartService.ts"; +import { layerThreadWorktreeRestore } from "../workspace/restoreMissingWorktree.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as RunFinalizationService from "./RunFinalizationService.ts"; import * as ResourceCleanupService from "./ResourceCleanupService.ts"; @@ -267,6 +268,7 @@ const layerThreadManagementProvided = ThreadManagementService.layerWithLegacyImp layerLegacyV1ThreadImporterProvided, layerCommandReceiptStoreProvided, layerProviderSessionManagerProvided, + layerThreadWorktreeRestore, ), ), ); @@ -281,14 +283,13 @@ const layerManagedProjectFoldersProvided = ManagedProjectFolders.layer.pipe( const layerThreadLaunchProvided = ThreadLaunchService.layer.pipe( Layer.provide( Layer.mergeAll( - layerProjectService, layerProjectSetupScriptRunner, layerManagedProjectFoldersProvided, layerThreadManagementProvided, layerCommandReceiptStoreProvided, layerEventSink, IdAllocator.layer, - ), + ).pipe(Layer.provideMerge(layerProjectService)), ), ); const layerSecretRequestsProvided = SecretRequests.layer.pipe( @@ -307,11 +308,10 @@ const layerScheduledTaskProvided = ScheduledTaskService.layer.pipe( const layerScratchThreadPromotionProvided = ScratchThreadPromotion.layer.pipe( Layer.provide( Layer.mergeAll( - layerProjectService, layerManagedProjectFoldersProvided, layerThreadManagementProvided, layerScheduledTaskProvided, - ), + ).pipe(Layer.provideMerge(layerProjectService)), ), ); const layerProviderContinuationWorkerProvided = ProviderContinuationService.layer.pipe( @@ -389,8 +389,7 @@ export const layerProduction = Layer.mergeAll( WorktreeBranchSync.layer.pipe( Layer.provide(Layer.merge(layerThreadManagementProvided, ProjectionStore.layer)), ), - layer.pipe(Layer.provide(layerProjectService)), - layerProjectService, + layer, layerManagedProjectFoldersProvided, layerThreadLaunchProvided, layerScheduledTaskProvided, @@ -414,6 +413,7 @@ export const layerProduction = Layer.mergeAll( EffectOutbox.layerPruneWorker.pipe(Layer.provide(EffectOutbox.layer)), ).pipe( Layer.provide(ResourceCleanupService.layer.pipe(Layer.provide(layerScheduledTaskProvided))), + Layer.provideMerge(layerProjectService), Layer.provide(Scheduler.layer), Layer.provideMerge(layerEventInfrastructure), ); diff --git a/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts index 8886daad3e017..1085fa04f7565 100644 --- a/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts @@ -95,6 +95,19 @@ describe("Claude Agent SDK replay fixtures", () => { userFacingDispatchErrorMessage(refused), "This subagent is run by its provider and cannot take messages. Message the parent thread instead.", ); + const refusedContinuation = yield* orchestrator + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("command:subagent:continue-native-child"), + threadId: child.thread.id, + title: "Renamed", + continuation: { + messageId: MessageId.make("message:subagent:continue-native-child"), + text: "Also check the tests.", + }, + }) + .pipe(Effect.flip); + assert.equal(refusedContinuation._tag, "OrchestratorSubagentThreadReadOnlyError"); assert.equal(yield* orchestrator.getThreadEventSequence(child.thread.id), before); const after = yield* orchestrator.getThreadProjection(child.thread.id); assert.lengthOf(after.runs, 0); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts index e4371b54ee4b5..965e5bd44f2dc 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts @@ -2004,8 +2004,9 @@ describe("orchestration v2 provider switching", () => { yield* Deferred.await(started); yield* Fiber.join(toolCallRunning); - const runFailed = yield* awaitEvent( - (event) => event.type === "run.updated" && event.payload.status === "failed", + // The handoff itself is not a failure: the run completes once the session closes. + const runSettled = yield* awaitEvent( + (event) => event.type === "run.updated" && event.payload.status === "waiting", ); yield* orchestrator.dispatch({ type: "thread.metadata.update", @@ -2016,9 +2017,11 @@ describe("orchestration v2 provider switching", () => { expectedWorktreePath: null, }); yield* worker.drain(); - yield* Fiber.join(runFailed); + yield* Fiber.join(runSettled); + yield* worker.drain(); const projection = yield* orchestrator.getThreadProjection(scenarioThreadId); + assert.equal(projection.runs.at(-1)?.status, "completed"); const toolCall = projection.turnItems.find((item) => item.id === toolCallId); assert.equal(toolCall?.status, "interrupted"); assert.isNotNull(toolCall?.completedAt); diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 6d09b6b1b3a68..af569e902c027 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -25,6 +25,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -644,6 +645,8 @@ const makeLaptop = ( >, /** The laptop's links from before a restart, which keep their sessions there. */ kept?: Context.Context>>, + /** Runs as each follow attempt here starts, on its follower's fiber. */ + beforeFollow: Effect.Effect = Effect.void, ) => Effect.gen(function* () { const linking = kept ?? (yield* layerLinkingEnvironment(laptop).pipe(Layer.build)); @@ -672,6 +675,19 @@ const makeLaptop = ( Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), Layer.provideMerge( RemoteDelegation.layer.pipe( + Layer.provide( + Layer.effect( + ThreadManagement.ThreadManagementService, + Effect.gen(function* () { + const threads = yield* ThreadManagement.ThreadManagementService; + return { + ...threads, + getThreadEventSequence: (threadId: ThreadId) => + beforeFollow.pipe(Effect.andThen(threads.getThreadEventSequence(threadId))), + }; + }), + ), + ), Layer.provideMerge(PeerForwarding.layer), Layer.provide( Layer.mock(ProjectService.ProjectService)({ @@ -1784,6 +1800,108 @@ const steppedRetries = Effect.gen(function* () { return { failed, retry, schedule }; }); +it.effect("a follower that keeps hitting defects fails the task and wakes the parent", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const retries = yield* steppedRetries; + const attempts = yield* Ref.make(0); + // The defect carries internal detail that the task's result must not. + const beforeFollow = Ref.update(attempts, (count) => count + 1).pipe( + Effect.andThen(Effect.die(new Error("A follow attempt hit a bug: defect-detail-4f1c9e"))), + ); + const a = yield* makeLaptop(database, offers, undefined, beforeFollow).pipe( + Effect.provideService(RemoteDelegation.FollowRetrySchedule, retries.schedule), + ); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + yield* Queue.take(retries.failed).pipe( + Effect.andThen(Queue.offer(retries.retry, undefined)), + Effect.forever, + Effect.forkScoped, + ); + + const delegated = yield* delegateToBox(a); + const task = yield* taskResult(a, delegated.taskId); + expect(yield* Ref.get(attempts)).toBe(3); + expect(task?.status).toBe("failed"); + expect(task?.result).toContain(delegated.remoteChild.threadId); + expect(task?.result).not.toContain("defect-detail-4f1c9e"); + const offered = yield* SubscriptionRef.changes(offers).pipe( + Stream.filter((seen) => seen.some((offer) => offer.threadId === parentThreadId)), + Stream.runHead, + ); + expect(Option.isSome(offered)).toBe(true); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect.each(["a still-running wait", "a failed attempt"] as const)( + "defects separated by %s do not add up to giving up", + (between) => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const retries = yield* steppedRetries; + const attempts = yield* Ref.make(0); + const defect = Effect.die(new Error("A follow attempt hit a bug.")); + const script = [ + defect, + between === "a still-running wait" + ? Effect.void + : Effect.fail( + new Orchestrator.OrchestratorProjectionError({ threadId: parentThreadId }), + ), + defect, + between === "a still-running wait" + ? Effect.void + : Effect.fail( + new Orchestrator.OrchestratorProjectionError({ threadId: parentThreadId }), + ), + defect, + ]; + // Past the script, the run there has ended, so the next attempt completes the task. + const beforeFollow = Ref.getAndUpdate(attempts, (count) => count + 1).pipe( + Effect.flatMap( + (count) => + script[count] ?? + Ref.set(thread.reply, "All green.").pipe( + Effect.andThen(Ref.set(thread.status, "completed")), + ), + ), + ); + // Each wait there answers at once that its run is still running. + yield* Deferred.succeed(thread.finished, undefined); + const a = yield* makeLaptop(database, offers, undefined, beforeFollow).pipe( + Effect.provideService(RemoteDelegation.FollowRetrySchedule, retries.schedule), + ); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + yield* Queue.take(retries.failed).pipe( + Effect.andThen(Queue.offer(retries.retry, undefined)), + Effect.forever, + Effect.forkScoped, + ); + + const delegated = yield* delegateToBox(a); + expect(yield* taskResult(a, delegated.taskId)).toMatchObject({ + status: "completed", + result: "All green.", + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + /** Waits until the task here records that the `stopCount`th Stop after its result reached there. */ const stoppedThere = ( laptopEnv: Effect.Success>, @@ -1813,6 +1931,87 @@ const stoppedThere = ( ), ); +it.effect("a follower that keeps hitting defects leaves a stop it owes owed", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const retries = yield* steppedRetries; + // Follow attempts hit a defect only once the task has its result. + const broken = yield* Ref.make(false); + const follower = yield* Deferred.make>(); + const beforeFollow = Ref.get(broken).pipe( + Effect.flatMap((isBroken) => + isBroken + ? Effect.withFiber((fiber) => Deferred.succeed(follower, fiber)).pipe( + Effect.andThen(Effect.die(new Error("A follow attempt hit a bug."))), + ) + : Effect.void, + ), + ); + const a = yield* makeLaptop(database, offers, undefined, beforeFollow).pipe( + Effect.provideService(RemoteDelegation.FollowRetrySchedule, retries.schedule), + ); + yield* a.remote.start(); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "All green."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + yield* taskResult(a, delegated.taskId); + yield* Ref.set(broken, true); + yield* Queue.take(retries.failed).pipe( + Effect.andThen(Queue.offer(retries.retry, undefined)), + Effect.forever, + Effect.forkScoped, + ); + + // The Stop owes one stop there, which every attempt to send fails on. + yield* a.threads.stopDelegatedTasks({ + threadId: parentThreadId, + commandId: CommandId.make("command:stop:laptop-parent-defective-follower"), + }); + const owedAgain = a.orchestrator + .streamStoredEventsFrom({ + threadId: parentThreadId, + afterSequence: 0, + eventType: "subagent.updated", + }) + .pipe( + Stream.filter( + (stored) => + stored.event.type === "subagent.updated" && + stored.event.payload.id === delegated.taskId && + (stored.event.payload.remoteChild?.stopCount ?? 0) > 1, + ), + Stream.runHead, + Effect.flatMap((owed) => + Option.isSome(owed) ? Effect.succeed("owed another stop" as const) : Effect.never, + ), + ); + const ended = yield* Deferred.await(follower).pipe( + Effect.flatMap(Fiber.await), + Effect.as("follower ended" as const), + Effect.raceFirst(owedAgain), + ); + expect(ended).toBe("follower ended"); + const { subagents } = yield* a.threads.getThreadRecords(parentThreadId, ["subagents"], { + subagentIds: [delegated.taskId], + }); + expect(subagents[0]).toMatchObject({ + status: "completed", + result: "All green.", + remoteChild: { stoppedThere: false, stopCount: 1 }, + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + it.effect("stopping the parent stops follow-up work on a task there that has its result", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 3b01c48b01db0..c9e38b4bc73d4 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -19,6 +19,7 @@ import { type RunId, type ThreadId, } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; @@ -53,6 +54,8 @@ import * as PeerLinks from "./PeerLinks.ts"; const FOLLOW_WAIT_MS = 10 * 60 * 1_000; /** A linked environment that stops answering is retried, backing off to this. */ const FOLLOW_MAX_BACKOFF = Duration.minutes(5); +/** A follower that hits this many defects in a row fails its task instead of retrying. */ +const FOLLOW_MAX_DEFECTS = 3; /** How a follower retries; tests step it by hand. */ export const FollowRetrySchedule = Context.Reference>( "t3/peer/RemoteDelegation/FollowRetrySchedule", @@ -673,26 +676,54 @@ const make = Effect.gen(function* () { /** * Waits for the task's run there to end, completes the task here, and stops it there if it * ended here first. A revoked, expired or forgotten link, or a thread or run gone there, - * fails the task with nothing left to stop; anything else (the other machine asleep, a - * dropped route) is retried with back-off, and so is completing. + * fails the task with nothing left to stop; repeated defects here fail it too. Anything else + * (the other machine asleep, a dropped route) is retried with back-off, and so is completing. */ const follow = (parentThreadId: ThreadId, taskId: NodeId): Effect.Effect => - followOnce(parentThreadId, taskId).pipe( - // `false` means it is still running there: follow again straight away. - Effect.repeat({ while: (done) => !done }), - Effect.catchTags({ - OrchestratorMcpFailure: Effect.fn("RemoteDelegation.followFailed")(function* (error) { - const reason = yield* finalReason(parentThreadId, taskId, error); - if (reason === undefined) return yield* error; - // Gone there, or no link to reach it by: nothing left to stop there. - const { task } = yield* readTask(parentThreadId, taskId); - const stopCount = task?.remoteChild?.stopCount; - yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount); + Effect.suspend(() => { + let defects = 0; + const noDefect = Effect.sync(() => { + defects = 0; + }); + return followOnce(parentThreadId, taskId).pipe( + Effect.tap(noDefect), + // `false` means it is still running there: follow again straight away. + Effect.repeat({ while: (done) => !done }), + Effect.catchTags({ + OrchestratorMcpFailure: Effect.fn("RemoteDelegation.followFailed")(function* (error) { + const reason = yield* finalReason(parentThreadId, taskId, error); + if (reason === undefined) return yield* error; + // Gone there, or no link to reach it by: nothing left to stop there. + const { task } = yield* readTask(parentThreadId, taskId); + const stopCount = task?.remoteChild?.stopCount; + yield* complete(parentThreadId, taskId, "failed", reason, "stopped", stopCount); + }), }), - }), - Effect.retry(followRetry), - Effect.ignoreCause({ log: true }), - ); + Effect.tapError(() => noDefect), + Effect.tapDefect(() => + Effect.sync(() => { + defects += 1; + }), + ), + failOnDefect, + Effect.retry({ schedule: followRetry, while: () => defects < FOLLOW_MAX_DEFECTS }), + Effect.catch( + Effect.fn("RemoteDelegation.followGaveUp")( + function* () { + const { task } = yield* readTask(parentThreadId, taskId); + const remote = task?.remoteChild; + // A task with its result keeps it; completing it again would owe another stop there. + if (remote === undefined || task?.result !== null) return; + const result = `Following the thread ${remote.threadId} in ${remote.label} failed repeatedly, so it may still run there (task_cancel stops it).`; + yield* complete(parentThreadId, taskId, "failed", result, undefined); + }, + failOnDefect, + Effect.retry(followRetry), + ), + ), + Effect.ignoreCause({ log: true }), + ); + }); /** * One wait on the task's thread there; true once the task here is done. @@ -976,6 +1007,14 @@ const make = Effect.gen(function* () { return RemoteDelegation.of({ delegate, followUp, cancel, start }); }); +/** A defect, logged, as a failure, so a retry covers it. */ +const failOnDefect = (effect: Effect.Effect) => + Effect.catchDefect(effect, (defect) => + Effect.logWarning("A remote task's follower hit a defect", Cause.die(defect)).pipe( + Effect.andThen(Effect.fail(new Cause.UnknownError(defect, "A follower hit a defect."))), + ), + ); + const isTerminal = (status: string) => status === "completed" || status === "failed" || diff --git a/apps/server/src/preview/Manager.test.ts b/apps/server/src/preview/Manager.test.ts index 1c16992123206..28598cfbdfe15 100644 --- a/apps/server/src/preview/Manager.test.ts +++ b/apps/server/src/preview/Manager.test.ts @@ -79,6 +79,18 @@ it.layer(layer)("PreviewManager", (it) => { }), ); + it.effect("opens a server tab with the requested zoom and appearance", () => + Effect.gen(function* () { + const threadId = freshThreadId(); + const manager = yield* PreviewManager.PreviewManager; + const rendering = { zoomFactor: 0.8, colorScheme: "dark" } as const; + + const opened = yield* manager.open({ threadId, runtime: "server", ...rendering }); + + expect(opened).toMatchObject(rendering); + }), + ); + it.effect("reissues presentation requests without replaying them on navigation", () => Effect.gen(function* () { const threadId = freshThreadId(); diff --git a/apps/server/src/preview/Manager.ts b/apps/server/src/preview/Manager.ts index ff8442306f2ff..0899866f80b64 100644 --- a/apps/server/src/preview/Manager.ts +++ b/apps/server/src/preview/Manager.ts @@ -193,6 +193,8 @@ export const make = Effect.gen(function* PreviewManagerMake() { viewport: input.viewport ?? FILL_PREVIEW_VIEWPORT, ...(input.profileId === undefined ? {} : { profileId: input.profileId }), ...(runtime === undefined ? {} : { runtime }), + ...(input.colorScheme === undefined ? {} : { colorScheme: input.colorScheme }), + ...(input.zoomFactor === undefined ? {} : { zoomFactor: input.zoomFactor }), ...(runtime === "server" && input.automationOwner !== undefined ? { automationOwner: input.automationOwner } : {}), diff --git a/apps/server/src/preview/PreviewBrowser.ts b/apps/server/src/preview/PreviewBrowser.ts index 50ba7b91c56fa..203ec112cccb7 100644 --- a/apps/server/src/preview/PreviewBrowser.ts +++ b/apps/server/src/preview/PreviewBrowser.ts @@ -25,31 +25,31 @@ import { openZipArchive } from "../zipArchive.ts"; // https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json // Never pin below 156.0.8078.70: the shell has no CRLSet and older SPKI blocklists trust // compromised eMudhra intermediates (crrev.com/c/8627687). -const VERSION = "157.0.8103.38"; +const VERSION = "157.0.8103.78"; const ARCHIVES = { linux64: { - bytes: 128_168_542, - sha256: "deafffa74660b34853a4119c361fd427ac8c9fcb62db51ddb8a797cd83a4ba2d", + bytes: 127_965_683, + sha256: "f90329720fb61e5a76da9b6b509b6ad12a484c9c5df0359403e935177c6d153a", }, "linux-arm64": { - bytes: 128_171_139, - sha256: "b9b910a57b2a15eb3e55000a2339f93a973934a413ebfc6e585a50ec6c42fd6c", + bytes: 128_047_138, + sha256: "912fbf877e53de34d7b3cca5104f3b95607d41bd35412ccc6cd2a599ff0c0dbf", }, "mac-arm64": { - bytes: 104_773_711, - sha256: "e6a6b13551aa12f951d0891d79282606b13742837c8fa0505e1272bae116ce82", + bytes: 104_822_985, + sha256: "17bf66d53c1b1104dcb641c5b331cd4ac5d200c778f5feed0934a0b92deaf8d6", }, "mac-x64": { - bytes: 110_442_262, - sha256: "79821745d0a72d2ba752d981284ed0a9e6fa320dad133596941a17dba6186de3", + bytes: 110_132_547, + sha256: "f1a6a9561eaf1f409849538de663695d36d72fbf1ebca4d42e47c7b5f2a157f3", }, win32: { - bytes: 120_390_416, - sha256: "35e0d45c0136448f7b587f6fb7195a0686127a4dfdc23ef3b0e04b5e9ffe16cd", + bytes: 120_403_126, + sha256: "d9829c59dcc79d9e6e920f8ab841f2a9a055dcf54229d756ac0b42dfec303910", }, win64: { - bytes: 126_513_060, - sha256: "1ff4540855478ba0848e03f1ef8d455f77d058b38285df91bc34273788a73446", + bytes: 126_047_001, + sha256: "2138c1583d25d6f3abec5269943b2f430207d87a539895aa9e90cc4697ec0e1f", }, } as const; diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index d2897987dc1f6..e76b313f131dd 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -213,11 +213,11 @@ function makeContext(onClose?: (context: BrowserContext) => void, initialUrl = " viewport = size; }), goto: vi.fn(async (next: string, _options?: { timeout?: number; waitUntil?: string }) => { - url = next; - events.emit("load"); const pending = initialNavigation; initialNavigation = null; await pending?.(); + url = next; + events.emit("load"); }), goBack: vi.fn(async () => {}), goForward: vi.fn(async () => {}), @@ -360,12 +360,10 @@ function makeEncoderPage() { document: { createElement: (tag: string) => (tag === "video" ? video : canvas) }, Path2D: function Path2D() {}, MediaRecorder: FakeMediaRecorder, - createImageBitmap: async (blob: Blob) => ({ - width: 1280, - height: 800, - pixels: await blob.text(), - close() {}, - }), + createImageBitmap: async (blob: Blob) => { + await decodeGate?.promise; + return { width: 1280, height: 800, pixels: await blob.text(), close() {} }; + }, atob, btoa, Blob, @@ -386,6 +384,7 @@ function makeEncoderPage() { const contexts: ReturnType[] = []; let encoderPageOverride: Page | undefined; const encoderStreams: Array<{ frameRate: number | undefined; bitsPerSecond: number }> = []; +let decodeGate: PromiseWithResolvers | null = null; const contextRequests: Array<{ profileId: string; isolated: boolean }> = []; let contextGate: PromiseWithResolvers | null = null; let heldStill: (() => Promise) | null = null; @@ -571,6 +570,7 @@ beforeEach(() => { contexts.length = 0; encoderPageOverride = undefined; encoderStreams.length = 0; + decodeGate = null; contextRequests.length = 0; contextGate = null; heldStill = null; @@ -998,15 +998,117 @@ it.effect("a desktop page that loaded before the server attached reports its loa ).pipe(Effect.provide(layer)), ); +it.effect.each(["none", "during", "after-fragment", "same-url"])( + "Stop settles an initial navigation with its request event $0", + (requestTiming) => + Effect.scoped( + Effect.gen(function* () { + const { browser, broker } = yield* ready; + const manager = yield* Manager.PreviewManager; + const events = yield* manager.subscribeEvents; + const started = Promise.withResolvers(); + const committed = Promise.withResolvers(); + initialNavigation = () => { + started.resolve(); + return committed.promise; + }; + yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve())); + const { tabId } = yield* manager.open({ + threadId: scope.thread.threadId, + runtime: "server", + url: + requestTiming === "after-fragment" + ? "https://example.com/pending#section" + : "https://example.com/pending", + }); + const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); + yield* Effect.promise(() => started.promise); + const page = contexts.at(-1)!.page; + const request = { + url: () => "https://example.com/pending", + method: () => "GET", + isNavigationRequest: () => true, + frame: () => page, + failure: () => ({ errorText: "net::ERR_ABORTED" }), + }; + const cdp = contexts.at(-1)!.sessions.at(-1)!; + const send = cdp.send.getMockImplementation()!; + cdp.send.mockImplementation(async (operation, input) => { + if (operation === "Page.stopLoading") { + committed.reject(new Error("net::ERR_ABORTED")); + if (requestTiming === "during") page.emit("request", request); + } + return send(operation, input); + }); + yield* viewer.input({ type: "stopLoading" }); + const stopped = yield* broker.invoke({ + scope, + tabId, + operation: "status", + input: {}, + }); + expect(stopped.loading).toBe(false); + let settled = yield* PubSub.take(events); + while ( + settled.type !== "navigated" || + settled.tabId !== tabId || + settled.snapshot.navStatus._tag !== "Idle" + ) { + settled = yield* PubSub.take(events); + } + const corrected = requestTiming === "same-url"; + using timeout = vi.spyOn(globalThis, "setTimeout"); + if (corrected) { + page.goto.mockImplementationOnce(async () => { + page.emit("request", request); + }); + yield* viewer.input({ type: "navigate", url: request.url() }); + } else if (requestTiming !== "none") { + if (requestTiming === "after-fragment") page.emit("request", request); + page.emit("requestfailed", request); + } + const status = yield* broker.invoke({ + scope, + tabId, + operation: "status", + input: {}, + }); + expect(status.loading).toBe(corrected); + expect(timeout).not.toHaveBeenCalledWith(expect.any(Function), 5_000); + if (!corrected) { + const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); + expect(sessions.find((session) => session.tabId === tabId)?.navStatus).toEqual({ + _tag: "Idle", + }); + } + }), + ).pipe(Effect.provide(layer)), +); + it.effect.each([ - { method: "goto" as const, message: { type: "navigate", url: "http://10.255.255.1/" } }, - { method: "goBack" as const, message: { type: "history", delta: -1 } }, - { method: "goForward" as const, message: { type: "history", delta: 1 } }, - { method: "reload" as const, message: { type: "reload" } }, -])("a pending viewer $method allows a corrected URL and text input", ({ method, message }) => + { + method: "goto" as const, + message: { type: "navigate", url: "http://10.255.255.1/" }, + abortEvent: "before", + }, + { method: "goBack" as const, message: { type: "history", delta: -1 }, abortEvent: "before" }, + { method: "goForward" as const, message: { type: "history", delta: 1 }, abortEvent: "before" }, + { method: "reload" as const, message: { type: "reload" }, abortEvent: "after" }, + { method: "reload" as const, message: { type: "reload" }, abortEvent: "none" }, + ...["before", "after", "none"].map((abortEvent) => ({ + method: "goto" as const, + message: { type: "navigate", url: "http://10.255.255.1/" }, + abortEvent, + blank: true, + })), +])("viewer $method Stop settles ($abortEvent, blank=$blank)", (testCase) => Effect.scoped( Effect.gen(function* () { - const { browser, tabId } = yield* ready; + const { method, message, abortEvent } = testCase; + const blank = "blank" in testCase; + const { browser, broker, tabId } = yield* ready; + const manager = yield* Manager.PreviewManager; + const events = yield* manager.subscribeEvents; const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); yield* viewer.input({ type: "takeControl" }); const started = Promise.withResolvers(); @@ -1020,26 +1122,77 @@ it.effect.each([ yield* Effect.promise(() => started.promise); const cdp = contexts[0]!.sessions.at(-1)!; const send = cdp.send.getMockImplementation()!; + const request = { + url: () => "https://example.com/pending", + method: () => "GET", + isNavigationRequest: () => true, + frame: () => page, + failure: () => ({ errorText: "net::ERR_ABORTED" }), + }; const typed = Promise.withResolvers(); + let cancelled = false; cdp.send.mockImplementation(async (operation, input) => { if (operation === "Input.insertText") typed.resolve(); + if (operation === "Page.stopLoading") { + cancelled = true; + committed.reject(new Error("net::ERR_ABORTED")); + if (abortEvent === "before") page.emit("requestfailed", request); + } return send(operation, input); }); const correction = yield* Effect.gen(function* () { - yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" }); + if (!blank) yield* viewer.input({ type: "navigate", url: "http://localhost:5173/fixed" }); yield* viewer.input({ type: "text", text: "hello" }); }).pipe(Effect.forkScoped); yield* Effect.addFinalizer(() => Effect.sync(() => committed.resolve())); // The text reaches the page while the first navigation is still uncommitted. yield* Effect.promise(() => typed.promise); expect(page.goto).toHaveBeenLastCalledWith( - "http://localhost:5173/fixed", + blank ? "http://10.255.255.1/" : "http://localhost:5173/fixed", expect.objectContaining({ waitUntil: "commit" }), ); expect(contexts[0]!.sessions.at(-1)!.send).toHaveBeenCalledWith("Input.insertText", { text: "hello", }); - committed.resolve(); + page.emit("request", request); + let loadingEvent = yield* PubSub.take(events); + while ( + loadingEvent.type !== "navigated" || + loadingEvent.snapshot.navStatus._tag !== "Loading" + ) { + loadingEvent = yield* PubSub.take(events); + } + const reader = yield* browser.attachViewer(viewerInput(tabId, false)); + yield* reader.input({ type: "stopLoading" }); + expect(cancelled).toBe(false); + if (abortEvent === "none" && !blank) committed.resolve(); + yield* viewer.input({ type: "stopLoading" }); + expect(cancelled).toBe(true); + using timeout = vi.spyOn(globalThis, "setTimeout"); + if (abortEvent === "after") page.emit("requestfailed", request); + expect(timeout).not.toHaveBeenCalledWith(expect.any(Function), 5_000); + const status = yield* broker.invoke({ + scope, + tabId, + operation: "status", + input: {}, + }); + expect(status.loading).toBe(false); + const expectedStatus = blank ? "Idle" : "Success"; + let settled = yield* PubSub.take(events); + while (settled.type !== "navigated" || settled.snapshot.navStatus._tag !== expectedStatus) { + settled = yield* PubSub.take(events); + } + if (blank) { + const { sessions } = yield* manager.list({ threadId: scope.thread.threadId }); + expect(sessions.find((session) => session.tabId === tabId)?.navStatus).toEqual({ + _tag: "Idle", + }); + } + if (settled.snapshot.navStatus._tag === "Success") + expect(settled.snapshot.navStatus.url).toBe("http://localhost:5173/fixed"); + expect(page[method]).toHaveBeenCalledTimes(method === "goto" && !blank ? 2 : 1); + yield* viewer.input({ type: "releaseControl" }); yield* Fiber.join(navigation); yield* Fiber.join(correction); }), @@ -1077,6 +1230,32 @@ it.effect.each([ ).pipe(Effect.provide(layer)), ); +// Chrome stops sending screencast frames while too many are unacked. +it.effect("recordings ack screencast frames without waiting for the encoder to decode them", () => + Effect.scoped( + Effect.gen(function* () { + const { broker, tabId } = yield* ready; + yield* broker.invoke({ scope, tabId, operation: "recordingStart", input: {} }); + const session = contexts[0]!.sessions.find((candidate) => + candidate.send.mock.calls.some(([method]) => method === "Page.startScreencast"), + )!; + const gate = Promise.withResolvers(); + decodeGate = gate; + yield* Effect.addFinalizer(() => Effect.sync(() => gate.resolve())); + for (const sessionId of [1, 2, 3]) { + session.emit("Page.screencastFrame", { + data: Buffer.from(`frame ${sessionId}`).toString("base64"), + sessionId, + metadata: { deviceWidth: 1280 }, + }); + } + expect( + session.send.mock.calls.filter(([method]) => method === "Page.screencastFrameAck"), + ).toHaveLength(3); + }), + ).pipe(Effect.provide(layer)), +); + it.effect.each([{ truncated: false }, { truncated: true }])( "saves a large recording as a binary download and removes its staged file (truncated: $truncated)", ({ truncated }) => @@ -1627,6 +1806,34 @@ it.effect("closing a tab with an unsaved-changes guard still closes it", () => ).pipe(Effect.provide(layer)), ); +it.effect("a tab whose renderer crashes stays open instead of vanishing", () => + Effect.scoped( + Effect.gen(function* () { + const { browser, broker, tabId } = yield* ready; + const url = `https://example.com/app?${"a".repeat(3000)}`; + contexts[0]!.page.commit(url); + yield* Effect.promise(() => contexts[0]!.page.emitAsync("crash")); + const status = yield* broker.invoke({ + scope, + tabId, + operation: "status", + input: {}, + }); + expect(status.tabId).toBe(tabId); + expect(status.loadError).toEqual({ + url: url.slice(0, 2048), + code: -2, + description: "Page crashed", + }); + // The crashed page cannot load anything again, so Reload goes to the page that replaced it. + const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); + yield* viewer.input({ type: "takeControl" }); + yield* viewer.input({ type: "reload" }); + expect(contexts[1]!.page.goto).toHaveBeenCalledWith(url, expect.anything()); + }), + ).pipe(Effect.provide(layer)), +); + it.effect("a tab opened to a file the browser cannot show reports the file to download", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index fdffcc49414ed..8928346b92979 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -377,10 +377,16 @@ interface ServerTab { desktopResize: PromiseWithResolvers; loading: boolean; loadError: PreviewAutomationLoadError | undefined; + /** The renderer crash this page died of, or the one the page it replaced died of. */ + crash: PreviewAutomationLoadError | undefined; + /** What Reload loads after a crash; the reported URL is shortened and drops data payloads. */ + crashedUrl: string | undefined; closing: boolean; recording: Recording | null; initialNavigation: Promise | null; + pendingInitialRequestUrl: string | null; navigationGeneration: number; + stoppedGeneration: number | null; abortedNavigation: { readonly url: string; @@ -584,6 +590,51 @@ const make = Effect.gen(function* () { }, }); + // Playwright cannot reload a crashed page, so a fresh page takes over its tab. + const reopenCrashedTab = async (tab: ServerTab) => { + if (tab.desktop) return dropTab(tab, true); + const key = tabKey(tab.threadId, tab.tabId); + if (tabs.get(key) !== tab) return; + const crash = { + url: ServerBrowserPage.withoutDataPayload(tab.page.url()).slice(0, 2048), + code: -2, + description: "Page crashed", + }; + tab.crash = crash; + const reopening = (async () => { + // The session must name the crash before a new page reads it, or it would load the URL again. + await runPromise( + manager + .reportStatus({ + threadId: tab.threadId, + tabId: tab.tabId, + serverControlled: true, + navStatus: { _tag: "LoadFailed", title: "", ...crash }, + canGoBack: false, + canGoForward: false, + }) + .pipe(Effect.ignore), + ); + dropTab(tab, false, true); + // A context that is still closing would take the new page down with it. + if (tab.isolatedContext) await tab.page.context().close().catch(constVoid); + const { sessions } = await runPromise(manager.list({ threadId: tab.threadId })); + const snapshot = sessions.find( + (session) => session.tabId === tab.tabId && session.runtime === "server", + ); + if (!snapshot) { + throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId }); + } + return createTab(snapshot, tab.page.url()); + })().finally(() => { + pendingTabs.delete(key); + closedPendingTabs.delete(key); + }); + // Reserved before the dead page leaves, so a lookup in between waits for its replacement. + pendingTabs.set(key, { agentId: tab.control.agentId, promise: reopening }); + await reopening.catch(constVoid); + }; + const dialogStatus = (tab: ServerTab) => tab.dialog ? { @@ -636,6 +687,8 @@ const make = Effect.gen(function* () { .send("Page.getNavigationHistory") .catch(() => null) .then((history) => { + // A status the dead page still had in flight must not replace the crash. + if (tab.crash) return; const index = history?.currentIndex ?? 0; const count = history?.entries.length ?? 0; runFork( @@ -830,7 +883,7 @@ const make = Effect.gen(function* () { clearTimeout(timeout); }; - const dropTab = (tab: ServerTab, closeSession: boolean) => { + const dropTab = (tab: ServerTab, closeSession: boolean, reopening = false) => { const key = tabKey(tab.threadId, tab.tabId); if (tabs.get(key) !== tab) return; tabs.delete(key); @@ -838,7 +891,8 @@ const make = Effect.gen(function* () { tab.viewerAttached?.resolve(); clearAbortedNavigation(tab); // A desktop page outlives the connection unless its session closed with it. - const end = tab.desktop && !closeSession && sessionOpen(tab) ? "reconnect" : "gone"; + const end = + (tab.desktop || reopening) && !closeSession && sessionOpen(tab) ? "reconnect" : "gone"; for (const viewer of tab.viewers) viewer.push({ _tag: end }); void tab.control.close().catch(constVoid); if (tab.desktop) void tab.desktop.close().catch(constVoid); @@ -853,7 +907,8 @@ const make = Effect.gen(function* () { const forceClose = setTimeout(() => void page.close().catch(constVoid), PAGE_CLOSE_GRACE_MS); void closed.then(() => clearTimeout(forceClose)); void page - .close({ runBeforeUnload: tab.dialog === null }) + // A crashed page never answers `beforeunload`, so that close would not finish. + .close({ runBeforeUnload: tab.dialog === null && tab.crash === undefined }) .catch(() => page.close()) .catch(constVoid); if (tab.isolatedContext) void closed.then(() => page.context().close()).catch(constVoid); @@ -905,10 +960,13 @@ const make = Effect.gen(function* () { } }; - const createTab = async (snapshot: PreviewSessionSnapshot): Promise => { + const createTab = async ( + snapshot: PreviewSessionSnapshot, + crashedUrl?: string, + ): Promise => { const opened: Array<() => Promise> = []; try { - return await setUpTab(snapshot, opened); + return await setUpTab(snapshot, opened, crashedUrl); } catch (cause) { // An unpublished tab is in no list, so nothing else would ever close it. for (const close of opened.reverse()) await close().catch(constVoid); @@ -919,6 +977,7 @@ const make = Effect.gen(function* () { const setUpTab = async ( snapshot: PreviewSessionSnapshot, opened: Array<() => Promise>, + crashedUrl: string | undefined, ): Promise => { const adopted = adoptedPages.get(tabKey(snapshot.threadId, snapshot.tabId)); adoptedPages.delete(tabKey(snapshot.threadId, snapshot.tabId)); @@ -1007,11 +1066,23 @@ const make = Effect.gen(function* () { desktopResize: Promise.withResolvers(), loading: false, loadError: undefined, + // The page a crash left behind is blank; the session still names what crashed. + crash: + !desktop && !adopted && snapshot.navStatus._tag === "LoadFailed" + ? { + url: snapshot.navStatus.url, + code: snapshot.navStatus.code, + description: snapshot.navStatus.description, + } + : undefined, + crashedUrl, closing: false, recording: null, recordingStart: null, initialNavigation: null, + pendingInitialRequestUrl: null, navigationGeneration: 0, + stoppedGeneration: null, abortedNavigation: null, captureLock: Promise.resolve(), capturing: 0, @@ -1047,10 +1118,22 @@ const make = Effect.gen(function* () { const navigationGenerations = new WeakMap(); page.on("request", (request) => { if (!isMainNavigation(request)) return; + // Playwright can deliver the first request after Stop has already settled its navigation. + const stoppedInitialRequest = + request.url() === tab.pendingInitialRequestUrl && + tab.stoppedGeneration === tab.navigationGeneration; + tab.pendingInitialRequestUrl = null; navigationGenerations.set(request, ++tab.navigationGeneration); clearAbortedNavigation(tab); tab.loading = true; tab.loadError = undefined; + tab.crash = undefined; + tab.crashedUrl = undefined; + if (stoppedInitialRequest) { + tab.stoppedGeneration = tab.navigationGeneration; + settleStoppedNavigation(tab, tab.navigationGeneration); + return; + } report(tab, { _tag: "Loading", url: ServerBrowserPage.withoutDataPayload(request.url()).slice(0, 2048), @@ -1058,6 +1141,7 @@ const make = Effect.gen(function* () { }); }); page.on("load", () => { + tab.pendingInitialRequestUrl = null; tab.loading = false; void reportLoaded(tab); }); @@ -1090,6 +1174,10 @@ const make = Effect.gen(function* () { if (generation !== tab.navigationGeneration) return; // An aborted navigation is usually a download; its `download` event settles the status. if (errorText.includes("ERR_ABORTED")) { + if (tab.stoppedGeneration === generation) { + settleStoppedNavigation(tab, generation); + return; + } const url = request.url(); const navigationGeneration = tab.navigationGeneration; clearAbortedNavigation(tab); @@ -1139,14 +1227,13 @@ const make = Effect.gen(function* () { updateFileChooserInterception(tab); // Popups become tabs and keep `window.opener`, so sign-in popups can report back. page.on("popup", (popup) => void adoptPopup(tab, popup)); - // Playwright cannot reload a crashed page, so it must leave the tab list. const key = tabKey(tab.threadId, tab.tabId); if (closedPendingTabs.delete(key)) { await control.close().catch(constVoid); throw new ServerBrowserTabNotFoundError({ threadId: tab.threadId, tabId: tab.tabId }); } page.on("close", () => dropTab(tab, true)); - page.on("crash", () => dropTab(tab, true)); + page.on("crash", () => reopenCrashedTab(tab)); tabs.set(key, tab); reportLiveTabs(); // A desktop page navigates on its own and can finish loading before these listeners attach. @@ -1156,6 +1243,10 @@ const make = Effect.gen(function* () { snapshot.navStatus._tag === "Loading" && ((!adopted && !desktop) || isPdfAssetUrl(snapshot.navStatus.url)) ) { + tab.loading = true; + const initialUrl = URL.parse(snapshot.navStatus.url); + if (initialUrl) initialUrl.hash = ""; + tab.pendingInitialRequestUrl = initialUrl?.href ?? null; const options = { waitUntil: "commit", timeout: NAVIGATION_TIMEOUT_MS } as const; tab.initialNavigation = ( (desktop || adopted) && page.url() === snapshot.navStatus.url @@ -1193,6 +1284,14 @@ const make = Effect.gen(function* () { tab.abortedNavigation = null; }; + const settleStoppedNavigation = (tab: ServerTab, generation: number) => { + if (tab.navigationGeneration !== generation || !tab.loading) return; + clearAbortedNavigation(tab); + tab.loading = false; + if (tab.page.url() === "about:blank") report(tab, { _tag: "Idle" }); + else void reportLoaded(tab); + }; + const settleAbortedNavigation = ( tab: ServerTab, generation: number, @@ -1797,6 +1896,7 @@ const make = Effect.gen(function* () { }; const loadErrorOf = (tab: ServerTab): PreviewAutomationLoadError | undefined => { + if (tab.crash) return tab.crash; if (!tab.page.url().startsWith("chrome-error://")) return undefined; // A desktop failure from before CDP attached is superseded by any navigation we observe. if (tab.loadError || !tab.desktop || tab.navigationGeneration > 0) return tab.loadError; @@ -1923,6 +2023,7 @@ const make = Effect.gen(function* () { readiness: "load" | "domContentLoaded" | "none", timeout: number, ) => { + tab.pendingInitialRequestUrl = null; const startedAt = performance.now(); const navigation = tab.page.goto(url, { timeout, waitUntil: "commit" }); if (readiness === "none") { @@ -1986,24 +2087,37 @@ const make = Effect.gen(function* () { const opened = await tab.page.context().newCDPSession(tab.page); session = opened; const framesInFlight = new Set>(); + // Chrome withholds frames while acks are outstanding, so ack on arrival and let a + // slow encoder skip to the newest frame instead of throttling the capture. + let pendingFrame: readonly [string, number] | null = null; + const deliverPending = async () => { + while (pendingFrame) { + const next = pendingFrame; + pendingFrame = null; + const accepted = await encoder + .evaluate( + ([data, width]) => + (globalThis as unknown as EncoderWindow).__t3Recorder.frame(data, width), + next, + ) + .catch(() => true); + if (!accepted) { + pendingFrame = null; + await opened.send("Page.stopScreencast").catch(constVoid); + } + } + }; opened.on("Page.screencastFrame", (frame) => { + void opened + .send("Page.screencastFrameAck", { sessionId: frame.sessionId }) + .catch(constVoid); const cssWidth = tab.page.viewportSize()?.width ?? frame.metadata.deviceWidth; - const delivered: Promise = encoder - .evaluate( - ([data, width]) => - (globalThis as unknown as EncoderWindow).__t3Recorder.frame(data, width), - [frame.data, cssWidth] as const, - ) - .then(async (accepted) => { - if (!accepted) await opened.send("Page.stopScreencast"); - }) - .catch(constVoid) - .finally(() => { - framesInFlight.delete(delivered); - void opened - .send("Page.screencastFrameAck", { sessionId: frame.sessionId }) - .catch(constVoid); - }); + const delivering = framesInFlight.size > 0; + pendingFrame = [frame.data, cssWidth]; + if (delivering) return; + const delivered: Promise = deliverPending().finally(() => + framesInFlight.delete(delivered), + ); framesInFlight.add(delivered); }); await opened.send("Page.startScreencast", RECORDING_SCREENCAST); @@ -2581,7 +2695,11 @@ const make = Effect.gen(function* () { return loadError ? { ...snapshot, url: loadError.url, loadError } : snapshot; } case "click": { - const clickInput = input as PreviewAutomationClickInput; + // Time spent queued behind other work on this tab counts against the broker's deadline. + const clickInput = { + ...(input as PreviewAutomationClickInput), + timeoutMs: Math.max(1, Math.floor(deadlineMs - performance.now())), + }; await recordAction(tab, "click", () => ServerBrowserPage.click(tab.page, clickInput, pointerFor(tab)), ); @@ -2692,7 +2810,10 @@ const make = Effect.gen(function* () { const request = event.request; if (request?.clear === "cookies") await tab.cdp.send("Network.clearBrowserCookies"); if (request?.clear === "cache") await tab.cdp.send("Network.clearBrowserCache"); - if (request?.hardReload) await tab.cdp.send("Page.reload", { ignoreCache: true }); + if (request?.hardReload) { + tab.pendingInitialRequestUrl = null; + await tab.cdp.send("Page.reload", { ignoreCache: true }); + } }) .catch((cause: unknown) => runFork(Effect.logWarning("server preview could not apply a tab setting", { cause })), @@ -2834,17 +2955,34 @@ const make = Effect.gen(function* () { case "navigate": if (typeof message.url === "string") { const url = normalizePreviewUrl(message.url); + tab.pendingInitialRequestUrl = null; tab.control.trackUntilHandoff(tab.page.goto(url, VIEWER_NAVIGATION_OPTIONS)); } return; case "history": + tab.pendingInitialRequestUrl = null; tab.control.trackUntilHandoff( num(message.delta) < 0 ? tab.page.goBack(VIEWER_NAVIGATION_OPTIONS) : tab.page.goForward(VIEWER_NAVIGATION_OPTIONS), ); return; + case "stopLoading": { + const generation = tab.navigationGeneration; + tab.stoppedGeneration = generation; + await session.send("Page.stopLoading"); + // Stopping a committed document need not emit Playwright's load or requestfailed events. + settleStoppedNavigation(tab, generation); + return; + } case "reload": + tab.pendingInitialRequestUrl = null; + if (tab.crash) { + tab.control.trackUntilHandoff( + tab.page.goto(tab.crashedUrl ?? tab.crash.url, VIEWER_NAVIGATION_OPTIONS), + ); + return; + } if (message.ignoreCache === true) { await session.send("Page.reload", { ignoreCache: true }); return; diff --git a/apps/server/src/preview/ServerBrowserContexts.ts b/apps/server/src/preview/ServerBrowserContexts.ts index 06c2d4983ea3d..03088a173a815 100644 --- a/apps/server/src/preview/ServerBrowserContexts.ts +++ b/apps/server/src/preview/ServerBrowserContexts.ts @@ -14,6 +14,43 @@ const requirePlaywright = NodeModule.createRequire(import.meta.url); const loadPlaywright = () => requirePlaywright("playwright-core") as typeof import("playwright-core"); +const BADGE_STUB = `if (typeof WorkerNavigator === "function") for (const name of ["setAppBadge", "clearAppBadge"]) WorkerNavigator.prototype[name] = () => Promise.resolve();`; + +interface CdpSession { + send(method: string, params?: object): Promise; + createChildSession(...args: ReadonlyArray): CdpSession; +} + +// The headless shell binds no BadgeService for service workers and kills the renderer of a +// worker that calls navigator.setAppBadge. Playwright resumes each worker itself, so the stub +// can only go in ahead of that resume through its in-process session; without it nothing is stubbed. +const stubWorkerBadges = (client: Browser | BrowserContext) => { + const { _connection: connection } = client as unknown as { + readonly _connection?: { + readonly toImpl?: ( + client: unknown, + ) => + | { readonly _session?: CdpSession; readonly _browser?: { readonly _session?: CdpSession } } + | undefined; + }; + }; + const impl = connection?.toImpl?.(client); + const root = impl?._browser?._session ?? impl?._session; + if (!root) return; + const createChildSession = root.createChildSession.bind(root); + root.createChildSession = (...args) => { + const session = createChildSession(...args); + const send = session.send.bind(session); + session.send = (method, params) => { + if (method === "Runtime.runIfWaitingForDebugger") { + void send("Runtime.evaluate", { expression: BADGE_STUB }).catch(constVoid); + } + return send(method, params); + }; + return session; + }; +}; + interface Options { readonly profilesDir: string; readonly executable: () => Promise; @@ -127,6 +164,7 @@ export class ServerBrowserContexts { const browser = await this.launch(executable, (executablePath) => chromium.launch({ ...options, executablePath }), ); + stubWorkerBadges(browser); browser.on("disconnected", () => { if (this.browser === launched) this.browser = undefined; }); @@ -207,13 +245,15 @@ export class ServerBrowserContexts { await NodeFSP.mkdir(directory, { recursive: true }); const { executable, ...options } = await this.launchOptions(); const { chromium } = loadPlaywright(); - return this.launch(executable, (executablePath) => + const context = await this.launch(executable, (executablePath) => chromium.launchPersistentContext(directory, { ...options, ...contextOptions, executablePath, }), ); + stubWorkerBadges(context); + return context; } private profileDirectory(profileId: string) { diff --git a/apps/server/src/preview/ServerBrowserPage.test.ts b/apps/server/src/preview/ServerBrowserPage.test.ts index 8225597d380fd..550943312c2f1 100644 --- a/apps/server/src/preview/ServerBrowserPage.test.ts +++ b/apps/server/src/preview/ServerBrowserPage.test.ts @@ -173,10 +173,22 @@ describe("server browser element refs", () => { const hidden = await failure("button"); expect(hidden.tag).toBe("PreviewAutomationTimeoutError"); expect(hidden.message).toBe( - 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout.', + 'The click may have happened; check the page before retrying. "button" still matches an element after the timeout. Playwright last saw: element is not visible.', ); }); + it("gives a late target only the click's remaining time, not a fresh timeout", async () => { + await page.setContent(``); + await expect( + ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 2_000 }), + ).rejects.toThrow(); + expect(await page.locator("body").getAttribute("data-clicked")).toBeNull(); + }); + it("does not retarget a removed ref to a replacement node", async () => { await page.setContent(""); const locator = buttonLocator((await takeSnapshot()).accessibilityTree, "original"); @@ -610,6 +622,67 @@ describe("server browser drag", () => { }); }); +describe("server browser click", () => { + it("clicks a target the page replaced while it was being scrolled into view", async () => { + let scrolls = 0; + const clicks: Array = []; + const page = { + locator: () => ({ + // Playwright resolves the node once; a page re-rendering it detaches that node. + scrollIntoViewIfNeeded: async () => { + if (scrolls++ === 0) { + throw new Error("locator.scrollIntoViewIfNeeded: Element is not attached to the DOM"); + } + }, + boundingBox: async () => ({ x: 0, y: 0, width: 20, height: 20 }), + click: async (options: unknown) => { + clicks.push(options); + }, + count: async () => 1, + }), + once: () => {}, + off: () => {}, + } as unknown as Page; + + await expect(ServerBrowserPage.click(page, { selector: "#save" })).resolves.toEqual({ + x: 10, + y: 10, + }); + expect(clicks).toHaveLength(1); + }); + + it("retries a replaced target only within the action's timeout", async () => { + vi.useFakeTimers(); + try { + const timeouts: Array = []; + const clicks: Array = []; + const detached = new Error( + "locator.scrollIntoViewIfNeeded: Element is not attached to the DOM", + ); + const page = { + locator: () => ({ + scrollIntoViewIfNeeded: async (options?: { timeout?: number }) => { + timeouts.push(options?.timeout); + vi.advanceTimersByTime(60); + throw detached; + }, + click: async (options: unknown) => { + clicks.push(options); + }, + }), + } as unknown as Page; + + await expect( + ServerBrowserPage.click(page, { selector: "#save", timeoutMs: 100 }), + ).rejects.toBe(detached); + expect(timeouts).toEqual([100, 40]); + expect(clicks).toHaveLength(0); + } finally { + vi.useRealTimers(); + } + }); +}); + describe("server browser evaluate", () => { it("does not retry a parse error that arrives after the timeout", async () => { vi.useFakeTimers(); diff --git a/apps/server/src/preview/ServerBrowserPage.ts b/apps/server/src/preview/ServerBrowserPage.ts index 65a283dc3cca4..3354554f1dd90 100644 --- a/apps/server/src/preview/ServerBrowserPage.ts +++ b/apps/server/src/preview/ServerBrowserPage.ts @@ -22,6 +22,7 @@ import { constVoid } from "effect/Function"; import * as Schema from "effect/Schema"; import type { CDPSession, ConsoleMessage, Frame, Locator, Page } from "playwright-core"; import * as NodeCrypto from "node:crypto"; +import * as NodeUtil from "node:util"; import { BrowserControlInterrupted } from "./SessionControl.ts"; const isBrowserControlInterrupted = Schema.is(BrowserControlInterrupted); @@ -62,7 +63,7 @@ export const toOperationError = ( if (cause instanceof Error && cause.name === "TimeoutError") { return new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: firstLine, + message: withActionabilityReason(firstLine, cause), detail: timeoutMs === undefined ? undefined : { timeoutMs }, }); } @@ -84,6 +85,17 @@ export const toOperationError = ( }); }; +/** Playwright puts why an element was not actionable in its call log, below the first line. */ +const withActionabilityReason = (message: string, cause: Error) => { + // Playwright dims call-log lines with ANSI escapes when colour is on. + const reason = NodeUtil.stripVTControlCharacters(cause.message) + .split("\n") + .map((line) => line.trim()) + .findLast((line) => line.startsWith("- element is ")) + ?.slice(2); + return reason === undefined ? message : `${message} Playwright last saw: ${reason}.`; +}; + const DEFAULT_TIMEOUT_MS = 15_000; const TARGET_COUNT_MS = 250; const MAX_TARGET_CHARS = 200; @@ -147,15 +159,32 @@ export type PointerReporter = ( ) => Promise; const noPointer: PointerReporter = async () => {}; +// Locator.scrollIntoViewIfNeeded resolves its node once and fails when the page replaces it; the +// input actions after it re-resolve, so the scroll does too, within the same timeout. +const DETACHED = /^locator\.scrollIntoViewIfNeeded: Element is not attached to the DOM(?:\n|$)/; + +const scrollIntoView = async (locator: Locator, timeout: number) => { + const deadline = Date.now() + timeout; + for (;;) { + try { + return await locator.scrollIntoViewIfNeeded({ timeout: Math.max(1, deadline - Date.now()) }); + } catch (cause) { + if (!(cause instanceof Error && DETACHED.test(cause.message)) || Date.now() >= deadline) { + throw cause; + } + } + } +}; + const targetPoint = async ( page: Page, locator: Locator | null, input: { readonly x?: number | undefined; readonly y?: number | undefined }, - timeout: number, + timeout: () => number, ) => { if (locator === null) return { x: input.x ?? 0, y: input.y ?? 0 }; - await locator.scrollIntoViewIfNeeded({ timeout }); - const box = await locator.boundingBox({ timeout }); + await scrollIntoView(locator, timeout()); + const box = await locator.boundingBox({ timeout: timeout() }); if (box) return { x: box.x + box.width / 2, y: box.y + box.height / 2 }; const viewport = page.viewportSize(); return { x: (viewport?.width ?? 0) / 2, y: (viewport?.height ?? 0) / 2 }; @@ -694,10 +723,12 @@ export const click = async ( input: PreviewAutomationClickInput, pointer: PointerReporter = noPointer, ): Promise<{ readonly x: number; readonly y: number }> => { - const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + // One deadline across steps keeps the reply inside the broker's grace; Playwright reads 0 as none. + const deadline = Date.now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS); + const remaining = () => Math.max(1, deadline - Date.now()); const locator = targetLocator(page, input); try { - return await clickTarget(page, locator, input, timeout, pointer); + return await clickTarget(page, locator, input, remaining, pointer); } catch (cause) { throw locator === null ? cause : await namedTargetTimeout(locator, input, cause); } @@ -733,10 +764,11 @@ const namedTargetTimeout = async ( : matches === 0 ? `The click may have happened and removed its target or navigated; check the page before retrying. No element matches ${target} after the timeout; take a fresh snapshot and use its locator.` : `The click may have happened; check the page before retrying. ${target} still matches an element after the timeout.`; + const message = withActionabilityReason(reason, cause); return new ServerBrowserOperationError({ tag: "PreviewAutomationTimeoutError", - message: reason, - detail: { reason }, + message, + detail: { reason: message }, cause, }); }; @@ -745,7 +777,7 @@ const clickTarget = async ( page: Page, locator: Locator | null, input: PreviewAutomationClickInput, - timeout: number, + timeout: () => number, pointer: PointerReporter, ) => { const point = await targetPoint(page, locator, input, timeout); @@ -754,7 +786,7 @@ const clickTarget = async ( const clicked = locator === null ? page.mouse.click(point.x, point.y, options) - : locator.click({ ...options, timeout }); + : locator.click({ ...options, timeout: timeout() }); let onDialog = constVoid; const dialogOpened = new Promise<"dialog">((resolve) => { onDialog = () => resolve("dialog"); @@ -835,7 +867,7 @@ export const hover = async ( ) => { const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const locator = targetLocator(page, input); - await pointer(await targetPoint(page, locator, input, timeout), "move"); + await pointer(await targetPoint(page, locator, input, () => timeout), "move"); if (locator === null) { await page.mouse.move(input.x ?? 0, input.y ?? 0); return; @@ -886,7 +918,7 @@ export const drag = async ( const timeout = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const source = targetLocator(page, { locator: input.source })!; const target = targetLocator(page, { locator: input.target })!; - await pointer(await targetPoint(page, source, {}, timeout), "move"); + await pointer(await targetPoint(page, source, {}, () => timeout), "move"); // Observe drag rejection immediately; an unhandled rejection during cursor movement exits the server. // Chromium delivers a single move before dragstart; steps give the page mousemoves during the drag. const dragFailure = source.dragTo(target, { timeout, steps: 5 }).then( @@ -1103,7 +1135,8 @@ export const recordingEncoderScript = (frameRate: BrowserRecordingFrameRate) => window.__t3Recorder = { async frame(base64, cssWidth) { if (tooLarge) return false; - const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)); + // A per-character atob copy costs ~30 ms on a 3200x1800 frame and throttles recordings. + const bytes = Uint8Array.fromBase64(base64); const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/jpeg" })); if (tooLarge) { bitmap.close(); return false; } if (!recorder) { diff --git a/apps/server/src/preview/ServerBrowserStream.test.ts b/apps/server/src/preview/ServerBrowserStream.test.ts index 30cd298fea7b8..c0a9fbc923ff2 100644 --- a/apps/server/src/preview/ServerBrowserStream.test.ts +++ b/apps/server/src/preview/ServerBrowserStream.test.ts @@ -57,6 +57,7 @@ const mutations = [ { type: "navigate", url: "https://example.com" }, { type: "history", delta: -1 }, { type: "reload" }, + { type: "stopLoading" }, { type: "probe", x: 10, y: 10 }, { type: "takeControl" }, { type: "releaseControl" }, diff --git a/apps/server/src/process/NonBlockingSpawner.test.ts b/apps/server/src/process/NonBlockingSpawner.test.ts new file mode 100644 index 0000000000000..81563cbab70dc --- /dev/null +++ b/apps/server/src/process/NonBlockingSpawner.test.ts @@ -0,0 +1,200 @@ +// @effect-diagnostics nodeBuiltinImport:off - the spawner's checks are node:fs/promises calls, which the test spies on. +import * as NodeFSP from "node:fs/promises"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { describe, expect, it } from "@effect/vitest"; +import { vi } from "vite-plus/test"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; + +import * as NonBlockingSpawner from "./NonBlockingSpawner.ts"; + +vi.mock("node:fs/promises", { spy: true }); + +const hostPath = process.env.PATH; + +const wrapped = NonBlockingSpawner.layer.pipe(Layer.provideMerge(NodeServices.layer)); + +/** What a caller sees of a command: its output, or the error of a spawn that failed. */ +const outcome = (command: ChildProcess.Command) => + ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.string(command)).pipe( + Effect.match({ + onSuccess: (output) => ({ output }), + onFailure: (error) => ({ reason: error.reason._tag, message: error.message }), + }), + ); + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")("NonBlockingSpawner", () => { + it.live("gives callers what the native spawner gives them", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const root = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped()); + for (const [file, mode] of [ + ["stale/tool", 0o644], + ["fresh/tool", 0o755], + ["target/bin/tool", 0o755], + // GNU env reads a lone `-` as -i and `NAME=value` as an assignment, even after `--`. + ["fresh/-", 0o755], + ["fresh/launch=stable", 0o755], + ] as const) { + yield* fileSystem.makeDirectory(`${root}/${file.slice(0, file.lastIndexOf("/"))}`, { + recursive: true, + }); + yield* fileSystem.writeFileString(`${root}/${file}`, `#!/bin/sh\necho ${file} "$@"\n`); + yield* fileSystem.chmod(`${root}/${file}`, mode); + } + yield* fileSystem.makeDirectory(`${root}/target/subdir`); + yield* fileSystem.symlink(`${root}/target/subdir`, `${root}/link`); + const PATH = `${root}/stale:${root}/fresh`; + + const commands = { + "enters the cwd": ChildProcess.make("pwd", ["-P"], { cwd: root }), + "keeps argv": ChildProcess.make( + "printf", + ["%s\\n", "-n", "--", "a b", `it's "quoted"`, "$HOME", "; exit 3", "", "A=b"], + { cwd: root }, + ), + // dash would drop the exported function and add PWD and OLDPWD. + "keeps the environment": ChildProcess.make("env", [], { + cwd: root, + env: { PATH: hostPath, A: "1", "BASH_FUNC_x%%": "() { echo exported\n}" }, + }), + "skips a non-executable PATH entry": ChildProcess.make("tool", [], { env: { PATH } }), + "resolves `..` in PATH after a symlink": ChildProcess.make("tool", [], { + env: { PATH: `${root}/link/../bin` }, + }), + "searches PATH relative to the cwd": ChildProcess.make("tool", [], { + cwd: root, + env: { PATH: "fresh" }, + }), + "a command named -": ChildProcess.make("-", [], { cwd: root, env: { PATH } }), + "a command containing =": ChildProcess.make("launch=stable", [], { env: { PATH } }), + "shell mode": ChildProcess.make('pwd -P; echo "$0" "a b"', [], { cwd: root, shell: true }), + "a pipeline": ChildProcess.make("printf", ["a\\nb\\n"], { cwd: root }).pipe( + ChildProcess.pipeTo(ChildProcess.make("tail", ["-n", "1"])), + ), + "a missing command": ChildProcess.make("t3code-missing-command", ["--version"]), + "a missing command in a cwd": ChildProcess.make("t3code-missing-command", [], { + cwd: root, + }), + "a non-executable command": ChildProcess.make("tool", [], { + env: { PATH: `${root}/stale` }, + }), + "a missing explicit path": ChildProcess.make("./missing", [], { cwd: root }), + "a non-executable explicit path": ChildProcess.make(`${root}/stale/tool`, []), + "a missing cwd": ChildProcess.make("true", [], { cwd: `${root}/missing` }), + // The native check sees `missing`, although the path resolves to an existing directory. + "a cwd through a missing directory": ChildProcess.make("true", [], { + cwd: `${root}/missing/..`, + }), + }; + for (const [name, command] of Object.entries(commands)) { + const native = yield* outcome(command).pipe(Effect.provide(NodeServices.layer)); + expect(yield* outcome(command).pipe(Effect.provide(wrapped)), name).toEqual(native); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live("hands the native spawner only `env`, never a cwd or a command to look up", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const directory = yield* fileSystem.makeTempDirectoryScoped(); + const received: Array = []; + const record = (command: ChildProcess.Command): void => { + if (command._tag === "StandardCommand") received.push(command); + else [command.left, command.right].forEach(record); + }; + const recording = Layer.effect( + ChildProcessSpawner.ChildProcessSpawner, + Effect.map(ChildProcessSpawner.ChildProcessSpawner, (native) => + ChildProcessSpawner.make((command) => { + record(command); + return native.spawn(command); + }), + ), + ).pipe(Layer.provideMerge(NodeServices.layer)); + const commands = [ + ChildProcess.make("true", [], { cwd: directory }), + ChildProcess.make("true", []), + ChildProcess.make("/bin/true", []), + ChildProcess.make("t3code-missing-command", []), + ChildProcess.make("true", [], { cwd: directory, shell: true }), + ChildProcess.make("printf", ["a"], { cwd: directory }).pipe( + ChildProcess.pipeTo(ChildProcess.make("cat", [], { cwd: directory })), + ), + ]; + yield* Effect.forEach(commands, (command) => + ChildProcessSpawner.ChildProcessSpawner.use((spawner) => spawner.exitCode(command)).pipe( + Effect.exit, + ), + ).pipe(Effect.provide(NonBlockingSpawner.layer.pipe(Layer.provide(recording)))); + + expect(received.map((command) => [command.command, command.options.cwd])).toEqual( + Array.from({ length: 6 }, () => ["/usr/bin/env", undefined]), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live("checks at most two paths at once, however many directories hang", () => + Effect.gen(function* () { + const allArrived = yield* Deferred.make(); + let arrivals = 0; + // Each spawn resolves its cwd, then starts its check within microtasks. + const arrivalPath = Layer.effect( + Path.Path, + Effect.map(Path.Path, (path) => ({ + ...path, + resolve: (...segments: ReadonlyArray) => { + if (++arrivals === 3) setImmediate(() => Deferred.doneUnsafe(allArrived, Effect.void)); + return path.resolve(...segments); + }, + })), + ); + const hung: Array<() => void> = []; + let releasing = false; + let running = 0; + let mostRunning = 0; + using _access = vi.spyOn(NodeFSP, "access").mockImplementation( + () => + new Promise((_resolve, reject) => { + mostRunning = Math.max(mostRunning, ++running); + const fail = () => { + running--; + reject(Object.assign(new Error("ENOENT"), { code: "ENOENT" })); + }; + if (releasing) fail(); + else hung.push(fail); + }), + ); + const spawns = yield* Effect.forEach( + ["a", "b", "c"], + (name) => + ChildProcessSpawner.ChildProcessSpawner.use((spawner) => + spawner.exitCode(ChildProcess.make("true", [], { cwd: `/t3code-hung/${name}` })), + ).pipe(Effect.flip), + { concurrency: "unbounded" }, + ).pipe( + Effect.provide( + NonBlockingSpawner.layer.pipe( + Layer.provide(arrivalPath), + Layer.provide(NodeServices.layer), + ), + ), + Effect.forkChild, + ); + yield* Deferred.await(allArrived); + expect(mostRunning).toBe(2); + releasing = true; + for (const fail of hung.splice(0)) fail(); + yield* Fiber.join(spawns); + expect(mostRunning).toBe(2); + }), + ); +}); diff --git a/apps/server/src/process/NonBlockingSpawner.ts b/apps/server/src/process/NonBlockingSpawner.ts new file mode 100644 index 0000000000000..0807b287cb9cc --- /dev/null +++ b/apps/server/src/process/NonBlockingSpawner.ts @@ -0,0 +1,178 @@ +// @effect-diagnostics nodeBuiltinImport:off - execvp's X_OK test has no Effect FileSystem equivalent. +import * as NodeFS from "node:fs"; +import * as NodeFSP from "node:fs/promises"; + +import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; +import * as Redacted from "effect/Redacted"; +import * as ChildProcess from "effect/process/ChildProcess"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import * as CommandLine from "effect/process/CommandLine"; + +// libuv's _PATH_DEFPATH, searched when the child environment has no PATH. +const DEFAULT_PATH = "/usr/bin:/bin"; + +// A check on a hung mount holds a libuv threadpool thread until the mount answers, and the +// pool's four threads also compress every WebSocket frame. Checks therefore run one at a time +// per directory and two at a time overall; the rest wait without holding a thread. +const CHECK_LIMIT = 2; +const directoryTails = new Map>(); +const waiting: Array<() => void> = []; +let running = 0; + +const access = async (path: string, mode: number) => { + if (running < CHECK_LIMIT) running++; + else await new Promise((resume) => waiting.push(resume)); + try { + await NodeFSP.access(path, mode); + return undefined; + } catch (error) { + return error as NodeJS.ErrnoException; + } finally { + // A waiter takes over the slot. + const next = waiting.shift(); + if (next === undefined) running--; + else next(); + } +}; + +/** The errno error of `access(path, mode)`, or undefined when it passes. */ +const check = (directory: string, path: string, mode: number) => { + const result = (directoryTails.get(directory) ?? Promise.resolve()).then(() => + access(path, mode), + ); + directoryTails.set(directory, result); + void result.then(() => { + if (directoryTails.get(directory) === result) directoryTails.delete(directory); + }); + return Effect.promise(() => result); +}; + +// The PATH the child searches, from the environment Effect's Node spawner gives it. +const childPath = ({ env, extendEnv }: ChildProcess.CommandOptions) => { + if (env === undefined) return process.env.PATH; + if (!Object.hasOwn(env, "PATH")) return extendEnv === true ? process.env.PATH : undefined; + const value = env.PATH; + return value === undefined || !Redacted.isRedacted(value) ? value : Redacted.value(value); +}; + +// The spawn error Effect's Node spawner reports when execvp fails with `code`. +const spawnFailure = (command: ChildProcess.StandardCommand, code: "ENOENT" | "EACCES") => { + const syscall = `spawn ${command.command}`; + return PlatformError.systemError({ + _tag: code === "ENOENT" ? "NotFound" : "PermissionDenied", + module: "ChildProcess", + method: "spawn", + pathOrDescriptor: CommandLine.display([command.command, ...command.args], { format: "posix" }), + syscall, + cause: Object.assign(new Error(`${syscall} ${code}`), { + errno: code === "ENOENT" ? -2 : -13, + code, + syscall, + path: command.command, + spawnargs: command.args.map((arg) => (Redacted.isRedacted(arg) ? "" : arg)), + }), + }); +}; + +// The error of the `FileSystem.access(cwd)` Effect's Node spawner runs before it spawns. +const cwdFailure = (cwd: string, cause: NodeJS.ErrnoException) => + PlatformError.systemError({ + _tag: + cause.code === "ENOENT" + ? "NotFound" + : cause.code === "EACCES" || cause.code === "EPERM" + ? "PermissionDenied" + : cause.code === "ENOTDIR" || cause.code === "ELOOP" + ? "BadResource" + : "Unknown", + module: "FileSystem", + method: "access", + pathOrDescriptor: cwd, + syscall: cause.syscall, + cause, + }); + +/** + * Fails as a native spawn does when the command is missing or not executable: callers read + * that error to tell a CLI that is not installed from one that failed. execvp reports EACCES + * when a candidate exists but cannot be run, and ENOENT otherwise. + */ +const findExecutable = Effect.fnUntraced(function* ( + command: ChildProcess.StandardCommand, + cwd: string | undefined, +) { + // Joined as text: the kernel resolves `..` after a symlink differently from a normalized path. + const fromCwd = (path: string) => + cwd === undefined || path.startsWith("/") ? path : `${cwd}/${path}`; + const candidates = command.command.includes("/") + ? [fromCwd(command.command)] + : (childPath(command.options) ?? DEFAULT_PATH) + .split(":") + .map((entry) => `${fromCwd(entry || ".")}/${command.command}`); + let denied = false; + for (const candidate of candidates) { + const error = yield* check( + candidate.slice(0, candidate.lastIndexOf("/")) || "/", + candidate, + NodeFS.constants.X_OK, + ); + // Any other errno is left for `env` to report through its exit code. + if (error === undefined || (error.code !== "ENOENT" && error.code !== "EACCES")) return; + denied ||= error.code === "EACCES"; + } + return yield* spawnFailure(command, denied ? "EACCES" : "ENOENT"); +}); + +const make = Effect.gen(function* () { + const native = yield* ChildProcessSpawner.ChildProcessSpawner; + if ((yield* HostProcess.Platform) !== "linux") return native; + if (!(yield* Effect.promise(supportsEnvChdir))) return native; + const path = yield* Path.Path; + + // Runs inside the NonBlockingSpawner.spawn span. + const prepareStandard = Effect.fnUntraced(function* (input: ChildProcess.StandardCommand) { + const { cwd: givenCwd, shell, ...options } = input.options; + // Effect rejects a shell command with arguments, and a NUL, itself. + if ((shell && input.args.length > 0) || input.command.includes("\0")) return input; + // Node's shell mode on Unix, spelled out so the trampoline can run it. + const command = shell + ? ChildProcess.make(typeof shell === "string" ? shell : "/bin/sh", ["-c", input.command]) + : input; + // Checked as given and entered resolved, as Effect's Node spawner does. + const cwd = givenCwd === undefined ? undefined : path.resolve(givenCwd); + const trampoline = envTrampoline(command.command, command.args, cwd); + if (trampoline === undefined) return input; + if (givenCwd !== undefined && cwd !== undefined) { + const error = yield* check(cwd, givenCwd, NodeFS.constants.F_OK); + if (error !== undefined) return yield* cwdFailure(givenCwd, error); + } + yield* findExecutable(ChildProcess.make(command.command, command.args, options), cwd); + return ChildProcess.make(trampoline.command, trampoline.args, options); + }); + + const prepare = ( + command: ChildProcess.Command, + ): Effect.Effect => + command._tag === "StandardCommand" + ? prepareStandard(command) + : Effect.map(Effect.all([prepare(command.left), prepare(command.right)]), ([left, right]) => + ChildProcess.pipeTo(left, right, command.options), + ); + + return ChildProcessSpawner.make( + Effect.fn("NonBlockingSpawner.spawn")(function* (command) { + return yield* native.spawn(yield* prepare(command)); + }), + ); +}); + +/** + * On Linux with GNU `env`, replaces the provided `ChildProcessSpawner` with one that never + * hands libuv a cwd or a PATH search; elsewhere it passes the provided one through. + */ +export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make); diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index b05a0a0504cdd..4378a7fde8470 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -92,6 +92,7 @@ function candidate( { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, ], }, + worktree: null as { path: string; branch: string | null } | null, } satisfies AgentSessionScanner.AgentSessionRecentThread; } @@ -304,6 +305,7 @@ it.effect( ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); unowned.thread.omittedMessageCount = 1; + unowned.worktree = { path: "/workspace/project/.claude/worktrees/feat", branch: "feat" }; const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); const importer = yield* makeImporter([ active, @@ -356,6 +358,8 @@ it.effect( expect(notices).toEqual([]); } expect(records.thread.historyOrigin).toBe("v1_import"); + expect(records.thread.worktreePath).toBe(source.worktree?.path ?? null); + expect(records.thread.branch).toBe(source.worktree?.branch ?? null); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({ @@ -364,7 +368,10 @@ it.effect( source.source.provider === "claudeAgent" ? { threadId, resume: source.source.providerSessionId } : { threadId: nativeId(source) }, - runtimePayload: { importedTranscripts: [source.source] }, + runtimePayload: { + cwd: source.worktree?.path ?? "/workspace/project", + importedTranscripts: [source.source], + }, }); } }).pipe(Effect.scoped, Effect.provide(persistence)), diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 9c80ebf1049bf..6200fc11188fb 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -309,7 +309,7 @@ const make = Effect.gen(function* () { thread.source === "claudeAgent" ? { threadId, resume: thread.providerSessionId } : { threadId: nativeThreadId }, - runtimePayload: { cwd: project.workspaceRoot }, + runtimePayload: { cwd: outcome.worktree?.path ?? project.workspaceRoot }, }, { onConflict: "ignore" }, ); @@ -362,8 +362,8 @@ const make = Effect.gen(function* () { modelSelection: { instanceId: thread.providerInstanceId, model }, runtimeMode, interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - branch: null, - worktreePath: null, + branch: outcome.worktree?.branch ?? null, + worktreePath: outcome.worktree?.path ?? null, linkedPullRequest: null, branchPullRequest: null, activeProviderThreadId: providerThreadId, diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 30db62847e8e1..6dac5a1b0b6c9 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -5,6 +5,7 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; +import * as NodeZlib from "node:zlib"; import { describe, expect, it } from "@effect/vitest"; import { AgentSessionImportSource, @@ -174,6 +175,21 @@ const writeTranscript = Effect.fn("AgentSessionScanner.test.writeTranscript")(fu yield* fileSystem.utimes(input.filePath, seconds, seconds); }); +const writeCompressedTranscript = Effect.fn("AgentSessionScanner.test.writeCompressedTranscript")( + function* (input: { + readonly filePath: string; + readonly contents: string; + readonly mtimeMs: number; + }) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fileSystem.makeDirectory(path.dirname(input.filePath), { recursive: true }); + yield* fileSystem.writeFile(input.filePath, NodeZlib.zstdCompressSync(input.contents)); + const seconds = input.mtimeMs / 1000; + yield* fileSystem.utimes(input.filePath, seconds, seconds); + }, +); + const claudeSessionLine = (cwd: string) => `${JSON.stringify({ type: "user", cwd, sessionId: "s1" })}\n${JSON.stringify({ type: "assistant" })}\n`; @@ -1088,6 +1104,70 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("imports a checkout's sessions from the linked worktrees the scan counts", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const repo = yield* makeTempDir("t3code-workspace-repo-"); + yield* fileSystem.makeDirectory(path.join(repo, ".git")); + yield* fileSystem.writeFileString(path.join(repo, ".git", "config"), "[core]\n"); + const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature"); + yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true }); + yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n"); + yield* fileSystem.writeFileString( + path.join(worktreeGitDir, "HEAD"), + "ref: refs/heads/feature\n", + ); + const worktree = path.join(repo, ".claude", "worktrees", "feature"); + yield* fileSystem.makeDirectory(worktree, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(worktree, ".git"), + `gitdir: ${worktreeGitDir}\n`, + ); + + for (const [index, [cwd, sessionId]] of [ + [repo, "at-root"], + [worktree, "in-worktree"], + ].entries()) { + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, `${sessionId}.jsonl`), + contents: `${JSON.stringify({ + type: "user", + cwd, + sessionId, + message: { role: "user", content: "Fix the project" }, + })}\n${JSON.stringify({ + type: "assistant", + sessionId, + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + })}\n`, + mtimeMs: nowMs - (index + 1) * 60 * 60 * 1000, + }); + } + + const input = { claudeHomePath, codexHomePath }; + const { candidates } = yield* runScan(input); + expect(candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: repo, threadCount: 2 }, + ]); + const outcomes = yield* runRecentThreadOutcomes({ ...input, workspaceRoot: repo }); + expect( + outcomes.flatMap((outcome) => + outcome._tag === "Importable" + ? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }] + : [], + ), + ).toEqual([ + { sessionId: "at-root", worktree: null }, + { sessionId: "in-worktree", worktree: { path: worktree, branch: "feature" } }, + ]); + }), + ); + it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1244,6 +1324,32 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { const result = yield* runScan({ claudeHomePath, codexHomePath }); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: workspace, threadCount: 1 }, + ]); + }), + ); + it.effect("discovers projects whose Codex rollouts are zstd-compressed", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeCompressedTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "05", + "03", + "rollout-2026-05-03T00-00-00-019a5f00-0000-7000-8000-00000000000b.jsonl.zst", + ), + contents: codexRolloutLine(workspace), + mtimeMs: Date.parse("2026-05-03T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath }); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ { path: workspace, threadCount: 1 }, ]); @@ -1252,6 +1358,66 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); describe("recentThreads", () => { + it.effect("imports Codex conversations stored only as zstd-compressed rollouts", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const workspace = yield* makeTempDir("t3code-workspace-"); + yield* writeCompressedTranscript({ + filePath: path.join( + codexHomePath, + "sessions", + "2026", + "08", + "20", + "rollout-2026-08-20T10-00-00-019a5f00-0000-7000-8000-00000000000c.jsonl.zst", + ), + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: "019a5f00-0000-7000-8000-00000000000c", cwd: workspace }, + }), + encodeTranscriptRecord({ + type: "event_msg", + timestamp: "2026-08-20T10:00:00.000Z", + payload: { type: "user_message", message: "Compressed prompt" }, + }), + encodeTranscriptRecord({ + type: "response_item", + timestamp: "2026-08-20T10:01:00.000Z", + payload: { + type: "message", + role: "assistant", + content: [{ type: "output_text", text: "Compressed answer" }], + }, + }), + ].join("\n"), + mtimeMs: nowMs - 4 * 24 * 60 * 60 * 1000, + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + workspaceRoot: workspace, + }); + + expect( + threads.map((thread) => ({ + id: thread.providerSessionId, + messages: thread.messages.map((message) => message.text), + })), + ).toEqual([ + { + id: "019a5f00-0000-7000-8000-00000000000c", + messages: ["Compressed prompt", "Compressed answer"], + }, + ]); + }), + ); + it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index d9ca41b8f26b1..0de2e84b1f6e3 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -1,5 +1,6 @@ import * as NodeOS from "node:os"; import * as NodeSqlite from "node:sqlite"; +import * as NodeZlib from "node:zlib"; import { AgentSessionImportSource, @@ -17,11 +18,13 @@ import { import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as NodeStream from "@effect/platform-node/NodeStream"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Pull from "effect/Pull"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -177,7 +180,11 @@ const decodeCodexHistoryBase = Schema.decodeUnknownOption( ); // Original rollouts end in their thread ID, rewound ones in `_`. const CODEX_ROLLOUT_ID_PATTERN = - /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl$/i; + /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:_([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}))?\.jsonl(?:\.zst)?$/i; +// Codex zstd-compresses older rollouts; their byte limits and offsets count decompressed bytes. +const COMPRESSED_TRANSCRIPT_SUFFIX = ".jsonl.zst"; +const isCompressedTranscript = (filePath: string) => + filePath.endsWith(COMPRESSED_TRANSCRIPT_SUFFIX); // Codex records a chat's project only here; moving a chat leaves its rollout cwd unchanged. const CODEX_STATE_DATABASE = "state_5.sqlite"; const decodeCodexSessionIndexEntry = Schema.decodeUnknownOption( @@ -216,6 +223,8 @@ export type AgentSessionRecentThread = readonly _tag: "Importable"; readonly thread: AgentSessionThread; readonly source: AgentSessionImportSource; + /** The root's linked worktree the session ran in, or null when it ran in the root. */ + readonly worktree: { readonly path: string; readonly branch: string | null } | null; } | { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource } | { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource } @@ -861,6 +870,33 @@ export const make = Effect.gen(function* () { const statOption = (target: string) => fileSystem.stat(target).pipe(Effect.asSome, Effect.orElseSucceed(Option.none)); + const transcriptChunkReader = Effect.fn("AgentSessionScanner.transcriptChunkReader")(function* ( + file: FileSystem.File, + filePath: string, + ) { + if (!isCompressedTranscript(filePath)) return (size: number) => file.readAlloc(size); + const pull = yield* Stream.toPull( + fileSystem + .stream(filePath) + .pipe(NodeStream.pipeThroughSimple(() => NodeZlib.createZstdDecompress())), + ); + let pending: Array = []; + let done = false; + // Untraced: called once per chunk inside the caller's traced read. + return Effect.fnUntraced(function* (size: number) { + while (pending.length === 0) { + if (done) return Option.none(); + const next = yield* pull.pipe(Pull.catchDone(() => Effect.undefined)); + if (next === undefined) done = true; + else pending = [...next]; + } + const chunk = pending.shift(); + if (chunk === undefined) return Option.none(); + if (chunk.byteLength > size) pending.unshift(chunk.subarray(size)); + return Option.some(chunk.subarray(0, size)); + }); + }); + const directoryIdentity = Effect.fn("AgentSessionScanner.directoryIdentity")(function* ( target: string, knownStats?: FileSystem.File.Info, @@ -945,19 +981,24 @@ export const make = Effect.gen(function* () { | { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null } | { readonly _tag: "Worktree"; + readonly gitDir: string; readonly mainCheckout: string | null; readonly git: AgentSessionProjectGit | null; } | { readonly _tag: "NotGit" }; const identities = new Map(); - const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = []; + const repositories: Array<{ + directory: string; + gitDir: string; + worktreeGitDir: string | null; + }> = []; const pointers: Array<{ directory: string; gitPath: string }> = []; for (const directory of directories) { const gitPath = path.join(directory, ".git"); const gitStats = yield* statOption(gitPath); if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" }); else if (gitStats.value.type === "Directory") { - repositories.push({ directory, gitDir: gitPath, linkedWorktree: false }); + repositories.push({ directory, gitDir: gitPath, worktreeGitDir: null }); } else pointers.push({ directory, gitPath }); } @@ -972,7 +1013,7 @@ export const make = Effect.gen(function* () { const gitDir = path.resolve(directory, target); if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) { linkedWorktrees.push({ directory, gitDir }); - } else repositories.push({ directory, gitDir, linkedWorktree: false }); + } else repositories.push({ directory, gitDir, worktreeGitDir: null }); } const commonDirTexts = yield* readGitFiles( @@ -981,19 +1022,19 @@ export const make = Effect.gen(function* () { for (const { directory, gitDir } of linkedWorktrees) { const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim(); if (commonDir.length === 0) { - identities.set(directory, { _tag: "Worktree", mainCheckout: null, git: null }); + identities.set(directory, { _tag: "Worktree", gitDir, mainCheckout: null, git: null }); } else repositories.push({ directory, gitDir: path.resolve(gitDir, commonDir), - linkedWorktree: true, + worktreeGitDir: gitDir, }); } const configTexts = yield* readGitFiles( repositories.map(({ gitDir }) => path.join(gitDir, "config")), ); - for (const { directory, gitDir, linkedWorktree } of repositories) { + for (const { directory, gitDir, worktreeGitDir } of repositories) { const configText = configTexts.get(path.join(gitDir, "config")) ?? ""; const originUrl = parseOriginUrlFromGitConfig(configText); const git: AgentSessionProjectGit = { @@ -1002,9 +1043,10 @@ export const make = Effect.gen(function* () { repository: repositoryPathFromRemoteUrl(originUrl), }; // Bare repositories have no main checkout, so offer their linked worktrees independently. - if (linkedWorktree && !isBareGitConfig(configText)) { + if (worktreeGitDir !== null && !isBareGitConfig(configText)) { identities.set(directory, { _tag: "Worktree", + gitDir: worktreeGitDir, // Only a common dir named .git sits inside its main checkout, and an // unreadable config can't rule out a bare repository. mainCheckout: @@ -1018,6 +1060,61 @@ export const make = Effect.gen(function* () { return identities; }); + /** Maps each directory to the project it counts toward: a linked worktree counts toward its main checkout. */ + const resolveDirectoryProjects = Effect.fn("AgentSessionScanner.resolveDirectoryProjects")( + function* (resolvedDirectories: ReadonlyArray) { + // Stat every directory first so one batch reads all git identities. + const directories = new Map>(); + for (const resolved of resolvedDirectories) { + if (directories.has(resolved)) continue; + directories.set(resolved, yield* projectDirectoryStats(resolved)); + } + const directoryGitIdentities = yield* readGitIdentities( + Array.from(directories).flatMap(([directory, stats]) => + Option.isSome(stats) ? [directory] : [], + ), + ); + const projects = new Map< + string, + { + readonly key: string; + readonly path: string; + readonly git: AgentSessionProjectGit | null; + readonly worktreeGitDir: string | null; + } | null + >(); + for (const [resolved, stats] of directories) { + const gitIdentity = directoryGitIdentities.get(resolved); + if (Option.isNone(stats) || gitIdentity === undefined) { + projects.set(resolved, null); + } else if (gitIdentity._tag === "Worktree") { + const { mainCheckout } = gitIdentity; + const mainStats = + mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout); + projects.set( + resolved, + mainCheckout !== null && Option.isSome(mainStats) + ? { + key: yield* directoryIdentity(mainCheckout, mainStats.value), + path: mainCheckout, + git: gitIdentity.git, + worktreeGitDir: gitIdentity.gitDir, + } + : null, + ); + } else { + projects.set(resolved, { + key: yield* directoryIdentity(resolved, stats.value), + path: resolved, + git: gitIdentity._tag === "Repository" ? gitIdentity.git : null, + worktreeGitDir: null, + }); + } + } + return projects; + }, + ); + const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* ( source: AgentSessionSource, transcript: TranscriptCandidate, @@ -1037,11 +1134,15 @@ export const make = Effect.gen(function* () { fileSystem.open(transcript.filePath, { flag: "r" }).pipe( Effect.flatMap((file) => Effect.gen(function* () { + const readChunk = yield* transcriptChunkReader(file, transcript.filePath); + const size = isCompressedTranscript(transcript.filePath) + ? Number.POSITIVE_INFINITY + : transcript.identity.size; const decoder = new TextDecoder(); let remaining = ""; let bytesRead = 0; let recordsRead = 0; - const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, transcript.identity.size); + const maxBytes = Math.min(MAX_TRANSCRIPT_SCAN_BYTES, size); const reserveRecord = () => { if ( recordsRead === MAX_METADATA_RECORDS_PER_TRANSCRIPT || @@ -1073,7 +1174,7 @@ export const make = Effect.gen(function* () { ); budget.operationsRemaining -= 1; budget.bytesRemaining -= readSize; - const next = yield* file.readAlloc(readSize); + const next = yield* readChunk(readSize); if (Option.isNone(next)) { return readLastRecord(); } @@ -1090,7 +1191,7 @@ export const make = Effect.gen(function* () { } } - if (bytesRead < transcript.identity.size) { + if (bytesRead < size) { budget.truncated = true; return null; } @@ -1107,8 +1208,12 @@ export const make = Effect.gen(function* () { source: AgentSessionSource, prefix?: { readonly endByteOffset: number; readonly historyBytes: number }, ) { - const readBytes = prefix?.endByteOffset ?? expected.size; - if (readBytes > expected.size || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) return null; + const compressed = isCompressedTranscript(filePath); + const readBytes = + prefix?.endByteOffset ?? (compressed ? MAX_IMPORTED_TRANSCRIPT_BYTES : expected.size); + if ((!compressed && readBytes > expected.size) || readBytes > MAX_IMPORTED_TRANSCRIPT_BYTES) { + return null; + } return yield* Effect.scoped( fileSystem.open(filePath, { flag: "r" }).pipe( @@ -1117,6 +1222,7 @@ export const make = Effect.gen(function* () { if (!sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))) { return null; } + const readChunk = yield* transcriptChunkReader(file, filePath); const records: Array = []; const claudeHistory = createClaudeHistoryWindow(); let cwd = Option.none(); @@ -1177,10 +1283,12 @@ export const make = Effect.gen(function* () { }; while (bytesRead < readBytes) { - const next = yield* file.readAlloc( + const next = yield* readChunk( Math.min(TRANSCRIPT_PREFIX_BYTES, readBytes - bytesRead), ); if (Option.isNone(next)) { + // A compressed rollout's decompressed length is only known at its end. + if (compressed && prefix === undefined) break; return null; } @@ -1398,7 +1506,12 @@ export const make = Effect.gen(function* () { } const directory = path.join(sessionsDir, year, month, day); for (const entry of (yield* readDirectory(directory)).toSorted().toReversed()) { - if (!entry.startsWith("rollout-") || !entry.endsWith(".jsonl")) continue; + if ( + !entry.startsWith("rollout-") || + !(entry.endsWith(".jsonl") || isCompressedTranscript(entry)) + ) { + continue; + } if (operationsRemaining <= 0) { truncated = true; break; @@ -1719,64 +1832,18 @@ export const make = Effect.gen(function* () { git: AgentSessionProjectGit | null; } >(); - // Resolve every candidate directory first so one batch reads all git identities. - const directories = new Map>(); - for (const candidate of raw) { - const expanded = expandHomePath(candidate.cwd.trim(), homeDir); - if (!path.isAbsolute(expanded)) continue; - const resolved = path.resolve(expanded); - if (directories.has(resolved)) continue; - directories.set(resolved, yield* projectDirectoryStats(resolved)); - } - const directoryGitIdentities = yield* readGitIdentities( - Array.from(directories).flatMap(([directory, stats]) => - Option.isSome(stats) ? [directory] : [], - ), + const directoryProjects = yield* resolveDirectoryProjects( + raw.flatMap((candidate) => { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + return path.isAbsolute(expanded) ? [path.resolve(expanded)] : []; + }), ); - const directoryProjects = new Map< - string, - { - readonly key: string; - readonly path: string; - readonly git: AgentSessionProjectGit | null; - } | null - >(); - for (const candidate of raw) { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; - const resolved = path.resolve(expanded); - const stats = directories.get(resolved); - if (stats === undefined || Option.isNone(stats)) continue; - let project = directoryProjects.get(resolved); - if (project === undefined) { - const gitIdentity = directoryGitIdentities.get(resolved); - if (gitIdentity === undefined) { - project = null; - } else if (gitIdentity._tag === "Worktree") { - // A linked worktree's sessions count toward its main checkout's project. - const { mainCheckout } = gitIdentity; - const mainStats = - mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout); - project = - mainCheckout !== null && Option.isSome(mainStats) - ? { - key: yield* directoryIdentity(mainCheckout, mainStats.value), - path: mainCheckout, - git: gitIdentity.git, - } - : null; - } else { - project = { - key: yield* directoryIdentity(resolved, stats.value), - path: resolved, - git: gitIdentity._tag === "Repository" ? gitIdentity.git : null, - }; - } - directoryProjects.set(resolved, project); - } - if (project === null) continue; + const project = directoryProjects.get(path.resolve(expanded)); + if (project === undefined || project === null) continue; const existing = merged.get(project.key); if (!existing) { @@ -1866,6 +1933,45 @@ export const make = Effect.gen(function* () { } const { candidates } = cachedCandidates; + // The scan counts a linked worktree's sessions toward its main checkout, so import them with it. + const candidateDirectories = candidates.flatMap((candidate) => { + const expanded = expandHomePath(candidate.cwd.trim(), homeDir); + return path.isAbsolute(expanded) ? [path.resolve(expanded)] : []; + }); + const directoryProjects = yield* resolveDirectoryProjects(candidateDirectories); + const belongsToRoot = Effect.fn("AgentSessionScanner.belongsToRoot")(function* ( + resolved: string, + ) { + if ((yield* directoryIdentity(resolved)) === rootIdentity) return true; + if (!directoryProjects.has(resolved)) { + const project = (yield* resolveDirectoryProjects([resolved])).get(resolved) ?? null; + directoryProjects.set(resolved, project); + } + return directoryProjects.get(resolved)?.key === rootIdentity; + }); + const worktreesByDirectory = new Map(); + const rootWorktree = Effect.fn("AgentSessionScanner.rootWorktree")(function* ( + resolved: string, + ) { + const known = worktreesByDirectory.get(resolved); + if (known !== undefined) return known; + const gitDir = + (yield* directoryIdentity(resolved)) === rootIdentity + ? null + : (directoryProjects.get(resolved)?.worktreeGitDir ?? null); + let worktree: { path: string; branch: string | null } | null = null; + if (gitDir !== null) { + const headPath = path.join(gitDir, "HEAD"); + const head = (yield* readGitFiles([headPath])).get(headPath) ?? ""; + worktree = { + path: resolved, + branch: /^ref: refs\/heads\/(.+)$/.exec(head.trim())?.[1] ?? null, + }; + } + worktreesByDirectory.set(resolved, worktree); + return worktree; + }); + const eligibleTranscripts: Array<{ readonly candidate: RawCandidate; readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number }; @@ -1874,7 +1980,7 @@ export const make = Effect.gen(function* () { const expanded = expandHomePath(candidate.cwd.trim(), homeDir); if (!path.isAbsolute(expanded)) continue; const resolved = path.resolve(expanded); - if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue; + if (!(yield* belongsToRoot(resolved))) continue; for (const transcript of candidate.transcripts) { if ( @@ -2005,12 +2111,10 @@ export const make = Effect.gen(function* () { projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), homeDir, ); - if ( - !path.isAbsolute(expandedCwd) || - (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity - ) { + if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) { return Option.some({ _tag: "Skipped" }); } + const worktree = yield* rootWorktree(path.resolve(expandedCwd)); const inheritedRecords = candidate.source === "codex" @@ -2024,7 +2128,12 @@ export const make = Effect.gen(function* () { { source: candidate.source, providerInstanceId: candidate.providerInstanceId, - fallbackSessionId: path.basename(transcript.filePath, ".jsonl"), + fallbackSessionId: path.basename( + transcript.filePath, + isCompressedTranscript(transcript.filePath) + ? COMPRESSED_TRANSCRIPT_SUFFIX + : ".jsonl", + ), lastActiveAtMs: transcript.mtimeMs, }, inheritedRecords === null @@ -2061,6 +2170,7 @@ export const make = Effect.gen(function* () { thread: savedTitle === undefined ? parsedThread : { ...parsedThread, title: savedTitle }, source, + worktree, }); }).pipe(importReadLock.withPermits(1)), ), diff --git a/apps/server/src/project/ManagedProjectFolders.ts b/apps/server/src/project/ManagedProjectFolders.ts index 27316997077b1..007f784374c15 100644 --- a/apps/server/src/project/ManagedProjectFolders.ts +++ b/apps/server/src/project/ManagedProjectFolders.ts @@ -66,6 +66,10 @@ export class ScratchProjectError extends Schema.TaggedError } } +/** Where No project threads keep their folders, whether or not this T3 home allows them. */ +export const scratchFolderRoot = (baseDir: string, path: Path.Path) => + path.resolve(baseDir, "scratch"); + export type ScratchError = ScratchUnavailableError | ScratchFolderError | ScratchProjectError; // The spawner checks cwd before spawning, so NotFound from spawn itself means a missing executable. @@ -255,7 +259,7 @@ const make = Effect.gen(function* () { Effect.flatMap( (repositoryRoot): Effect.Effect> => { if (repositoryRoot === null) { - return Effect.succeed(Result.succeed(path.resolve(config.baseDir, "scratch"))); + return Effect.succeed(Result.succeed(scratchFolderRoot(config.baseDir, path))); } const unavailable = new ScratchUnavailableError({ baseDir: config.baseDir, diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index 9a2e36b43bc2e..492379beecc26 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -31,6 +31,7 @@ import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as RuntimeLayer from "../orchestration-v2/runtimeLayer.ts"; import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ProcessRunner from "../processRunner.ts"; import * as ServerSettings from "../serverSettings.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; @@ -783,6 +784,69 @@ it.effect("resolves a restored icon immediately after reselecting its saved path }).pipe(Effect.provide(NodeServices.layer)), ); +it.effect("refuses a worktree container as a new project and as a new workspace root", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const processRunner = yield* ProcessRunner.ProcessRunner; + const fixture = yield* fileSystem.makeTempDirectoryScoped({ prefix: "project-container-" }); + const git = (cwd: string, ...args: ReadonlyArray) => + processRunner.run({ + command: "git", + args: ["-C", cwd, "-c", "user.email=t@t", "-c", "user.name=t", ...args], + }); + const source = `${fixture}/source`; + const container = `${fixture}/container`; + yield* fileSystem.makeDirectory(source); + yield* fileSystem.makeDirectory(container); + yield* git(source, "init", "-b", "develop"); + yield* fileSystem.writeFileString(`${source}/README.md`, "readme\n"); + yield* git(source, "add", "README.md"); + yield* git(source, "commit", "-m", "init"); + yield* git(fixture, "clone", "--bare", source, `${container}/.bare`); + yield* fileSystem.writeFileString(`${container}/.git`, "gitdir: ./.bare\n"); + yield* git(container, "worktree", "add", "develop", "develop"); + + yield* Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + // As cloned the container is bare; Initialize Git or a config edit clears core.bare. + for (const coreBare of ["true", "false"]) { + yield* git(container, "config", "core.bare", coreBare); + const rejected = yield* service + .create({ + commandId: CommandId.make(`command:container:create:${coreBare}`), + projectId: ProjectId.make(`project:container:${coreBare}`), + title: "Container", + workspaceRoot: container, + }) + .pipe(Effect.flip); + assert.equal(rejected._tag, "ProjectInvalidError", `core.bare=${coreBare}`); + assert.include(rejected.message, "Add one of its worktrees"); + assert.isTrue(Option.isNone(yield* service.getByWorkspaceRoot(container))); + } + + const projectId = ProjectId.make("project:container:worktree"); + const worktree = yield* service.create({ + commandId: CommandId.make("command:container:worktree"), + projectId, + title: "Worktree", + workspaceRoot: `${container}/develop`, + }); + const moved = yield* service + .update({ + commandId: CommandId.make("command:container:move"), + projectId, + workspaceRoot: container, + }) + .pipe(Effect.flip); + assert.equal(moved._tag, "ProjectInvalidError"); + assert.equal( + Option.getOrThrow(yield* service.getById(projectId)).workspaceRoot, + worktree.workspaceRoot, + ); + }).pipe(Effect.provide(layerTest)); + }).pipe(Effect.provide(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))), +); + it.effect("serializes two projects claiming the same workspace root", () => Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 464454ebba763..d6bc3e8eedf4d 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -34,7 +34,9 @@ import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecuto import { planThreadDeletion } from "../orchestration-v2/ThreadDeletion.ts"; import * as ServerSettings from "../serverSettings.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; +import * as ProcessRunner from "../processRunner.ts"; import * as ProjectEnrichmentService from "./ProjectEnrichmentService.ts"; +import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; export interface ProjectCreateInput extends ProjectCreatePayload { @@ -182,6 +184,9 @@ export const make = Effect.gen(function* () { const serverSettings = yield* ServerSettings.ServerSettingsService; const fileSystem = yield* FileSystem.FileSystem; const isManagedWorktreePath = yield* makeIsManagedWorktreePath; + const isWorktreeContainer = yield* makeIsWorktreeContainer.pipe( + Effect.provide(ProcessRunner.layer), + ); const projectLocks = yield* KeyedLock.make(); const workspaceLocks = yield* KeyedLock.make(); @@ -244,6 +249,17 @@ export const make = Effect.gen(function* () { ), ); + const rejectWorktreeContainer = Effect.fn("ProjectService.rejectWorktreeContainer")(function* ( + projectId: ProjectId, + workspaceRoot: string, + ) { + if (!(yield* isWorktreeContainer(workspaceRoot))) return; + return yield* new ProjectInvalidError({ + projectId, + detail: `${workspaceRoot} holds a repository's worktrees but is not a checkout itself. Add one of its worktrees as the project instead.`, + }); + }); + const commit = Effect.fn("ProjectService.commit")(function* (command: ProjectCommand) { const { projectId } = command; const dispatchError = (cause: unknown) => @@ -383,6 +399,7 @@ export const make = Effect.gen(function* () { workspaceRoot: input.workspaceRoot, createIfMissing: input.createWorkspaceRootIfMissing ?? false, }); + yield* rejectWorktreeContainer(input.projectId, workspaceRoot); yield* commit({ type: "project.create", commandId: input.commandId, @@ -410,6 +427,9 @@ export const make = Effect.gen(function* () { projectId: input.projectId, workspaceRoot: input.workspaceRoot, }); + if (workspaceRoot !== previousRoot) { + yield* rejectWorktreeContainer(input.projectId, workspaceRoot); + } yield* commit({ type: "project.meta.update", commandId: input.commandId, diff --git a/apps/server/src/project/worktreeContainer.test.ts b/apps/server/src/project/worktreeContainer.test.ts new file mode 100644 index 0000000000000..b10f8db93dab3 --- /dev/null +++ b/apps/server/src/project/worktreeContainer.test.ts @@ -0,0 +1,94 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; + +import * as ProcessRunner from "../processRunner.ts"; +import { makeIsWorktreeContainer } from "./worktreeContainer.ts"; + +const git = Effect.fn("worktreeContainerTest.git")(function* ( + cwd: string, + ...args: ReadonlyArray +) { + const processRunner = yield* ProcessRunner.ProcessRunner; + return yield* processRunner.run({ + command: "git", + args: ["-C", cwd, "-c", "user.email=t@t", "-c", "user.name=t", ...args], + }); +}); + +it.layer(ProcessRunner.layer.pipe(Layer.provideMerge(NodeServices.layer)))( + "isWorktreeContainer", + (it) => { + it.effect("is true only for a folder of worktrees around metadata that is no checkout", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const isWorktreeContainer = yield* makeIsWorktreeContainer; + const fixture = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-container-test-" }); + + const source = path.join(fixture, "source"); + yield* fileSystem.makeDirectory(source); + yield* git(source, "init", "-b", "develop"); + yield* fileSystem.writeFileString(path.join(source, "README.md"), "readme\n"); + yield* git(source, "add", "README.md"); + yield* git(source, "commit", "-m", "init"); + + const makeContainer = Effect.fn(function* (name: string, coreBare: boolean) { + const root = path.join(fixture, name); + yield* fileSystem.makeDirectory(root); + yield* git(fixture, "clone", "--bare", source, path.join(root, ".bare")); + yield* fileSystem.writeFileString(path.join(root, ".git"), "gitdir: ./.bare\n"); + yield* git(root, "worktree", "add", "develop", "develop"); + yield* git(root, "config", "core.bare", String(coreBare)); + return root; + }); + const makeSeparateGitDirCheckout = Effect.fn(function* (name: string) { + const root = path.join(fixture, name); + yield* fileSystem.makeDirectory(root); + yield* git(root, "init", "-b", "develop", "--separate-git-dir", ".metadata", "."); + return root; + }); + + const container = yield* makeContainer("container", false); + assert.isTrue(yield* isWorktreeContainer(container), "container"); + assert.isFalse(yield* isWorktreeContainer(path.join(container, "develop")), "its worktree"); + + const linked = path.join(fixture, "link"); + yield* fileSystem.symlink(container, linked); + assert.isTrue(yield* isWorktreeContainer(linked), "container through a symlink"); + + // The issue's steps leave core.bare set; Initialize Git would clear it later. + const bare = yield* makeContainer("bare", true); + assert.isTrue(yield* isWorktreeContainer(bare), "core.bare container"); + + // Git allows an orphan worktree before the first commit: no index, yet a valid checkout. + const fresh = yield* makeSeparateGitDirCheckout("fresh"); + yield* git(fresh, "worktree", "add", "--orphan", "-b", "feature", "../fresh-feature"); + assert.isFalse(yield* isWorktreeContainer(fresh), "fresh checkout with an orphan worktree"); + + const checkout = yield* makeSeparateGitDirCheckout("checkout"); + yield* fileSystem.writeFileString(path.join(checkout, "README.md"), "readme\n"); + yield* git(checkout, "add", "README.md"); + yield* git(checkout, "commit", "-m", "init"); + yield* git(checkout, "worktree", "add", "worktrees/feature", "-b", "feature"); + assert.isFalse(yield* isWorktreeContainer(checkout), "checkout with a nested worktree"); + + const outside = path.join(fixture, "outside"); + yield* git( + fixture, + "clone", + "--no-checkout", + "--separate-git-dir", + path.join(outside, ".metadata"), + source, + outside, + ); + yield* git(outside, "worktree", "add", "../outside-feature", "-b", "feature"); + assert.isFalse(yield* isWorktreeContainer(outside), "worktrees outside the folder"); + }), + ); + }, +); diff --git a/apps/server/src/project/worktreeContainer.ts b/apps/server/src/project/worktreeContainer.ts new file mode 100644 index 0000000000000..f20e9c4375cae --- /dev/null +++ b/apps/server/src/project/worktreeContainer.ts @@ -0,0 +1,95 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import * as ProcessRunner from "../processRunner.ts"; +import { explicitBareRepositoryEnv, unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; + +const parseGitfileTarget = (contents: string): string | undefined => { + const firstLine = contents.split(/\r?\n/u, 1)[0] ?? ""; + if (!firstLine.startsWith("gitdir:")) return undefined; + const target = firstLine.slice("gitdir:".length).trim(); + return target === "" ? undefined : target; +}; + +const splitNul = (stdout: string) => stdout.split("\0").filter((entry) => entry !== ""); + +/** + * Whether a folder only holds a repository's metadata and worktrees: its `.git` file points at + * metadata inside it, a linked worktree lives inside it, and either the repository is bare or it + * has commits but no index. A checkout whose tracked files are all deleted keeps its index, and a + * fresh one has no commit. Anything this cannot establish answers false. + */ +export const makeIsWorktreeContainer = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const processRunner = yield* ProcessRunner.ProcessRunner; + const platform = yield* HostProcess.Platform; + const env = { + ...unsetInheritedRepositoryEnv(process.env, platform), + ...explicitBareRepositoryEnv(process.env, platform), + }; + + const realPath = (target: string) => fileSystem.realPath(target).pipe(Effect.option); + const isInside = (parent: string, child: string) => { + const relative = path.relative(parent, child); + return ( + relative !== "" && + relative !== ".." && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative) + ); + }; + + return Effect.fn("ProjectService.isWorktreeContainer")(function* (workspaceRoot: string) { + // A `.git` directory is an ordinary checkout, so only a gitfile costs any Git process. + const gitfileTarget = yield* fileSystem.readFileString(path.join(workspaceRoot, ".git")).pipe( + Effect.map(parseGitfileTarget), + Effect.orElseSucceed(() => undefined), + ); + if (gitfileTarget === undefined) return false; + const root = yield* realPath(workspaceRoot); + const gitDir = yield* realPath(path.resolve(workspaceRoot, gitfileTarget)); + if (root._tag === "None" || gitDir._tag === "None") return false; + if (!isInside(root.value, gitDir.value)) return false; + + const git = (args: ReadonlyArray) => + processRunner + .run({ + command: "git", + args: ["-C", workspaceRoot, ...args], + env, + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.map((result) => (result.code === 0 && !result.timedOut ? result.stdout : null)), + Effect.orElseSucceed(() => null), + ); + + // Initializing Git in a bare container clears core.bare, so it is refused while still bare. + const isBare = yield* git(["rev-parse", "--is-bare-repository"]); + if (isBare === null) return false; + if (isBare.trim() !== "true") { + const hasCommit = yield* git(["rev-parse", "--quiet", "--verify", "HEAD^{commit}"]); + if (hasCommit === null) return false; + const hasIndex = yield* fileSystem + .exists(path.join(gitDir.value, "index")) + .pipe(Effect.orElseSucceed(() => true)); + if (hasIndex) return false; + } + + const worktrees = yield* git(["worktree", "list", "--porcelain", "-z"]); + if (worktrees === null) return false; + // The first entry is the main worktree, which Git reports as the metadata directory here. + const linkedWorktreePaths = splitNul(worktrees) + .filter((field) => field.startsWith("worktree ")) + .slice(1) + .map((field) => field.slice("worktree ".length)); + for (const worktreePath of linkedWorktreePaths) { + const worktree = yield* realPath(worktreePath); + if (worktree._tag === "Some" && isInside(root.value, worktree.value)) return true; + } + return false; + }); +}); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 7e380189ee6cd..5f4cb5ed4b8ed 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -116,13 +116,16 @@ const layerAdvertisedTools = McpHttpServer.layerTools.pipe( ); // Claude Code loads these tools up front instead of behind ToolSearch, outside this budget. -it.effect("only request_secret asks Claude Code to load it up front", () => +it.effect("only request_secret and send_to_user ask Claude Code to load them up front", () => Effect.gen(function* () { const mcp = yield* McpServer.McpServer; const alwaysLoad = mcp.tools .filter(({ tool }) => tool._meta?.["anthropic/alwaysLoad"] !== undefined) .map(({ tool }) => [tool.name, tool._meta]); - expect(alwaysLoad).toEqual([["request_secret", { "anthropic/alwaysLoad": true }]]); + expect(alwaysLoad).toEqual([ + ["request_secret", { "anthropic/alwaysLoad": true }], + ["send_to_user", { "anthropic/alwaysLoad": true }], + ]); }).pipe(Effect.provide(layerAdvertisedTools)), ); diff --git a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts index bf3c9318877bb..e2622bc9c2a65 100644 --- a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts +++ b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts @@ -14,10 +14,13 @@ import { buildClaudeCapabilitiesProbeQueryOptions, probeClaudeCapabilities, probeClaudeWorkspaceSnapshot, + spawnClaudeProbeThroughEnv, } from "./ClaudeProvider.ts"; vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true }); +const hostPath = process.env.PATH; + const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings); it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => { @@ -27,6 +30,7 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp environment: { HOME: "/home/user" }, cwd: undefined, managedMcpConfig: true, + spawnThroughEnv: false, }); // Claude exits before initializing when handed --strict-mcp-config here. @@ -35,6 +39,29 @@ it("drops strict MCP mode, and only that, next to an administrator's managed-mcp assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false"); }); +// A shell trampoline would not do: dash drops the exported function, and the launcher exits 127. +it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "starts a Bash launcher that calls an exported function in the probe's workspace", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.realPath(yield* fileSystem.makeTempDirectoryScoped()); + yield* fileSystem.writeFileString(`${workspace}/claude`, '#!/bin/bash\nt3_launch "$@"\n'); + yield* fileSystem.chmod(`${workspace}/claude`, 0o755); + const child = spawnClaudeProbeThroughEnv({ + command: "claude", + args: ["--probe"], + cwd: workspace, + env: { PATH: `.:${hostPath}`, "BASH_FUNC_t3_launch%%": '() { echo "$PWD $@"; }' }, + // @effect-diagnostics-next-line abortControllerInEffect:off - The launcher exits on its own. + signal: new AbortController().signal, + }); + assert.deepEqual(child.spawnargs.slice(0, 3), ["/usr/bin/env", "-C", workspace]); + const output = yield* Effect.promise(() => child.stdout.setEncoding("utf8").toArray()); + assert.equal(output.join(""), `${workspace} --probe\n`); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect("reports a deleted worktree's scan as finished, not pending", () => Effect.gen(function* () { const snapshot = yield* probeClaudeWorkspaceSnapshot( diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 1fcba1c388db6..d5ebcc31220c5 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -1,3 +1,6 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- the SDK's spawn hook returns a Node child process. +import * as NodeChildProcess from "node:child_process"; + import { resolveProviderProbeTimeoutMs } from "@t3tools/provider-core/server/snapshotProbe"; import { type ClaudeSettings, @@ -17,6 +20,8 @@ import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { createModelCapabilities } from "@t3tools/shared/model"; +import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { query as claudeQuery, @@ -26,6 +31,7 @@ import { type SDKControlGetUsageResponse, type SDKUserMessage, type SettingSource, + type SpawnOptions as ClaudeSpawnOptions, } from "@anthropic-ai/claude-agent-sdk"; import { @@ -231,7 +237,28 @@ const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [ "local", ] as const satisfies ReadonlyArray; -/** Build the exact SDK options used by the periodic Claude capability probe. */ +/** + * The SDK's own spawn stats the executable and hands libuv the workspace as cwd, so a mount + * that stops answering freezes the server. `env` enters the cwd and finds the CLI in the child. + * A shell would not do: dash drops the exported Bash functions a launcher may call. + */ +export function spawnClaudeProbeThroughEnv({ + command, + args, + cwd, + env, + signal, +}: ClaudeSpawnOptions) { + const launch = envTrampoline(command, args, cwd) ?? { command, args, cwd }; + return NodeChildProcess.spawn(launch.command, launch.args, { + ...("cwd" in launch ? { cwd: launch.cwd } : {}), + env, + signal, + // The probe ignores stderr. + stdio: ["pipe", "pipe", "ignore"], + }); +} + export function buildClaudeCapabilitiesProbeQueryOptions(input: { readonly executablePath: string; readonly abortController: AbortController; @@ -239,8 +266,10 @@ export function buildClaudeCapabilitiesProbeQueryOptions(input: { readonly cwd: string | undefined; /** An administrator's `managed-mcp.json` is installed; see `hasClaudeManagedMcpConfig`. */ readonly managedMcpConfig: boolean; + readonly spawnThroughEnv: boolean; }): ClaudeQueryOptions { return { + ...(input.spawnThroughEnv ? { spawnClaudeCodeProcess: spawnClaudeProbeThroughEnv } : {}), persistSession: false, pathToClaudeCodeExecutable: input.executablePath, abortController: input.abortController, @@ -475,6 +504,8 @@ const probeClaudeCapabilities = ( ...(yield* readClaudeSettingsEnv(claudeSettings, cwd, claudeEnvironment)), }) : 0; + const spawnThroughEnv = + (yield* HostProcess.Platform) === "linux" && (yield* Effect.promise(supportsEnvChdir)); return yield* Effect.tryPromise({ try: async () => { const q = claudeQuery({ @@ -488,6 +519,7 @@ const probeClaudeCapabilities = ( environment: claudeEnvironment, cwd, managedMcpConfig, + spawnThroughEnv, }), }); const init = await q.initializationResult(); @@ -791,6 +823,7 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( (yield* readClaudeSettingsEnv(claudeSettings, cwd, resolvedEnvironment)).ANTHROPIC_BASE_URL ?? resolvedEnvironment.ANTHROPIC_BASE_URL; const customApiEndpoint = customClaudeApiEndpointHost(baseUrl) !== undefined; + const endpoint = customApiEndpoint ? URL.parse(baseUrl?.trim() ?? "")?.origin : undefined; if (!customApiEndpoint && claudeAuthStatus(capabilities) === "unauthenticated") { const path = yield* Path.Path; const configDir = (yield* makeClaudeEnvironment(claudeSettings, resolvedEnvironment)) @@ -819,7 +852,9 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( // A proxy's ANTHROPIC_AUTH_TOKEN reads as an API key; the endpoint is what the token is for. const authMetadata = apiProviderAuthMetadata(capabilities.apiProvider) ?? - (customApiEndpoint ? { type: "customEndpoint", label: "Custom API endpoint" } : undefined) ?? + (customApiEndpoint + ? { type: "customEndpoint", label: "Custom API endpoint", ...(endpoint ? { endpoint } : {}) } + : undefined) ?? claudeAuthMetadata({ subscriptionType: capabilities.subscriptionType, authMethod: capabilities.tokenSource, diff --git a/apps/server/src/provider/CodexProvider.test.ts b/apps/server/src/provider/CodexProvider.test.ts index 7eadf550eab28..ad15bf0896eb2 100644 --- a/apps/server/src/provider/CodexProvider.test.ts +++ b/apps/server/src/provider/CodexProvider.test.ts @@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest"; import { applyPreferredCodexDefaultModel, + codexCustomEndpoint, codexRoutesSpendNativeQuota, mapCodexModelCapabilities, } from "./CodexProvider.ts"; @@ -192,4 +193,12 @@ it("reports native quota only for an OpenAI login on a native route", () => { name, ); } + // The custom endpoint is what a usage-limit hub is matched against. + assert.strictEqual(codexCustomEndpoint(hub), "https://hub.example.com"); + assert.strictEqual( + codexCustomEndpoint({ openai_base_url: "http://127.0.0.1:8317/v1" }), + "http://127.0.0.1:8317", + ); + assert.strictEqual(codexCustomEndpoint({ openai_base_url: "https://chatgpt.com/x" }), undefined); + assert.strictEqual(codexCustomEndpoint({}), undefined); }); diff --git a/apps/server/src/provider/CodexProvider.ts b/apps/server/src/provider/CodexProvider.ts index ab2cda61e53ee..df105d3ba20fe 100644 --- a/apps/server/src/provider/CodexProvider.ts +++ b/apps/server/src/provider/CodexProvider.ts @@ -57,7 +57,6 @@ import { import * as HostProcess from "@t3tools/shared/HostProcess"; import packageJson from "../../package.json" with { type: "json" }; const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError); -const RATE_LIMITS_PROBE_TIMEOUT_MS = 3_000; type CodexRateLimitsProbe = | { @@ -95,17 +94,21 @@ const CodexCyberAccessConfig = Schema.Struct({ }); const decodeCodexCyberAccessConfig = Schema.decodeUnknownOption(CodexCyberAccessConfig); -function routesToNativeOpenai(config: unknown): boolean { +// Null is Codex's auth-dependent OpenAI default; undefined is a route that cannot be read. +function codexRouteBaseUrl(config: unknown): string | null | undefined { const decoded = decodeCodexRoutingConfig(config); - if (Option.isNone(decoded)) return false; + if (Option.isNone(decoded)) return undefined; const routing = decoded.value; const providerId = routing.model_provider ?? "openai"; + if (providerId === "openai") return routing.openai_base_url || null; const provider = routing.model_providers?.[providerId]; - if (providerId !== "openai" && !provider) return false; - const baseUrl = - providerId === "openai" ? routing.openai_base_url || undefined : provider?.base_url; - // A provider without an override uses Codex's auth-dependent OpenAI default. - if (baseUrl == null) return true; + return provider ? (provider.base_url ?? null) : undefined; +} + +function routesToNativeOpenai(config: unknown): boolean { + const baseUrl = codexRouteBaseUrl(config); + if (baseUrl === undefined) return false; + if (baseUrl === null) return true; if (!URL.canParse(baseUrl)) return false; const url = new URL(baseUrl); return ( @@ -114,6 +117,15 @@ function routesToNativeOpenai(config: unknown): boolean { ); } +/** The origin of the custom endpoint Codex sends model requests to, if it uses one. */ +export function codexCustomEndpoint(config: unknown): string | undefined { + const baseUrl = codexRouteBaseUrl(config); + const url = baseUrl ? URL.parse(baseUrl) : null; + return url && /^https?:$/.test(url.protocol) && !routesToNativeOpenai(config) + ? url.origin + : undefined; +} + // A stored login does not mean this provider's traffic spends that login's quota. export const codexRoutesSpendNativeQuota = ( account: CodexSchema.V2GetAccountResponse, @@ -141,6 +153,7 @@ const CODEX_PRESENTATION = { export interface CodexAppServerProviderSnapshot { readonly account: CodexSchema.V2GetAccountResponse; + readonly endpoint?: string | undefined; readonly nativeUsage?: boolean; readonly rateLimits?: CodexRateLimitsProbe; readonly version: string | undefined; @@ -670,11 +683,7 @@ const readCodexRateLimits = ( client: CodexClient.CodexAppServerClient["Service"], deadlineMs: number, ) => - withCodexDiscoveryDeadline( - client.request("account/rateLimits/read", null), - deadlineMs, - RATE_LIMITS_PROBE_TIMEOUT_MS, - ).pipe( + withCodexDiscoveryDeadline(client.request("account/rateLimits/read", null), deadlineMs).pipe( Effect.map((response): CodexRateLimitsProbe => response ? { @@ -762,6 +771,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun const cyberAccess = Option.getOrUndefined(decodeCodexCyberAccessConfig(config)); return { account: accountResponse, + endpoint: config ? codexCustomEndpoint(config) : undefined, nativeUsage, ...(rateLimits ? { rateLimits } : {}), version, @@ -1080,7 +1090,9 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu installed: true, version: snapshot.version ?? null, status: snapshot.models === undefined ? "warning" : accountStatus.status, - auth: accountStatus.auth, + auth: snapshot.endpoint + ? { ...accountStatus.auth, endpoint: snapshot.endpoint } + : accountStatus.auth, ...(accountStatus.message ? { message: accountStatus.message } : snapshot.models === undefined diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 5060d8a24e5ed..c81b38a00dbcb 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -273,15 +273,43 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("rejects an oversized skill instead of returning an incomplete catalog", () => + it.effect("does not spend the scan budget on skill bodies", () => Effect.gen(function* () { const path = yield* Path.Path; const input = yield* makeWorkspace(); - const skillPath = yield* writeSkill( - path.join(input.cwd, ".agents", "skills", "oversized"), - `---\nname: oversized\ndescription: Read a large skill.\n---\n${"x".repeat(1_000_000)}`, + const root = path.join(input.userHome, ".gemini", "config", "skills"); + const expected = []; + for (let index = 0; index < 9; index += 1) { + const name = `large-${index}`; + const description = `Large skill ${index}. ${"y".repeat(2_000)}`; + const skillPath = yield* writeSkill( + path.join(root, name), + `---\nname: ${name}\ndescription: ${description}\n---\n${"x".repeat(950_000)}`, + ); + expected.push({ name, description, path: skillPath, scope: "user", enabled: true }); + } + + assert.deepEqual(yield* discoverAntigravitySkills(input), expected); + }), + ); + + it.effect("rejects frontmatter that does not close within the per-skill limit", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const input = yield* makeWorkspace(); + const root = path.join(input.cwd, ".agents", "skills"); + const largeBodyPath = yield* writeSkill( + path.join(root, "large-body"), + `---\nname: large-body\n---\n${"x".repeat(2_000_000)}`, ); + assert.deepEqual(yield* discoverAntigravitySkills(input), [ + { name: "large-body", path: largeBodyPath, scope: "project", enabled: true }, + ]); + const skillPath = yield* writeSkill( + path.join(root, "oversized"), + `---\nname: oversized\ndescription: ${"x".repeat(1_000_000)}\n---\n`, + ); const result = yield* discoverAntigravitySkills(input).pipe(Effect.result); assert.equal(result._tag, "Failure"); if (result._tag === "Failure") { @@ -291,7 +319,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { }), ); - it.effect("bounds the total read size across skills", () => + it.effect("bounds the total frontmatter read size across skills", () => Effect.gen(function* () { const path = yield* Path.Path; const input = yield* makeWorkspace(); @@ -299,7 +327,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { for (let index = 0; index < 9; index += 1) { yield* writeSkill( path.join(root, `large-${index}`), - `---\nname: large-${index}\n---\n${"x".repeat(900_000)}`, + `---\nname: large-${index}\ndescription: ${"x".repeat(900_000)}\n---\n`, ); } diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 19e9d8d293f48..96e1fe61109f4 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -37,6 +37,8 @@ export function antigravityUserSkillDirectories( const MAX_SKILL_BYTES = 1_000_000; const MAX_SCAN_BYTES = 8_000_000; const MAX_SCAN_ENTRIES = 10_000; +// Typical frontmatter fits in one chunk, so most skills cost about this much of the scan budget. +const SKILL_READ_CHUNK_BYTES = 1024; const SkillFrontmatter = Schema.Struct({ name: Schema.optional(Schema.NullOr(Schema.String)), @@ -106,7 +108,29 @@ function skillPathSortKey(entry: string) { ); } -const readSkill = Effect.fn("readAntigravitySkill")(function* ( +const DASH = 0x2d; + +/** Finds the byte offset after the second `---`, as parseSkillFrontmatter's indexOf calls do. */ +function makeFrontmatterEndFinder() { + let bytesSeen = 0; + let dashes = 0; + let markers = 0; + return (chunk: Uint8Array) => { + for (const byte of chunk) { + bytesSeen += 1; + dashes = byte === DASH ? dashes + 1 : 0; + if (dashes === 3) { + dashes = 0; + markers += 1; + if (markers === 2) return bytesSeen; + } + } + return undefined; + }; +} + +/** Reads through the frontmatter only, so skill bodies do not spend the scan budget. */ +const readSkillFrontmatter = Effect.fn("readAntigravitySkill")(function* ( skillPath: string, budget: ScanBudget, ) { @@ -115,26 +139,27 @@ const readSkill = Effect.fn("readAntigravitySkill")(function* ( if (info?.type !== "File") return undefined; const byteLimit = Math.min(MAX_SKILL_BYTES, budget.remainingBytes); - if (info.size > BigInt(byteLimit)) { - return yield* new AntigravitySkillsProbeError({ - reason: "scan-budget-exhausted", - path: skillPath, - }); - } + const findFrontmatterEnd = makeFrontmatterEndFinder(); + let frontmatterEnd: number | undefined; const chunks = yield* readIfPresent( - fileSystem.stream(skillPath, { bytesToRead: byteLimit + 1 }).pipe(Stream.runCollect), + fileSystem + .stream(skillPath, { bytesToRead: byteLimit + 1, chunkSize: SKILL_READ_CHUNK_BYTES }) + .pipe( + Stream.takeUntil((chunk) => (frontmatterEnd = findFrontmatterEnd(chunk)) !== undefined), + Stream.runCollect, + ), skillPath, ); if (chunks === undefined) return undefined; const bytes = Buffer.concat(chunks); - if (bytes.byteLength > byteLimit) { + budget.remainingBytes -= bytes.byteLength; + if ((frontmatterEnd ?? bytes.byteLength) > byteLimit) { return yield* new AntigravitySkillsProbeError({ reason: "scan-budget-exhausted", path: skillPath, }); } - budget.remainingBytes -= bytes.byteLength; - return bytes.toString("utf8"); + return bytes.toString("utf8", 0, frontmatterEnd); }); /** Keep read errors typed so workspace snapshots cannot cache partial results. */ @@ -187,7 +212,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( if (skillFileName !== undefined) { if (!skillFileName.endsWith(".md")) return; const skillPath = path.join(directory, skillFileName); - const contents = yield* readSkill(skillPath, budget); + const contents = yield* readSkillFrontmatter(skillPath, budget); if (contents === undefined) return; const skill = parseSkillFrontmatter(contents, skillFileName); if (!skill || skillsByName.has(skill.name)) return; diff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts index 6ce141eec733e..bdf2ed1cae61a 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts @@ -22,12 +22,14 @@ export interface ClaudeSkillDispatch { export function planClaudeSkillDispatch( prompt: string, skills: ReadonlyMap, + /** Mentions before this offset, such as inline handoff history, stay plain text. */ + mentionsFrom = 0, ): ClaudeSkillDispatch | undefined { const mentions = [...prompt.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => { const name = match[2] ?? ""; const skill = skills.get(name); - if (!skill) return []; const start = (match.index ?? 0) + (match[1]?.length ?? 0); + if (!skill || start < mentionsFrom) return []; return [{ name, skill, start, end: (match.index ?? 0) + match[0].length }]; }); const last = mentions.at(-1); diff --git a/apps/server/src/provider/Drivers/codexUsage.test.ts b/apps/server/src/provider/Drivers/codexUsage.test.ts index cacfc6c06211a..1cdbe05d07669 100644 --- a/apps/server/src/provider/Drivers/codexUsage.test.ts +++ b/apps/server/src/provider/Drivers/codexUsage.test.ts @@ -589,6 +589,98 @@ describe("parseCodexLine", () => { }); }); + const at = (time: string, line: string) => line.replace("05:17:49.919Z", `${time}.000Z`); + const anonymousRequest = (time: string, usage: unknown) => + JSON.stringify({ + type: "token_usage_record", + timestamp: `2026-08-01T${time}.000Z`, + payload: { usage }, + }); + it.each([ + { + name: "does not bill an older snapshot re-emitted after requests without cumulative counters", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4))), + at("10:00:10", counted(counters(30, 6))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + ], + processed: [120, 24, 36, 0], + skipped: 1, + }, + { + name: "bills a rewind that follows a request without cumulative counters", + lines: [ + at("10:00:00", counted(counters(100, 20))), + at("10:00:10", counted(counters(20, 4), counters(60, 12))), + ], + processed: [120, 24], + skipped: 0, + }, + { + name: "keeps the baseline when it rejects an older snapshot, so the replay that follows is not billed", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + at("10:00:10", counted(counters(30, 6), counters(150, 30))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + at("10:00:10", counted(counters(30, 6), counters(150, 30))), + ], + processed: [120, 24, 36, 0, 0], + skipped: 1, + }, + { + name: "keeps the baseline when it rejects a lower snapshot from the baseline's own time", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:00", counted(counters(20, 4), counters(120, 24))), + at("10:00:00", counted(counters(30, 6), counters(150, 30))), + at("10:00:00", counted(counters(20, 4), counters(120, 24))), + at("10:00:00", counted(counters(30, 6), counters(150, 30))), + ], + processed: [120, 24, 36, 0, 0], + skipped: 1, + }, + { + name: "does not bill replayed snapshots against a cached baseline of unknown age", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + at("10:00:10", counted(counters(30, 6), counters(150, 30))), + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + at("10:00:05", counted(counters(20, 4), counters(120, 24))), + ], + undatedAfter: 3, + processed: [120, 24, 36, 0, 0], + skipped: 1, + }, + { + name: "warns about the anonymous request a rewound snapshot does not report", + lines: [ + at("10:00:00", counted(counters(100, 20), counters(100, 20))), + anonymousRequest("10:00:05", counters(40, 8)), + anonymousRequest("10:00:06", counters(20, 4)), + at("10:00:07", counted(counters(20, 4), counters(60, 12))), + at("10:00:08", counted(counters(10, 2), counters(70, 14))), + ], + processed: [120, 0, 0, 24, 12], + skipped: 1, + }, + ])("$name", ({ lines, undatedAfter, processed, skipped }) => { + const state = initialCodexScanState(); + parseCodexLine(turnContext, state); + const billed = lines.map((line, index) => { + if (index === undatedAfter) delete state.latestCumulativeAtMs; + const record = parseCodexLine(line, state); + return record === null ? 0 : totalTokens(record.totals); + }); + + expect({ processed: billed, skipped: codexUsageFormat.readMalformedRecords?.(state) }).toEqual({ + processed, + skipped, + }); + }); + it("ignores a replay of the current sequence's first request without rewinding the baseline", () => { const state = initialCodexScanState(); parseCodexLine(turnContext, state); diff --git a/apps/server/src/provider/Drivers/codexUsage.ts b/apps/server/src/provider/Drivers/codexUsage.ts index 7f99d611c3de5..a2977d3080fee 100644 --- a/apps/server/src/provider/Drivers/codexUsage.ts +++ b/apps/server/src/provider/Drivers/codexUsage.ts @@ -54,10 +54,15 @@ function readCodexTokenUsage(value: unknown): CodexTokenUsage | null { return isCodexTokenUsage(usage) ? usage : null; } +// Every move of the baseline dates it, so an older snapshot re-emitted later is never a rewind. +function dateCodexBaseline(state: CodexScanState, timestampMs: number) { + state.latestCumulativeAtMs = Math.max(state.latestCumulativeAtMs ?? timestampMs, timestampMs); +} + // A zeroed baseline rebases the counters, so the sequence start measured against it is forgotten. function rebaseCodexUsage(state: CodexScanState, cumulative: CodexTokenUsage, timestampMs: number) { state.lastCumulativeUsage = cumulative; - state.latestCumulativeAtMs = Math.max(state.latestCumulativeAtMs ?? timestampMs, timestampMs); + dateCodexBaseline(state, timestampMs); delete state.unreportedRequests; if (cumulative.input_tokens + cumulative.output_tokens === 0) delete state.sequenceStartSignature; } @@ -112,6 +117,18 @@ function unreportedRequests( ); } +// A rewound snapshot vouches only for the request it reports, so the anonymous requests read before +// it can be neither billed nor ruled out as that request's prefix. +function discardedRequests( + pending: readonly CodexUnreportedRequest[] | undefined, + last: CodexTokenUsage, +) { + const final = pending?.at(-1); + if (pending === undefined || final === undefined) return 0; + const reported = CODEX_USAGE_FIELDS.every((key) => final.usage[key] === last[key]); + return pending.length - (reported ? 1 : 0); +} + /** * Codex `token_count` events carry no model or service tier, so both are carried forward: the model * from the most recent `turn_context`, the tier from the most recent `thread_settings_applied`. @@ -251,6 +268,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, request.usage); } state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, usage); + dateCodexBaseline(state, timestampMs); delete state.unreportedRequests; return [ ...pending.map((request) => codexRequestRecord(state, request.usage, request)), @@ -295,6 +313,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag if (cumulative !== null) rebaseCodexUsage(state, cumulative, timestampMs); else if (!hasCumulative && last !== null && signature !== state.lastUsageSignature) { state.lastCumulativeUsage = advanceCodexUsage(state.lastCumulativeUsage, last); + dateCodexBaseline(state, timestampMs); } state.lastUsageSignature = signature; return []; @@ -345,15 +364,18 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag // Only the same event is a replay; a later request can restart with identical counters. if (restarted && sequenceStart === state.sequenceStartSignature) { state.lastCumulativeUsage = previous; + // The retained baseline keeps its own age; one of unknown age must not take the replay's. + if (latestCumulativeAtMs === undefined) delete state.latestCumulativeAtMs; return []; } // Forks and paginated continuations can inherit totals without copying a counter snapshot, and // a later request can continue from an earlier snapshot; a re-emitted old snapshot is not later. - // Only bill the latest request, and require the unseen prefix to be valid usage too. + // Only bill the latest request, and require the unseen prefix to be valid usage too. A baseline + // of unknown age (a scan state cached before every move dated it) cannot order the snapshot. + const lowered = + previous !== null && CODEX_USAGE_FIELDS.some((key) => cumulative[key] < previous[key]); const rewound = - previous !== null && - (latestCumulativeAtMs === undefined || timestampMs > latestCumulativeAtMs) && - CODEX_USAGE_FIELDS.some((key) => cumulative[key] < previous[key]); + lowered && latestCumulativeAtMs !== undefined && timestampMs > latestCumulativeAtMs; const reconciled = previous === null || rewound ? readCodexTokenUsage( @@ -363,10 +385,24 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag if (!restarted && !reconciled) { const bridged = unreportedRequests(previous, cumulative, last, pending); if (bridged === null) { + // A rejected snapshot from before the baseline's time is a replay, not the next baseline. + // At the baseline's own time only lower counters are one; zeroed counters still rebase. + const replayed = + latestCumulativeAtMs !== undefined && + (timestampMs < latestCumulativeAtMs || + (timestampMs === latestCumulativeAtMs && + lowered && + cumulative.input_tokens + cumulative.output_tokens > 0)); + if (replayed) { + state.lastCumulativeUsage = previous; + if (pending !== undefined) state.unreportedRequests = pending; + } state.malformedRecords += 1; return []; } unreported = bridged; + } else if (!restarted && rewound) { + state.malformedRecords += discardedRequests(pending, last); } if (restarted) state.sequenceStartSignature = sequenceStart; } else { @@ -378,6 +414,7 @@ function parseCodexRecord(parsed: unknown, state: CodexScanState): readonly Usag return []; } state.lastCumulativeUsage = advanced; + dateCodexBaseline(state, timestampMs); } state.lastUsageSignature = signature; diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 1496abee20cc4..32e272fcd5a79 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -67,6 +67,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as PubSub from "effect/PubSub"; +import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; @@ -842,6 +843,86 @@ it.layer( }), ); + it.effect("shows Codex usage that answers after three seconds inside the probe budget", () => + Effect.gen(function* () { + const usageRequested = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Effect.gen(function* () { + const scope = yield* Effect.scope; + const output = yield* Queue.unbounded(); + const send = (message: unknown) => + Queue.offer(output, encoder.encode(`${JSON.stringify(message)}\n`)); + const results: Record = { + initialize: { + userAgent: "codex_cli_rs/0.167.0", + codexHome: "/nonexistent-codex-home", + platformFamily: "unix", + platformOs: "linux", + }, + "account/read": { + account: { type: "chatgpt", email: "test@example.com", planType: "pro" }, + requiresOpenaiAuth: true, + }, + "config/read": { config: {}, origins: {} }, + "skills/list": { data: [] }, + "model/list": { data: [] }, + }; + const answer = (line: string) => { + const { id, method } = JSON.parse(line) as { id?: number; method?: string }; + if (id === undefined || method === undefined) return Effect.void; + if (method !== "account/rateLimits/read") { + return send({ id, result: results[method] ?? {} }); + } + return Deferred.succeed(usageRequested, undefined).pipe( + Effect.andThen(Effect.sleep("4 seconds")), + Effect.andThen( + send({ + id, + result: { + rateLimits: { + limitId: "codex", + planType: "pro", + primary: { usedPercent: 42, windowDurationMins: 300, resetsAt: 2e9 }, + }, + rateLimitsByLimitId: null, + rateLimitResetCredits: null, + accountId: null, + }, + }), + ), + Effect.forkIn(scope), + ); + }; + const decoder = new TextDecoder(); + let buffered = ""; + return ChildProcessSpawner.makeHandle({ + ...mockHandle({ stdout: "", stderr: "", code: 0 }), + exitCode: Effect.never, + isRunning: Effect.succeed(true), + stdin: Sink.forEach((chunk: Uint8Array) => { + buffered += decoder.decode(chunk, { stream: true }); + const lines = buffered.split("\n"); + buffered = lines.pop() ?? ""; + return Effect.forEach(lines.filter(Boolean), answer, { discard: true }); + }), + stdout: Stream.fromQueue(output), + }); + }), + ); + const fiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.forkChild, + ); + yield* Deferred.await(usageRequested); + yield* TestClock.adjust("25 seconds"); + const status = yield* Fiber.join(fiber); + + assert.strictEqual(status.auth.status, "authenticated"); + assert.isUndefined(status.usageLimits?.unavailable); + assert.strictEqual(status.usageLimits?.windows[0]?.usedPercent, 42); + }), + ); + it.effect("does not run --version when the Codex executable cannot start", () => Effect.gen(function* () { if ((yield* HostProcess.Platform) === "win32") return; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index f80950bf8daed..0b2ec311f2af5 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { - "claudeSystemAppendBytes": 6144, - "codexAdditionalContextBytes": 7874, - "mcpToolListJsonBytes": 51128 + "claudeSystemAppendBytes": 6477, + "codexAdditionalContextBytes": 7871, + "mcpToolListJsonBytes": 51600 } diff --git a/apps/server/src/provider/claudeUsageLimits.test.ts b/apps/server/src/provider/claudeUsageLimits.test.ts index 5a7268fa8c831..072f84611580c 100644 --- a/apps/server/src/provider/claudeUsageLimits.test.ts +++ b/apps/server/src/provider/claudeUsageLimits.test.ts @@ -208,6 +208,22 @@ describe("claudeUsageResponseToLimits", () => { ).toEqual([monthlyWindow]); }); + it("flags a $0 cap instead of reporting a monthly window", () => { + const response = { + rate_limits_available: true, + rate_limits: { + five_hour: null, + seven_day: null, + extra_usage: { is_enabled: true, used_credits: 0, monthly_limit: 0, utilization: null }, + }, + }; + expect(claudeUsageResponseToLimits({ checkedAt, response }).limits).toEqual({ + checkedAt, + windows: [], + zeroSpendCap: true, + }); + }); + it("omits disabled budgets and refuses invalid money without an enabled fallback", () => { const rateLimits = enterpriseResponse.rate_limits; const response = { diff --git a/apps/server/src/provider/claudeUsageLimits.ts b/apps/server/src/provider/claudeUsageLimits.ts index 489b9e651fa1d..cc2cb73453a63 100644 --- a/apps/server/src/provider/claudeUsageLimits.ts +++ b/apps/server/src/provider/claudeUsageLimits.ts @@ -60,8 +60,20 @@ export const makeClaudeScopedLimitNames = Ref.make({ overageIncluded: undefined, }); +const SCOPED_WINDOW_PREFIX = "seven_day_"; +const scopeToken = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, "_"); + function scopedWindowId(displayName: string): string { - return `seven_day_${displayName.toLowerCase().replace(/[^a-z0-9]+/g, "_")}`; + return `${SCOPED_WINDOW_PREFIX}${scopeToken(displayName)}`; +} + +/** A model-scoped weekly allowance blocks only its own model; an unknown model is not blocked. */ +export function windowLimitsModel( + window: Pick, + model: string | null, +): boolean { + if (!window.id.startsWith(SCOPED_WINDOW_PREFIX)) return true; + return model !== null && scopeToken(model).includes(window.id.slice(SCOPED_WINDOW_PREFIX.length)); } function scopedWindow( @@ -217,6 +229,7 @@ export function claudeUsageResponseToLimits(input: { overageIncluded ??= entry.display_name; } const spendPercent = readSpendPercent(response.rate_limits); + const extra = response.rate_limits.extra_usage; if (spendPercent !== undefined) { windows.push({ id: "monthly_spend", @@ -226,7 +239,10 @@ export function claudeUsageResponseToLimits(input: { }); } return { - limits: makeUsageLimits({ checkedAt, windows }), + limits: { + ...makeUsageLimits({ checkedAt, windows }), + ...(extra?.is_enabled && extra.monthly_limit === 0 ? { zeroSpendCap: true } : {}), + }, names: { overageIncluded }, }; } diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.ts index dd3f1c01cd352..18c1dcf3f72ed 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.ts @@ -117,6 +117,7 @@ export function shouldPublishAgentAwarenessEvent( case "thread.active-reordered": case "thread.tags-updated": case "thread.visited": + case "thread.visit-recorded": case "thread.marked-unread": case "thread.runtime-mode-updated": case "thread.interaction-mode-updated": diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index f3e3bfbf652e8..e4c270627e188 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -29,6 +29,7 @@ import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as BackgroundPolicy from "./background/BackgroundPolicy.ts"; import * as HostPowerMonitor from "./background/HostPowerMonitor.ts"; +import * as NonBlockingSpawner from "./process/NonBlockingSpawner.ts"; import * as KeepAwake from "./background/KeepAwake.ts"; import * as ServerConfig from "./config.ts"; import { withUntracedRequests } from "./http.ts"; @@ -383,9 +384,14 @@ const layerHttpServer = Layer.unwrap( }, ); }), -).pipe(Layer.provide(ManagedPolicy.layer)); +).pipe( + Layer.provide(ManagedPolicy.layer), + // NodeHttpServer.layer also outputs NodeServices, whose spawner would shadow the wrapped one. + (layer) => NonBlockingSpawner.layer.pipe(Layer.provideMerge(layer)), +); const layerPlatformServices = DocumentText.layer.pipe( + Layer.provideMerge(NonBlockingSpawner.layer), Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), ); @@ -575,6 +581,7 @@ const layerScheduledTaskWebhookOrigin = Layer.effect( ); const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe( + Layer.provide(UsageLimitSources.layerResetFallback), Layer.provide(layerScheduledTaskWebhookOrigin), Layer.provide(ProviderUsageAnalytics.layer), Layer.provide(layerCheckpointStore), @@ -1310,4 +1317,7 @@ const layerMakeServer = Layer.unwrap( }), ).pipe(Layer.provide(ProcessRunner.layer)); -export const runServer = Layer.launch(layerMakeServer); +export const runServer = Layer.launch( + // For the layers above whose spawner requirement is met by the caller's runtime. + layerMakeServer.pipe(Layer.provide(NonBlockingSpawner.layer)), +); diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 7a3c6068a0543..2b8d9874a8fe1 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -52,6 +52,7 @@ it.effect.each([ "disabled-default", "launch-failure", "project-failure", + "project-refused", ] as const)("keeps bootstrap launch failures separate from project failures: %s", (scenario) => Effect.gen(function* () { const projectId = ProjectId.make("bootstrap-project"); @@ -155,22 +156,28 @@ it.effect.each([ bootstrap: () => scenario === "project-failure" ? Effect.die("project bootstrap failed") - : Effect.succeed({ - created: true, - project: { - id: projectId, - title: "Project", - workspaceRoot: "/bootstrap-project", - repositoryIdentity: null, - faviconPath: null, - scripts: [], - createdAt: "2026-01-01T00:00:00Z", - updatedAt: "2026-01-01T00:00:00Z", - deletedAt: null, - defaultModelSelection: - scenario === "disabled-default" ? { instanceId, model: "custom-model" } : null, - }, - }), + : scenario === "project-refused" + ? Effect.fail( + new ProjectService.ProjectInvalidError({ projectId, detail: "refused folder" }), + ) + : Effect.succeed({ + created: true, + project: { + id: projectId, + title: "Project", + workspaceRoot: "/bootstrap-project", + repositoryIdentity: null, + faviconPath: null, + scripts: [], + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + deletedAt: null, + defaultModelSelection: + scenario === "disabled-default" + ? { instanceId, model: "custom-model" } + : null, + }, + }), }), Layer.mock(ThreadManagement.ThreadManagementService)({ countThreads: () => Effect.succeed(0), @@ -223,7 +230,10 @@ it.effect.each([ } else { assert.isDefined(welcome); if (welcome?.type === "welcome") { - assert.equal(welcome.payload.bootstrapProjectId, projectId); + assert.equal( + welcome.payload.bootstrapProjectId, + scenario === "project-refused" ? undefined : projectId, + ); assert.isUndefined(welcome.payload.bootstrapThreadId); } } diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 689659ab23f59..0d84e99169e1b 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -270,12 +270,24 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () { if (serverConfig.autoBootstrapProjectFromCwd) { const threadModelSelection = getAutoBootstrapThreadModelSelection(); - const { project } = yield* projects.bootstrap({ - commandId: CommandId.make(yield* randomUUID), - projectId: ProjectId.make(yield* randomUUID), - title: path.basename(serverConfig.cwd) || "project", - workspaceRoot: serverConfig.cwd, - }); + const bootstrapped = yield* projects + .bootstrap({ + commandId: CommandId.make(yield* randomUUID), + projectId: ProjectId.make(yield* randomUUID), + title: path.basename(serverConfig.cwd) || "project", + workspaceRoot: serverConfig.cwd, + }) + .pipe( + // A folder the project rules refuse must not stop the server from starting there. + Effect.catchTags({ + ProjectInvalidError: (error) => + Effect.logWarning("Skipped bootstrap project", { detail: error.detail }).pipe( + Effect.as(undefined), + ), + }), + ); + if (bootstrapped === undefined) return {} satisfies AutoBootstrapWelcomeTargets; + const { project } = bootstrapped; const existingThread = (yield* threads.listActiveShellIndex()).find( (thread) => thread.projectId === project.id && isListedThreadLineage(thread.lineage), ); diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index c7d6c5e5d8f3a..ac699b9c7d6cb 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -1586,6 +1586,56 @@ process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.dat }), ); + it.effect("starts no trial when stopped during the pre-update backup", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-backup-stop-" }); + const statePath = path.join(root, "runtime", "service-state.json"); + const childSource = "setInterval(() => {}, 1000);\n"; + for (const version of ["1.0.0", "1.1.0"]) { + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", version), + childSource, + ); + } + const dbPath = path.join(root, "userdata", "state.sqlite"); + yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true }); + yield* fs.writeFileString(dbPath, "database"); + const pending = { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.0.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + dbPath, + status: "pending", + }, + } as const; + yield* Effect.promise(() => writeServiceState(statePath, pending)); + const childCount = spawnedChildren.length; + const launcher = new Launcher(root, pending); + + // Recovery is already queued, so this stop lands while the backup runs. + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + // A trial started here arms its 30-minute prepared timer, which keeps the stopped launcher alive. + assert.deepEqual( + spawnedChildren.slice(childCount).map((child) => child.spawnargs.join(" ")), + [], + ); + assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), pending); + const backupDir = path.join(root, "runtime", "db-backup", "update-1"); + assert.isFalse(yield* fs.exists(backupDir)); + assert.isFalse(yield* fs.exists(`${backupDir}.staging`)); + }), + ); + it.effect("records no update when the server exits during the backup check", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index c07697007fe57..1a6c07cf43659 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -326,14 +326,18 @@ async function syncDirectory(directory: string): Promise { } } -function runCp(args: ReadonlyArray): Promise { +function runCp(args: ReadonlyArray, signal?: AbortSignal): Promise { return new Promise((resolve) => { - NodeChildProcess.execFile("cp", args, (error) => resolve(error === null)); + NodeChildProcess.execFile("cp", args, { signal }, (error) => resolve(error === null)); }); } // macOS fs.copyFile clone flags fall back to full copies. -async function copyDatabaseFile(source: string, destination: string): Promise { +async function copyDatabaseFile( + source: string, + destination: string, + signal?: AbortSignal, +): Promise { // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. const platform = process.platform; // cp -c replaces files and breaks hard links; copy into hard-linked destinations instead. @@ -346,7 +350,9 @@ async function copyDatabaseFile(source: string, destination: string): Promise { +async function backupDatabaseOnce( + baseDir: string, + pending: PendingServiceUpdate, + signal: AbortSignal, +): Promise { const backupDir = databaseBackupDir(baseDir, pending.id); if (await pathExists(backupDir)) return; @@ -534,10 +544,11 @@ async function backupDatabaseOnce(baseDir: string, pending: PendingServiceUpdate await NodeFSP.mkdir(stagingDir, { recursive: true, mode: 0o700 }); try { for (const suffix of DB_FILE_SUFFIXES) { + signal.throwIfAborted(); const source = `${pending.dbPath}${suffix}`; if (suffix !== "" && !(await pathExists(source))) continue; const destination = databaseBackupFile(stagingDir, suffix); - await copyDatabaseFile(source, destination); + await copyDatabaseFile(source, destination, signal); await syncFile(destination); } await NodeFSP.rename(stagingDir, backupDir); @@ -830,6 +841,7 @@ export class Launcher { #timer: NodeJS.Timeout | undefined; #transitions: Promise = Promise.resolve(); #stopRequested = false; + readonly #stopSignal = new AbortController(); #stopping = false; #done = false; readonly #completion = Promise.withResolvers(); @@ -948,6 +960,7 @@ export class Launcher { return; } this.#stopRequested = true; + this.#stopSignal.abort(); this.#clearTimer(); this.#enqueue(async () => { // Let in-progress updates start replacements first; replacements observe the marker and own pre-activation tunnel cleanup. @@ -1043,11 +1056,14 @@ export class Launcher { async #startTrial(pending: PendingServiceUpdate): Promise { try { - await backupDatabaseOnce(this.#baseDir, pending); + await backupDatabaseOnce(this.#baseDir, pending, this.#stopSignal.signal); } catch { + // A stop aborts the copy and leaves the update pending for the next start. + if (this.#stopRequested) return; await this.#returnToPrevious(pending, "failed", "db-backup-failed"); return; } + if (this.#stopRequested) return; try { await this.#startChild(pending.targetVersion, "trial", pending); } catch { @@ -1202,8 +1218,6 @@ export class Launcher { this.#child = null; await this.#terminate(child.process); await finishOnlineBackup?.(); - // A stop during a minutes-long copy should not start a trial; restart resumes the pending update. - if (this.#stopRequested) return; await this.#startTrial(pending); } diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts index 4a0533da0b86e..bebdeef9ece33 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.test.ts @@ -78,6 +78,7 @@ function layer(input: { Layer.provide( Layer.mock(GitVcsDriver.GitVcsDriver)({ execute: () => Effect.succeed(processOutput()), + invalidateRefs: () => Effect.void, ensureRemote: () => Effect.succeed("origin"), pushCurrentBranch: () => Effect.succeed({ @@ -220,7 +221,7 @@ it.effect.each(["--bare", "source.git"])( }); assert.strictEqual(result.cwd, destinationPath); assert.isTrue(yield* fs.exists(path.join(destinationPath, ".git"))); - }).pipe(Effect.provide(layer({ git: { execute: git.execute } }))); + }).pipe(Effect.provide(layer({ git }))); }).pipe( Effect.provide( GitVcsDriver.layer.pipe( @@ -235,6 +236,72 @@ it.effect.each(["--bare", "source.git"])( ), ); +it.effect.each([ + { readsWhen: "before git creates the repository", readBeforeInit: true }, + { readsWhen: "while HEAD is unborn", readBeforeInit: false }, +])("lists the cloned branches after a ref list was read $readsWhen", ({ readBeforeInit }) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const git = yield* GitVcsDriver.GitVcsDriver; + const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-clone-refs-" }); + const source = path.join(parent, "source"); + const destinationPath = path.join(parent, "checkout"); + const run = (cwd: string, args: ReadonlyArray) => + git.execute({ operation: "test.git", cwd, args }); + yield* run(parent, ["init", "--initial-branch=staging", source]); + yield* run(source, [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "--allow-empty", + "-m", + "init", + ]); + const refNames = git + .listRefs({ cwd: destinationPath }) + .pipe(Effect.map((result) => result.refs.map((ref) => ref.name))); + let duringClone: ReadonlyArray | null = null; + // Stands in for git clone so the read lands at a chosen point inside it. + const cloneInTwoSteps = Effect.gen(function* () { + yield* fs.makeDirectory(destinationPath).pipe(Effect.orDie); + if (readBeforeInit) duringClone = yield* refNames; + yield* run(parent, ["init", "--initial-branch=staging", destinationPath]); + if (!readBeforeInit) duringClone = yield* refNames; + return yield* run(destinationPath, ["pull", source, "staging"]); + }); + yield* Effect.gen(function* () { + const service = yield* SourceControlRepositoryService.SourceControlRepositoryService; + yield* service.cloneRepository({ remoteUrl: source, destinationPath }); + }).pipe( + Effect.provide( + layer({ + git: { + ...git, + execute: (input) => (input.args[0] === "clone" ? cloneInTwoSteps : git.execute(input)), + }, + }), + ), + ); + + assert.deepStrictEqual(duringClone, []); + assert.deepStrictEqual(yield* refNames, ["staging"]); + }).pipe( + Effect.provide( + GitVcsDriver.layer.pipe( + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-clone-refs-config-", + }), + ), + Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), +); + it.effect("reports clone progress from git's stderr and keeps its error text on failure", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.ts index 3db65b0bd5f95..b4b2dc0e92fe5 100644 --- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts +++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts @@ -429,6 +429,8 @@ export const make = Effect.gen(function* () { ), ); + // A ref list read while the clone ran saw an unborn HEAD and no refs. + yield* git.invalidateRefs(prepared.destinationPath); return { cwd: prepared.destinationPath, remoteUrl, diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 09ff68754ceb1..a70cecab59db8 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -362,6 +362,7 @@ const cleanupFixture = ( let sessionLiveChecks = 0; let onLiveCheck: Effect.Effect = Effect.void; let outboxStatus: string | null = null; + let scheduledThreadIds: string[] = []; let fullStatusCalls = 0; let gitInspections = 0; let snapshotReads = 0; @@ -492,7 +493,9 @@ const cleanupFixture = ( ...threads.flatMap((thread) => thread.worktreePath ?? []), ...storedWorktreePaths, ].map((worktreePath) => ({ worktreePath })) - : [], + : strings.join("").includes("scheduled_tasks") + ? scheduledThreadIds.map((threadId) => ({ threadId })) + : [], )) as unknown as SqlClient.SqlClient), Effect.provideService(GitManager.GitManager, { invalidateStatus: () => Effect.void, @@ -583,6 +586,9 @@ const cleanupFixture = ( setOutboxStatus: (status: string | null) => { outboxStatus = status; }, + setScheduledThreadIds: (next: string[]) => { + scheduledThreadIds = next; + }, setDeletedThreads: (next: OrchestrationV2ThreadShell[]) => { deletedThreads = next; }, @@ -2642,6 +2648,114 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.effect("removes an idle No project thread's scratch folder past the retention", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const scratchRoot = `${fixture.config.baseDir}/scratch`; + const folder = `${scratchRoot}/quiet-otter`; + yield* fixture.fs.makeDirectory(folder, { recursive: true }); + yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); + fixture.setProjectRoots([scratchRoot]); + fixture.setStoredWorktreePaths([]); + // Only this rule lets cleanup delete untracked files, which is all a scratch folder has. + fixture.setPolicy("tracked-changes"); + fixture.setThreads([ + shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), + ]); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ path: folder, outcome: "removed" }), + ]); + expect(yield* fixture.fs.exists(folder)).toBe(false); + }), + ), + ); + it.effect.each([ + { + name: "a Git repository in a subfolder", + policy: "tracked-changes", + repository: "clone/.git", + reason: "Contains a nested Git repository", + }, + { + name: "a Git repository of its own", + policy: "tracked-changes", + repository: ".git", + reason: "Contains a nested Git repository", + }, + { name: "files under the default keep rule", reason: "Has local files (notes.md)" }, + { + name: "a scheduled task", + policy: "tracked-changes", + scheduled: true, + reason: "Thread has a scheduled task", + }, + ] as const)( + "keeps an idle No project thread's scratch folder with $name", + ({ + policy, + repository, + scheduled, + reason, + }: { + readonly policy?: WorktreeKeepWhen; + readonly repository?: string; + readonly scheduled?: boolean; + readonly reason: string; + }) => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const scratchRoot = `${fixture.config.baseDir}/scratch`; + const folder = `${scratchRoot}/quiet-otter`; + yield* fixture.fs.makeDirectory( + repository === undefined ? folder : `${folder}/${repository}`, + { recursive: true }, + ); + yield* fixture.fs.writeFileString(`${folder}/notes.md`, "scratch\n"); + // No thread owns this one, so it is listed and never removed. + const leftover = `${scratchRoot}/leftover`; + yield* fixture.fs.makeDirectory(leftover); + yield* fixture.fs.utimes(leftover, 1, 1); + fixture.setProjectRoots([scratchRoot]); + fixture.setStoredWorktreePaths([]); + if (policy !== undefined) fixture.setPolicy(policy); + if (scheduled) fixture.setScheduledThreadIds(["thread-1"]); + fixture.setThreads([ + shell({ worktreePath: folder, settledAt: at(-20 * DAY_MS), status: "completed" }), + ]); + const report = yield* fixture.service.runNow; + expect( + report.entries.map(({ path, outcome, reason }) => ({ path, outcome, reason })), + ).toEqual([ + { path: leftover, outcome: "kept", reason: "No thread uses this folder" }, + { path: folder, outcome: "kept", reason }, + ]); + expect(yield* fixture.fs.exists(`${folder}/notes.md`)).toBe(true); + }), + ), + ); + it.effect("keeps a thread's worktree folder that lost its .git link", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: fixture.worktree, archivedAt: at(-DAY_MS) }), + ]); + yield* fixture.fs.remove(`${fixture.worktree}/.git`); + yield* fixture.fs.makeDirectory(`${fixture.worktree}/node_modules`); + const report = yield* fixture.service.runNow; + expect(report.entries).toEqual([ + expect.objectContaining({ path: fixture.worktree, outcome: "kept" }), + ]); + expect(yield* fixture.fs.exists(`${fixture.worktree}/node_modules`)).toBe(true); + }), + ), + ); it.live("skips a stored worktree path whose parent is a regular file", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 52f3dcce090a8..fa2e6a6428c9b 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -45,6 +45,7 @@ import * as ServerConfig from "./config.ts"; import * as GitManager from "./git/GitManager.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; +import { scratchFolderRoot } from "./project/ManagedProjectFolders.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; @@ -392,20 +393,21 @@ const make = Effect.gen(function* () { const measureWorktree = Effect.fn("storageCleanup.measureWorktree")( function* ( worktreePath: string, - inspectRepositories = false, + inspectRepositories: boolean | "plain-folder" = false, checkedSubmodules: ReadonlyArray = [], ) { const root = yield* fs.realPath(worktreePath); const skipped = yield* sharedPnpmVirtualStore(root); const incomplete = { bytes: null, reason: "worktree could not be fully inspected" }; - const repositories = new Set([pathKey(root)]); + // A plain folder is not a checkout, so a repository at its root counts like one below it. + const repositories = new Set(inspectRepositories === "plain-folder" ? [] : [pathKey(root)]); const moduleStores: string[] = []; for (const submodule of checkedSubmodules) { repositories.add(pathKey(submodule)); repositories.add(pathKey(path.join(submodule, ".git"))); moduleStores.push(pathKey(path.join(submodule, ".git", "modules"))); } - if (inspectRepositories && (yield* fs.exists(path.join(root, ".gitmodules")))) { + if (inspectRepositories === true && (yield* fs.exists(path.join(root, ".gitmodules")))) { const submodules = yield* git.execute({ operation: "StorageCleanup.nestedRepositories", cwd: root, @@ -532,6 +534,7 @@ const make = Effect.gen(function* () { roots: ReadonlyArray, projects: ReadonlyArray<{ readonly workspaceRoot: string }>, entries: StorageCleanupReportEntry[], + scratchRoot: string | null, ) { const rows = yield* sql<{ worktreePath: string }>` SELECT DISTINCT json_extract(payload_json, '$.worktreePath') AS "worktreePath" @@ -570,12 +573,14 @@ const make = Effect.gen(function* () { (root) => !inside(root, managedRoot) && (pathKey(root) === pathKey(target) || inside(root, target)), ); - const directories = Effect.fnUntraced(function* (parent: string, managedRoot: string) { - if (inProject(parent, managedRoot)) return []; + // The scratch root is itself a project, so its folders skip the project check. + const directories = Effect.fnUntraced(function* (parent: string, managedRoot: string | null) { + const skipped = (target: string) => managedRoot !== null && inProject(target, managedRoot); + if (skipped(parent)) return []; const result: string[] = []; for (const name of yield* fs.readDirectory(parent).pipe(Effect.orElseSucceed(() => []))) { const target = path.join(parent, name); - if (!inside(parent, target) || inProject(target, managedRoot)) continue; + if (!inside(parent, target) || skipped(target)) continue; const directory = yield* Effect.gen(function* () { if (pathKey(yield* fs.realPath(target)) !== pathKey(target)) return false; return (yield* fs.stat(target)).type === "Directory"; @@ -590,7 +595,7 @@ const make = Effect.gen(function* () { let firstMeasurement = true; const reported = new Set(); const report = Effect.fnUntraced( - function* (worktreePath: string) { + function* (worktreePath: string, scratch = false) { const key = pathKey(worktreePath); if ( reported.has(key) || @@ -618,7 +623,9 @@ const make = Effect.gen(function* () { outcome: "kept", reason: linked ? "No thread uses this worktree" - : "No thread uses this folder, and it isn't a git worktree", + : scratch + ? "No thread uses this folder" + : "No thread uses this folder, and it isn't a git worktree", path: worktreePath, projectPath: null, threadId: null, @@ -666,6 +673,8 @@ const make = Effect.gen(function* () { }).pipe(Effect.orElseSucceed(() => undefined)); } } + if (scratchRoot !== null) + for (const folder of yield* directories(scratchRoot, null)) yield* report(folder, true); for (const key of orphanSizes.keys()) { if (!reported.has(key)) orphanSizes.delete(key); } @@ -1024,6 +1033,32 @@ const make = Effect.gen(function* () { ); if (root !== null && !isFilesystemRoot(root, path)) roots.push(root); } + const scratchRoot = yield* fs + .realPath(scratchFolderRoot(config.baseDir, path)) + .pipe(Effect.orElseSucceed(() => null)); + // Nothing can bring a scratch folder's files back, so these hold whatever the retention says. + const scratchKeepReason = Effect.fn("StorageCleanup.scratchKeepReason")(function* ( + folder: string, + threadIds: ReadonlyArray, + rules: WorktreeCleanupRules, + ) { + const realParent = yield* fs.realPath(path.dirname(folder)); + if ((yield* fs.realPath(folder)) !== path.join(realParent, path.basename(folder))) + return "folder is a symbolic link"; + // Every file here is untracked, and only "tracked-changes" lets cleanup delete those. + if (rules.worktreeKeepWhen !== "tracked-changes") { + const file = (yield* fs.readDirectory(folder)).find((name) => name !== "node_modules"); + if (file !== undefined) return `has local files (${file})`; + } + // Each run of a scheduled task works on what its earlier runs left in the folder. + const scheduled = yield* sql<{ threadId: string }>` + SELECT thread_id AS "threadId" FROM scheduled_tasks + WHERE enabled = 1 AND thread_id IS NOT NULL + `.pipe(NodeSqliteClient.readOnly); + if (scheduled.some((task) => threadIds.includes(task.threadId))) + return "thread has a scheduled task"; + return null; + }); const worktreePathReason = Effect.fn("StorageCleanup.worktreePathReason")(function* ( worktreePath: string, ) { @@ -1034,8 +1069,10 @@ const make = Effect.gen(function* () { return "worktree is a symbolic link"; if (!roots.some((root) => inside(root, realPath))) return "outside the managed worktree folder"; - if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") - return "not a linked worktree"; + const gitLink = yield* fs + .stat(path.join(worktreePath, ".git")) + .pipe(Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined)); + if (gitLink?.type !== "File") return "not a linked worktree"; return null; }); const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>` @@ -1125,6 +1162,11 @@ const make = Effect.gen(function* () { const worktreeKey = yield* canonical(worktreePath); const worktreePaths = [worktreePath, worktreeKey]; const group = groups.get(worktreeKey) ?? []; + // No project threads have no branch; their folders sit directly in the scratch root. + const scratch = + thread.branch === null && + scratchRoot !== null && + pathKey(path.dirname(worktreeKey)) === pathKey(scratchRoot); const activityAt = Math.max(...group.map(storageCleanupActivityAt)); const deleted = "workspaceRoot" in thread; const settlementChain = deleted @@ -1220,8 +1262,153 @@ const make = Effect.gen(function* () { : settings.worktreeUnchanged ? "not settled" : "no rules apply"; + // The merge and unchanged rules read Git, which a scratch folder does not have. + if (scratch && !eligible) + return keep( + settings.worktreeAfterDays !== null || settings.worktreeSettledAfterDays !== null + ? notDueReason + : "no rules apply", + ); // Only Git-based rules can make a not-yet-due worktree eligible, so skip Git otherwise. if (!eligible && !unchangedApplies && !settings.worktreeOnMerge) return keep(notDueReason); + // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds. + const blockedSinceCheck = Effect.fnUntraced(function* () { + const latestProjects = yield* projectStore.listShells(); + if (yield* containsProjectRoot(worktreePaths, [project, ...latestProjects])) + return "contains a project checkout"; + const bindings = yield* projections.getThreadWorktreePaths({ includeArchived: true }); + const bindingKeys = yield* Effect.forEach(bindings, (binding) => + canonical(binding.worktreePath), + ); + const latest = bindings.filter((_binding, index) => bindingKeys[index] === worktreeKey); + if (yield* hasTerminal(worktreePaths)) return waitForStop("open terminal"); + if (deleted) { + if ( + !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId) + .worktreeOnDelete + ) + return "thread or cleanup settings changed since check"; + // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout. + const pendingCleanup = yield* sql<{ status: string }>` + SELECT status FROM orchestration_v2_effect_outbox + WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') + `.pipe(NodeSqliteClient.readOnly); + // Failed effects never retry, so only running work can finish and free the path. + if (pendingCleanup.some((row) => row.status !== "failed")) + return waitForStop("thread deletion is still pending"); + if (pendingCleanup.length > 0) return "thread deletion is still pending"; + } + const latestShells = yield* Effect.forEach(latest, (entry) => + projections.getThreadShell(entry.threadId), + ); + const latestGroup = latestShells.filter((shell) => shell !== null); + const latestKeys = yield* Effect.forEach(latestGroup, (shell) => + shell.worktreePath === null ? Effect.succeed(null) : canonical(shell.worktreePath), + ); + const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup); + if ( + latestGroup.length !== group.length || + latestOwner?.id !== thread.id || + latestOwner?.branch !== thread.branch || + latestGroup.some((shell, index) => { + const previous = group.find((member) => member.id === shell.id); + return ( + previous === undefined || + shell.branch !== previous.branch || + !Equal.equals(shell.settledAt, previous.settledAt) || + (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) || + !storageCleanupThreadIdle(shell, now, serverSettings) || + latestKeys[index] !== worktreeKey || + storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) + ); + }) + ) + return waitForStop("thread activity or shared worktree changed since check"); + if (settlementChain.length > 1) { + const ancestors = yield* Effect.forEach(settlementChain.slice(1), (ancestor) => + projections.getThreadShell(ancestor.id), + ); + const latestSettlement = worktreeSettlementChain( + latestGroup.find((shell) => shell.id === thread.id)!, + new Map( + [...latestGroup, ...ancestors.filter((ancestor) => ancestor !== null)].map( + (ancestor) => [ancestor.id, ancestor], + ), + ), + now, + serverSettings, + ).at(-1); + if ( + latestSettlement?.id !== settledThread?.id || + !Equal.equals(latestSettlement?.settledAt, settledThread?.settledAt) || + !Equal.equals(latestSettlement?.updatedAt, settledThread?.updatedAt) + ) + return "parent settlement changed since check"; + } + // Sessions can outlive their run and can be shared across app threads. + const sessionRows = yield* sql<{ payload_json: string }>` + SELECT payload_json FROM orchestration_v2_projection_provider_sessions + WHERE status != 'stopped' + `.pipe(NodeSqliteClient.readOnly); + const sessions = yield* Effect.forEach(sessionRows, (row) => + decodeCleanupSession(row.payload_json), + ); + // Ready persisted sessions may have released their runtime; only live sessions protect the path. + for (const session of sessions) { + if ( + (yield* occupies(worktreePaths, session.cwd)) && + (yield* providerSessions.isLive(session.id)) + ) + return waitForStop("provider session is still open"); + } + return null; + }); + const settingsChangedSinceCheck = Effect.gen(function* () { + const currentSettings = yield* settingsService.getSettings; + const current = resolveWorktreeCleanup(currentSettings, thread.projectId); + return ( + currentSettings.autoResumeLimitedThreads !== serverSettings.autoResumeLimitedThreads || + currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads || + Object.keys(settings).some( + (key) => + current[key as keyof typeof settings] !== settings[key as keyof typeof settings], + ) + ); + }); + if (scratch) { + const threadIds = group.map((member) => member.id); + const blocked = + (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? + (yield* blockedSinceCheck()); + if (blocked !== null) return keep(blocked); + const inspection = yield* measureWorktree(worktreePath, "plain-folder"); + if (inspection.reason !== null) return keep(inspection.reason); + return yield* withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + // Walked again under the lease: a repository deleted with the folder is gone for good. + const finalInspection = yield* measureWorktree(worktreePath, "plain-folder"); + if (finalInspection.reason !== null) return keep(finalInspection.reason); + // The walk takes time, so the cheap checks run last, right before removal. + const blockedWhileMeasuring = + (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? + (yield* blockedSinceCheck()); + if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring); + if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); + yield* fs.remove(worktreePath, { recursive: true }); + entries.push({ + ...entry, + outcome: "removed", + reason: sentence(removalReason), + bytes: inspection.bytes, + }); + // The stored path stays so the next turn recreates the folder, empty. + yield* Effect.logInfo("storage cleanup removed scratch folder", { + threadId: thread.id, + }); + }), + ); + } const pathReason = yield* worktreePathReason(worktreePath); if (pathReason !== null) return keep(pathReason); if (yield* containsProjectRoot(worktreePaths, [project, ...snapshot.projects])) @@ -1400,98 +1587,6 @@ const make = Effect.gen(function* () { } if (!eligible) return keep(unpublished ? "has commits not on a remote-tracking ref" : notDueReason); - // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds. - const blockedSinceCheck = Effect.fnUntraced(function* () { - const latestProjects = yield* projectStore.listShells(); - if (yield* containsProjectRoot(worktreePaths, [project, ...latestProjects])) - return "contains a project checkout"; - const bindings = yield* projections.getThreadWorktreePaths({ includeArchived: true }); - const bindingKeys = yield* Effect.forEach(bindings, (binding) => - canonical(binding.worktreePath), - ); - const latest = bindings.filter((_binding, index) => bindingKeys[index] === worktreeKey); - if (yield* hasTerminal(worktreePaths)) return waitForStop("open terminal"); - if (deleted) { - if ( - !resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId) - .worktreeOnDelete - ) - return "thread or cleanup settings changed since check"; - // Durable deletion cleanup must succeed or be explicitly cancelled before removing its checkout. - const pendingCleanup = yield* sql<{ status: string }>` - SELECT status FROM orchestration_v2_effect_outbox - WHERE thread_id = ${thread.id} AND status NOT IN ('succeeded', 'cancelled') - `.pipe(NodeSqliteClient.readOnly); - // Failed effects never retry, so only running work can finish and free the path. - if (pendingCleanup.some((row) => row.status !== "failed")) - return waitForStop("thread deletion is still pending"); - if (pendingCleanup.length > 0) return "thread deletion is still pending"; - } - const latestShells = yield* Effect.forEach(latest, (entry) => - projections.getThreadShell(entry.threadId), - ); - const latestGroup = latestShells.filter((shell) => shell !== null); - const latestKeys = yield* Effect.forEach(latestGroup, (shell) => - shell.worktreePath === null ? Effect.succeed(null) : canonical(shell.worktreePath), - ); - const latestOwner = worktreeOwner(deleted ? [thread, ...latestGroup] : latestGroup); - if ( - latestGroup.length !== group.length || - latestOwner?.id !== thread.id || - latestOwner?.branch !== thread.branch || - latestGroup.some((shell, index) => { - const previous = group.find((member) => member.id === shell.id); - return ( - previous === undefined || - shell.branch !== previous.branch || - !Equal.equals(shell.settledAt, previous.settledAt) || - (shell.settledAt !== null && !Equal.equals(shell.updatedAt, previous.updatedAt)) || - !storageCleanupThreadIdle(shell, now, serverSettings) || - latestKeys[index] !== worktreeKey || - storageCleanupActivityAt(shell) !== storageCleanupActivityAt(previous) - ); - }) - ) - return waitForStop("thread activity or shared worktree changed since check"); - if (settlementChain.length > 1) { - const ancestors = yield* Effect.forEach(settlementChain.slice(1), (ancestor) => - projections.getThreadShell(ancestor.id), - ); - const latestSettlement = worktreeSettlementChain( - latestGroup.find((shell) => shell.id === thread.id)!, - new Map( - [...latestGroup, ...ancestors.filter((ancestor) => ancestor !== null)].map( - (ancestor) => [ancestor.id, ancestor], - ), - ), - now, - serverSettings, - ).at(-1); - if ( - latestSettlement?.id !== settledThread?.id || - !Equal.equals(latestSettlement?.settledAt, settledThread?.settledAt) || - !Equal.equals(latestSettlement?.updatedAt, settledThread?.updatedAt) - ) - return "parent settlement changed since check"; - } - // Sessions can outlive their run and can be shared across app threads. - const sessionRows = yield* sql<{ payload_json: string }>` - SELECT payload_json FROM orchestration_v2_projection_provider_sessions - WHERE status != 'stopped' - `.pipe(NodeSqliteClient.readOnly); - const sessions = yield* Effect.forEach(sessionRows, (row) => - decodeCleanupSession(row.payload_json), - ); - // Ready persisted sessions may have released their runtime; only live sessions protect the path. - for (const session of sessions) { - if ( - (yield* occupies(worktreePaths, session.cwd)) && - (yield* providerSessions.isLive(session.id)) - ) - return waitForStop("provider session is still open"); - } - return null; - }); const blocked = yield* blockedSinceCheck(); if (blocked !== null) return keep(blocked); // Inspect before the lease; provider startup must not wait for directory traversal. @@ -1516,15 +1611,7 @@ const make = Effect.gen(function* () { return keep("commit changed since check"); const finalChanges = yield* localChangesReason(worktreePath, settings); if (finalChanges !== null) return keep(finalChanges); - const currentSettings = yield* settingsService.getSettings; - const current = resolveWorktreeCleanup(currentSettings, thread.projectId); - if ( - currentSettings.autoResumeLimitedThreads !== - serverSettings.autoResumeLimitedThreads || - currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads || - !sameCleanupRules(current, settings) - ) - return keep("settings changed since check"); + if (yield* settingsChangedSinceCheck) return keep("settings changed since check"); // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check. if (settings.worktreeKeepWhen === "tracked-changes") yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); @@ -1601,6 +1688,7 @@ const make = Effect.gen(function* () { roots, yield* projectStore.list({ includeDeleted: true }), entries, + scratchRoot, ); return { waiting, kept }; }); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index eb27174d5ed6d..da37b82144ac0 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -13,6 +13,8 @@ import { ProviderDriverKind, ProviderInstanceId, retainedTerminalHistory, + terminalSequenceEnd, + terminalSequenceStateAfter, TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -337,7 +339,6 @@ function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): s if (terminated) lines.pop(); const retained = lines.slice(Math.max(0, lines.length - maxLines)).join("\n"); const capped = terminated ? `${retained}\n` : retained; - if (Buffer.byteLength(capped) <= maxBytes) return capped; const points = Array.from(capped); let start = points.length; let bytes = 0; @@ -347,7 +348,11 @@ function retainedHistory(text: string, maxLines: number, maxBytes = Infinity): s bytes += next; start -= 1; } - return points.slice(start).join(""); + const kept = points.slice(start).join(""); + if (maxLines <= 0 || maxBytes <= 0) return kept; + // A cut inside a control sequence drops the rest of that sequence too. + const state = terminalSequenceStateAfter(0, text, 0, text.length - kept.length); + return kept.slice(terminalSequenceEnd(state, kept)); } it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequences, and clear", () => { @@ -365,6 +370,10 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen "\u001b[31m", "\u001b[0m", "\u001b]8;;url\u0007", + "\u001b]0;", + "\u001bP", + "\u0007", + "\u001b\\", "\ud83d", "\ude80", ]; @@ -375,7 +384,8 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen for (const maxBytes of [0, 3, 8, 64, Infinity]) { for (const maxLines of [0, 1, 3, 5, 5_000]) { - let expected = retainedHistory("before\ninitial\n", maxLines, maxBytes); + let full = "before\ninitial\n"; + let expected = retainedHistory(full, maxLines, maxBytes); const history = new TerminalManager.BoundedTerminalHistory( maxLines, "before\ninitial\n", @@ -386,18 +396,33 @@ it("preserves line and byte limits across arbitrary chunks, Unicode, ANSI sequen for (let step = 0; step < 300; step += 1) { if (step % 73 === 0) { history.clear(); - expected = ""; - expect(history.value()).toBe(expected); + full = ""; + expect(history.value()).toBe(""); } const chunk = nextFragment() + nextFragment(); history.append(chunk); - expected = retainedHistory(expected + chunk, maxLines, maxBytes); + full += chunk; + expected = retainedHistory(full, maxLines, maxBytes); expect(history.value()).toBe(expected); } } } }); +it("does not retain the tail of a control sequence whose introducer was trimmed", () => { + for (const [text, maxBytes, retained] of [ + ["prefix\u001b[31mOK", 6, "OK"], + ["prefix\u001b]0;HIDDEN\u0007OK", 10, "OK"], + ["prefix\u001b]0;🙂HIDDEN\u0007OK", 9, "OK"], + // libghostty leaves every string but OSC at the emoji's second byte, so HELLO was visible. + ["prefix\u001bP🙂HELLO\u001b\\OK", 9, "HELLO\u001b\\OK"], + ] as const) { + expect(new TerminalManager.BoundedTerminalHistory(5_000, text, maxBytes).value()).toBe( + retained, + ); + } +}); + it("bounds long partial lines and joins surrogate pairs across chunk boundaries", () => { const maxBytes = 65_539; let expected = ""; @@ -1172,6 +1197,24 @@ it.layer( }), ); + it.effect("restores a log tail that starts inside a control sequence without its remainder", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + for (const [persisted, restored] of [ + ["\u001b]0;x\u0007ABCD", "ABCD"], + ["名\u001b]0;名\u0007ABCD", "ABCD"], + ["\u001b]0;x\u0007\u001b[31mABCD", "ABCD"], + ] as const) { + const { manager, logsDir } = yield* createManager(5, { historyByteLimit: 8 }); + const path = yield* historyLogPath(logsDir); + yield* fs.makeDirectory(logsDir, { recursive: true }); + yield* fs.writeFileString(path, persisted); + expect((yield* manager.open(openInput())).history).toBe(restored); + expect(yield* fs.readFileString(path)).toBe(restored); + } + }), + ); + it.effect("persists small terminal updates without rewriting the retained history", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -1426,6 +1469,15 @@ it.layer( { name: "NUL in DECRQM", data: "A\u001b[?2026\u0000$pB", history: "AB" }, { name: "CR in DSR", data: "AB\u001b[5\rnC", history: "AB\rC" }, { name: "DLE in DSR", data: "AB\u001b[5\u0010nC", history: "ABC" }, + // Ghostty reads non-ASCII there as UTF-8 bytes: it drops é and runs 0x80-0x9F as C1 controls. + { name: "é in DA", data: "A\u001b[0écB", history: "AB" }, + { name: "DECID byte in a CSI", data: "A\u001b[嚠B", history: "A\ufffdB" }, + { + name: "C1 DCS then C1 CSI in DSR", + data: "A\u001b[\u0090\u009b6nB", + history: "A\u001bP\u009cB", + }, + { name: "ESC in DSR", data: "A\u001b[5\u001b[6nB", history: "AB" }, ])( "strips a query with an embedded control but keeps what the terminal ran ($name)", ({ data, history }) => @@ -1441,6 +1493,19 @@ it.layer( }), ); + // Ghostty aborts a CSI at a non-ASCII code point and prints it and what follows. + it.effect("keeps a CSI interrupted by non-ASCII text in history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + ptyAdapter.processes[0]!.emitData("A\u001b[界nB"); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + expect(reopened.history.split("\u001b[?1049h")[0]).toBe("A\u001b[界nB"); + }), + ); + it.effect.each([ { name: "OSC", sequence: "\u001b]0;unfinished" }, { name: "DCS", sequence: "\u001bPunfinished" }, diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index dd06f5f516959..b9a279666e8fd 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -6,6 +6,9 @@ import { DEFAULT_TERMINAL_ID, DEFAULT_MAX_TERMINAL_BUFFER_BYTES, retainedTerminalHistory, + TERMINAL_SEQUENCE_GROUND, + terminalSequenceEnd, + terminalSequenceStateAfter, TerminalCwdError, TerminalCwdNotDirectoryError, TerminalCwdNotFoundError, @@ -888,6 +891,14 @@ interface TerminalHistoryPersistenceCursor { readonly fileBytes: number; } +function countLineBreaks(data: string): number { + let lineBreaks = 0; + for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { + lineBreaks += 1; + } + return lineBreaks; +} + export class BoundedTerminalHistory { private readonly maxLines: number; private readonly maxBytes: number; @@ -897,6 +908,8 @@ export class BoundedTerminalHistory { private lineBreaks = 0; // Reading the old string's tail on each append can force chunk concatenation. private lastCodeUnit: number | undefined; + // The terminal parser's state at the first retained code unit, which is where a replay starts. + private sequenceState = TERMINAL_SEQUENCE_GROUND; private cachedValue: string | null = ""; private generation = 0; private appendedLength = 0; @@ -961,10 +974,7 @@ export class BoundedTerminalHistory { private appendChunk(data: string): void { const byteLength = Buffer.byteLength(data); - let lineBreaks = 0; - for (let index = data.indexOf("\n"); index !== -1; index = data.indexOf("\n", index + 1)) { - lineBreaks += 1; - } + const lineBreaks = countLineBreaks(data); const previous = this.chunks.at(-1); if (previous && previous.data.length + data.length <= MAX_HISTORY_CHUNK_LENGTH) { previous.data += data; @@ -981,6 +991,7 @@ export class BoundedTerminalHistory { private discardChunk(): void { const first = this.chunks[this.start]!; + this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data); this.byteLength -= first.byteLength; this.lineBreaks -= first.lineBreaks; this.chunks[this.start++] = undefined; @@ -992,6 +1003,7 @@ export class BoundedTerminalHistory { this.discardChunk(); return; } + this.sequenceState = terminalSequenceStateAfter(this.sequenceState, first.data, 0, offset); first.data = first.data.slice(offset); first.byteLength -= byteLength; first.lineBreaks -= lineBreaks; @@ -1039,6 +1051,12 @@ export class BoundedTerminalHistory { } this.trimChunk(offset, bytes, lineBreaks); } + // A cut inside a control sequence would replay the rest of it as text. + while (this.sequenceState !== TERMINAL_SEQUENCE_GROUND && this.start < this.chunks.length) { + const first = this.chunks[this.start]!; + const dropped = first.data.slice(0, terminalSequenceEnd(this.sequenceState, first.data)); + this.trimChunk(dropped.length, Buffer.byteLength(dropped), countLineBreaks(dropped)); + } if ( this.start === this.chunks.length || (this.start > 2_048 && this.start * 2 >= this.chunks.length) @@ -1057,6 +1075,7 @@ export class BoundedTerminalHistory { this.byteLength = 0; this.lineBreaks = 0; this.lastCodeUnit = undefined; + this.sequenceState = TERMINAL_SEQUENCE_GROUND; this.cachedValue = ""; } @@ -1194,18 +1213,70 @@ function stripStringTerminator(value: string): string { return value; } -// BEL ends only OSC; inside DCS, PM and APC it is payload. A decoded U+009C is the -// reverse: libghostty keeps it inside OSC but ends the other strings there. -function findStringTerminatorIndex(input: string, start: number, isOsc: boolean): number | null { +interface C1Effect { + /** ESC form of the sequence the code point starts, or "" when it returns to ground. */ + readonly next: string; + /** Its 0x9A byte ran DECID, which replies with device attributes. */ + readonly query: boolean; + /** What replays its visible effect from ground. */ + readonly safe: string; +} + +// Outside ground and OSC, libghostty parses a code point's UTF-8 bytes one at a time: 0x80-0x9F +// act as C1 controls, the rest are dropped. Bytes left over after a return to ground print U+FFFD. +function c1Effect(codePoint: number): C1Effect | undefined { + // A lone surrogate is encoded as U+FFFD, whose bytes are all dropped. + if (codePoint >= 0xd800 && codePoint <= 0xdfff) return undefined; + let next: string | undefined; + let query = false; + let safe = ""; + for (let shift = codePoint > 0xffff ? 12 : codePoint > 0x7ff ? 6 : 0; shift >= 0; shift -= 6) { + const byte = 0x80 | ((codePoint >> shift) & 0x3f); + if (next === "") { + safe += "\ufffd"; + } else if (next?.startsWith("\u001b]")) { + next += "\ufffd"; + } else if (byte === 0x9b) { + next = "\u001b["; + } else if (byte === 0x9d) { + next = "\u001b]"; + } else if (byte === 0x90) { + next = "\u001bP"; + } else if (byte === 0x98 || byte === 0x9e || byte === 0x9f) { + next = "\u001b_"; + } else if (byte < 0xa0) { + next = ""; + query = byte === 0x9a; + // Any other C1 control but ST runs as ESC plus the byte less 0x40. + safe = query || byte === 0x9c ? "" : `\u001b${String.fromCharCode(byte - 0x40)}`; + } + } + return next === undefined ? undefined : { next, query, safe }; +} + +// BEL ends only OSC; inside DCS, PM and APC it is payload. Non-ASCII is the reverse: libghostty +// keeps it inside OSC, while a C1 byte in it ends the other strings. +function findStringEnd( + input: string, + start: number, + isOsc: boolean, +): { end: number; c1?: { effect: C1Effect; index: number } } | null { for (let index = start; index < input.length; index += 1) { const codePoint = input.charCodeAt(index); - if ((isOsc ? codePoint === 0x07 : codePoint === 0x9c) || isControlSequenceCancel(codePoint)) { - return index + 1; + if ((isOsc && codePoint === 0x07) || isControlSequenceCancel(codePoint)) { + return { end: index + 1 }; } // Like xterm.js, an ESC that does not start ST ends the string and begins the next sequence. if (codePoint === 0x1b) { if (index + 1 >= input.length) return null; - return input.charCodeAt(index + 1) === 0x5c ? index + 2 : index; + return { end: input.charCodeAt(index + 1) === 0x5c ? index + 2 : index }; + } + if (codePoint >= 0x80 && !isOsc) { + const fullCodePoint = input.codePointAt(index) ?? codePoint; + const end = index + (fullCodePoint > 0xffff ? 2 : 1); + const effect = c1Effect(fullCodePoint); + if (effect) return { end, c1: { effect, index } }; + index = end - 1; } } return null; @@ -1251,6 +1322,8 @@ function sanitizeTerminalHistoryChunk( const pendingScanStart = Math.max(0, pendingControlSequence.length - 1); let visibleText = ""; let index = 0; + // Set when a C1 code point began the sequence at `index`: the ESC form that stands in for it. + let c1Introducer = ""; const append = (value: string) => { visibleText += value; @@ -1259,14 +1332,18 @@ function sanitizeTerminalHistoryChunk( while (index < input.length) { const codePoint = input.charCodeAt(index); - if (codePoint === 0x1b) { - const nextCodePoint = input.charCodeAt(index + 1); + if (c1Introducer.length > 0 || codePoint === 0x1b) { + // Empty for a sequence the input introduces itself, which starts with ESC at `index`. + const prefix = c1Introducer; + c1Introducer = ""; + const contentStart = prefix.length > 0 ? index : index + 2; + const nextCodePoint = (prefix || input).charCodeAt(prefix.length > 0 ? 1 : index + 1); if (Number.isNaN(nextCodePoint)) { return { visibleText, pendingControlSequence: input.slice(index) }; } if (nextCodePoint === 0x5b) { - let cursor = index + 2; + let cursor = contentStart; // Inside a CSI Ghostty executes 0x00-0x0F and ignores DEL and 0x10-0x1F, which it would // print in ground state. None join the parameters; only executed ones survive a strip. let body = ""; @@ -1276,25 +1353,47 @@ function sanitizeTerminalHistoryChunk( const cancelled = isControlSequenceCancel(cursorCodePoint); if (cancelled || isCsiFinalByte(cursorCodePoint)) { if (cancelled || !shouldStripCsiSequence(body, input[cursor] ?? "")) { - append(input.slice(index, cursor + 1)); + append(prefix + input.slice(index, cursor + 1)); } else { append(executedControls); } index = cursor + 1; break; } + if (cursorCodePoint >= 0x80) { + const fullCodePoint = input.codePointAt(cursor) ?? cursorCodePoint; + const end = cursor + (fullCodePoint > 0xffff ? 2 : 1); + const c1 = c1Effect(fullCodePoint); + if (c1) { + // The CSI ends here undispatched, so it is kept only when the terminal is back in + // ground with nothing to answer. + if (c1.next.length === 0 && !c1.query) { + append(prefix + input.slice(index, end)); + } else { + append(executedControls + c1.safe); + } + c1Introducer = c1.next; + index = end; + break; + } + cursor = end; + continue; + } + // An ESC abandons the CSI and starts the next sequence, which may be stripped. + if (cursorCodePoint === 0x1b) { + append(executedControls); + index = cursor; + break; + } if (cursorCodePoint < 0x10) { executedControls += input[cursor]; - } else if ( - (cursorCodePoint >= 0x20 || cursorCodePoint === 0x1b) && - cursorCodePoint !== 0x7f - ) { + } else if (cursorCodePoint >= 0x20 && cursorCodePoint !== 0x7f) { body += input[cursor]; } cursor += 1; } if (cursor >= input.length) { - return { visibleText, pendingControlSequence: input.slice(index) }; + return { visibleText, pendingControlSequence: prefix + input.slice(index) }; } continue; } @@ -1305,23 +1404,32 @@ function sanitizeTerminalHistoryChunk( nextCodePoint === 0x5e || nextCodePoint === 0x5f ) { - const terminatorIndex = findStringTerminatorIndex( + const stringEnd = findStringEnd( input, - Math.max(index + 2, pendingScanStart), + Math.max(contentStart, pendingScanStart), nextCodePoint === 0x5d, ); - if (terminatorIndex === null) { - return { visibleText, pendingControlSequence: input.slice(index) }; + if (stringEnd === null) { + return { visibleText, pendingControlSequence: prefix + input.slice(index) }; } - const sequence = input.slice(index, terminatorIndex); - const content = stripStringTerminator(input.slice(index + 2, terminatorIndex)); + const { end, c1 } = stringEnd; + const content = stripStringTerminator( + prefix.slice(2) + input.slice(contentStart, c1?.index ?? end), + ); const strip = (nextCodePoint === 0x5d && shouldStripOscSequence(content)) || (nextCodePoint === 0x50 && shouldStripDcsSequence(content)); - if (!strip) { - append(sequence); + if (c1 === undefined || (!strip && c1.effect.next.length === 0 && !c1.effect.query)) { + if (!strip) { + append(prefix + input.slice(index, end)); + } + } else { + // ST stands in for a code point that cannot be replayed as it came. + const closed = strip ? "" : `${prefix}${input.slice(index, c1.index)}\u009c`; + append(closed + c1.effect.safe); + c1Introducer = c1.effect.next; } - index = terminatorIndex; + index = end; continue; } @@ -1344,7 +1452,7 @@ function sanitizeTerminalHistoryChunk( index = nextSequenceStart; } - return { visibleText, pendingControlSequence: "" }; + return { visibleText, pendingControlSequence: c1Introducer }; } function legacySafeThreadId(threadId: string): string { @@ -2087,6 +2195,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func const info = yield* file.stat; const limit = BigInt(historyByteLimit); const offset = info.size > limit ? info.size - limit : 0n; + // The tail can start inside a control sequence; only the bytes before it say which. + const decoder = new TextDecoder("utf-8", { ignoreBOM: true }); + let sequenceState = TERMINAL_SEQUENCE_GROUND; + const skipped = new Uint8Array(Math.min(Number(offset), 64 * 1024)); + for (let remaining = Number(offset); remaining > 0;) { + const read = Number(yield* file.read(skipped.subarray(0, remaining))); + if (read === 0) break; + remaining -= read; + sequenceState = terminalSequenceStateAfter( + sequenceState, + decoder.decode(skipped.subarray(0, read), { stream: true }), + ); + } yield* file.seek(offset, "start"); const bytes = new Uint8Array(Number(info.size - offset)); let length = 0; @@ -2100,8 +2221,15 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func // A tail read can start inside a UTF-8 code point. Skip its remaining bytes. while (start < length && ((bytes[start] ?? 0) & 0xc0) === 0x80) start += 1; } + sequenceState = terminalSequenceStateAfter( + sequenceState, + decoder.decode(bytes.subarray(0, start)), + ); + const history = new TextDecoder("utf-8", { ignoreBOM: true }).decode( + bytes.subarray(start, length), + ); return { - history: new TextDecoder("utf-8", { ignoreBOM: true }).decode(bytes.subarray(start, length)), + history: history.slice(terminalSequenceEnd(sequenceState, history)), truncated: offset > 0n, }; }); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index ae5c32bf57432..e6e43d606e27f 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -58,6 +58,7 @@ interface FakeCodexInput { mcpServers?: ReadonlyArray<{ name: string; enabled: boolean }> | number; requiredCwd?: string; requireInstructions?: string; + requireMcpServersOff?: ReadonlyArray; } function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { @@ -73,6 +74,7 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { mcpServers: input.mcpServers ?? [], requiredCwd: input.requiredCwd ?? null, requireInstructions: input.requireInstructions ?? null, + requireMcpServersOff: input.requireMcpServersOff ?? [], stderr: input.stderr ?? null, output: input.output, exitCode: input.exitCode ?? 0, @@ -129,6 +131,33 @@ function makeFakeCodexBinary(dir: string, input: FakeCodexInput) { ' process.stderr.write(message + "\\n");', " process.exit(code);", "}", + "// Like Codex: a later mcp_servers={...} override replaces servers earlier -c flags defined.", + "const servers = new Map();", + "const offServers = new Set();", + "for (let index = 0; index < args.length; index += 1) {", + ' if (args[index] !== "-c" && args[index] !== "--config") continue;', + ' const value = args[index + 1] ?? "";', + ' if (value.startsWith("mcp_servers={")) {', + ' const named = [...value.matchAll(/"([^"]+)"=\\{enabled=false\\}/g)].map((match) => match[1]);', + " for (const name of named) offServers.add(name);", + " for (const name of [...servers.keys()]) {", + " if (named.includes(name)) servers.set(name, false);", + " else servers.delete(name);", + " }", + ' } else if (value.startsWith("mcp_servers.")) {', + ' const [name, key] = value.slice("mcp_servers.".length).split(/[.=]/);', + " if (value === `mcp_servers.${name}.enabled=false`) offServers.add(name);", + " // An enabled flag alone toggles a server another layer (config.toml) defines.", + ' if (key === "enabled" && !servers.has(name)) continue;', + ' servers.set(name, servers.get(name) === true || key === "url" || key === "command");', + " }", + "}", + "for (const [name, hasTransport] of servers) {", + ' if (!hasTransport) fail("Error loading config.toml: invalid transport in `mcp_servers." + name + "`", 12);', + "}", + "for (const name of check.requireMcpServersOff) {", + ' if (!offServers.has(name)) fail("MCP server left on: " + name, 13);', + "}", 'if (check.requiredCwd !== null && process.cwd() !== check.requiredCwd) fail("cannot inspect checkout", 10);', 'if (check.requireInstructions !== null && !instructions.includes(check.requireInstructions)) fail("missing writer task", 11);', "if (check.requireArg !== null && !originalArgs.includes(` ${check.requireArg} `)) {", @@ -365,7 +394,7 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { { name: "already-off", enabled: false }, ], requireArg: - '--config features.plugins=false --config features.apps=false --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}}', + 'exec --config mcp_servers={"augmenter"={enabled=false},"my.server"={enabled=false}} --config developer_instructions="Use', }, (textGeneration) => Effect.gen(function* () { @@ -384,6 +413,52 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); + it.effect("turns off an MCP server that launch args define without dropping its transport", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Remove default shapes" }), + launchArgs: `-c 'mcp_servers.t3-code.url="http://127.0.0.1:1/mcp"' -c 'mcp_servers.t3-code.enabled=true'`, + mcpServers: [{ name: "t3-code", enabled: true }], + requireMcpServersOff: ["t3-code"], + requireArg: + "--config features.apps=false --config mcp_servers.t3-code.enabled=false --ephemeral", + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Remove default shapes from characters", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Remove default shapes"); + }), + ), + ); + + it.effect("keeps MCP servers off when launch args set their own mcp_servers table", () => + withFakeCodexEnv( + { + output: JSON.stringify({ title: "Remove default shapes" }), + launchArgs: `-c 'mcp_servers={"my.server"={command="echo",enabled=true}}'`, + mcpServers: [ + { name: "my.server", enabled: true }, + { name: "my server", enabled: true }, + ], + requireArg: + '--config features.apps=false --config mcp_servers={"my.server"={enabled=false},"my server"={enabled=false}} --config mcp_servers.my server.enabled=false --ephemeral', + }, + (textGeneration) => + Effect.gen(function* () { + const result = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Remove default shapes from characters", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + expect(result.title).toBe("Remove default shapes"); + }), + ), + ); + it.effect("still generates when Codex cannot list its MCP servers", () => withFakeCodexEnv( { diff --git a/apps/server/src/textGeneration/CodexTextGeneration.ts b/apps/server/src/textGeneration/CodexTextGeneration.ts index 4de5392502c8c..49c60166111ba 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.ts @@ -55,6 +55,11 @@ const codexMcpServersOff = (names: ReadonlyArray): string | null => names.length === 0 ? null : `mcp_servers={${names.map((name) => `${JSON.stringify(name)}={enabled=false}`).join(",")}}`; +// Codex splits -c keys at the first "=" and on every dot, so only those names take a dotted flag. +const codexMcpServerOffFlags = (names: ReadonlyArray) => + names + .filter((name) => !name.includes(".") && !name.includes("=")) + .flatMap((name) => ["--config", `mcp_servers.${name}.enabled=false`]); const encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(function* ( codexConfig: CodexSettings, @@ -291,20 +296,28 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func } : {}), }; - const mcpServersOff = yield* listEnabledMcpServers({ + const enabledMcpServers = yield* listEnabledMcpServers({ binary, cwd, env, launchArgs: codexMcpListLaunchArgs(launchArgs), - }).pipe(Effect.map(codexMcpServersOff)); + }); + const mcpServersOff = codexMcpServersOff(enabledMcpServers); + const execLaunchArgs = codexExecLaunchArgs(launchArgs); + // A launch-arg mcp_servers={...} table replaces ours and can re-enable dotted names. + const launchArgsSetMcpTable = execLaunchArgs.some((arg) => /\bmcp_servers\s*=/.test(arg)); const spawnCommand = yield* resolveSpawnCommand( binary, [ "exec", - ...codexExecLaunchArgs(launchArgs), + // Before launch args: a later table would replace servers their -c flags define. + ...(mcpServersOff ? ["--config", mcpServersOff] : []), + ...execLaunchArgs, // A user's MCP server could act on the text-generation prompt. ...CODEX_NO_PLUGIN_ARGS, - ...(mcpServersOff ? ["--config", mcpServersOff] : []), + ...(mcpServersOff && launchArgsSetMcpTable ? ["--config", mcpServersOff] : []), + // After launch args, so a launch arg's enabled=true cannot turn a server back on. + ...codexMcpServerOffFlags(enabledMcpServers), "--ephemeral", "--skip-git-repo-check", "-s", diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts index ae3e468d099e4..d7e73a1da96c9 100644 --- a/apps/server/src/usage/UsageLimitSources.test.ts +++ b/apps/server/src/usage/UsageLimitSources.test.ts @@ -1,11 +1,21 @@ import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import { expect, it } from "@effect/vitest"; -import { SecretProviderId, ServerConfigStreamEvent, UsageLimitSourceId } from "@t3tools/contracts"; +import { + ProviderDriverKind, + SecretProviderId, + ServerConfigStreamEvent, + UsageLimitSourceId, + type ServerProviderUsageWindow, + type UsageLimitSourceSnapshot, +} from "@t3tools/contracts"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; @@ -26,6 +36,14 @@ it.effect("keeps malformed source URLs encodable for config subscribers", () => "hub.test:8317", "Usage limit source", ]); + // Only an http(s) hub URL names an endpoint an agent can be sent to. + expect(snapshots.map((source) => source.origin)).toEqual([ + undefined, + undefined, + undefined, + "https://hub.test:8317", + undefined, + ]); expect(() => encodeConfigEvent({ version: 1, @@ -155,3 +173,135 @@ it.effect("reads a management key from its secret provider", () => { ]), ); }); + +const NOW = Date.parse("2026-11-13T12:00:00.000Z"); +const at = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(NOW + hours * 3_600_000)); +const spent = (id: string, hours: number): ServerProviderUsageWindow => ({ + id, + kind: "weekly", + label: id, + usedPercent: 100, + resetsAt: at(hours), +}); +const hub = ( + accounts: ReadonlyArray<{ + driver?: string; + windows?: ReadonlyArray; + unavailable?: true; + }>, +): UsageLimitSourceSnapshot => ({ + id: UsageLimitSourceId.make("hub"), + kind: "cliproxy", + label: "hub", + checkedAt: at(0), + accounts: accounts.map((account, index) => ({ + id: `account-${index}`, + driver: ProviderDriverKind.make(account.driver ?? "claudeAgent"), + usageLimits: { + checkedAt: at(0), + windows: account.windows ?? [], + ...(account.unavailable ? { unavailable: { reason: "probeFailed" as const } } : {}), + }, + })), +}); + +it.each([ + { + name: "earliest refill when every account is spent, each at its latest spent window", + accounts: [ + { windows: [spent("five_hour", 1), spent("seven_day", 3)] }, + { windows: [spent("five_hour", 2)] }, + { driver: "codex", windows: [] }, + ], + model: "claude-haiku-5-5", + expected: at(2), + }, + { + name: "unknown while an account still has room", + accounts: [{ windows: [spent("five_hour", 1)] }, { windows: [] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "unknown while an account could not be read", + accounts: [{ windows: [spent("five_hour", 1)] }, { unavailable: true as const }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "unknown when a spent window has no reset or already reset", + accounts: [{ windows: [{ ...spent("five_hour", 1), resetsAt: undefined }] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "a model-scoped weekly window blocks only its own model", + accounts: [{ windows: [spent("seven_day_fable", 5)] }], + model: "claude-haiku-5-5", + expected: null, + }, + { + name: "a model-scoped weekly window blocks its own model", + accounts: [{ windows: [spent("seven_day_fable", 5)] }], + model: "claude-fable-5-2", + expected: at(5), + }, + { + name: "no account of the driver", + accounts: [{ driver: "codex", windows: [spent("five_hour", 1)] }], + model: "claude-haiku-5-5", + expected: null, + }, +])("hub pool reset: $name", ({ accounts, model, expected }) => { + expect( + UsageLimitSources.hubPoolResetAt( + [hub(accounts)], + ProviderDriverKind.make("claudeAgent"), + model, + NOW, + ), + ).toBe(expected); +}); + +it.effect("the reset fallback refreshes its hub, and a stalled hub cannot hold the failure", () => + Effect.gen(function* () { + yield* TestClock.setTime(NOW); + const roomLeft = { ...hub([{ windows: [spent("five_hour", 2)] }]), origin: "http://hub.test" }; + const cached = { + ...roomLeft, + accounts: roomLeft.accounts.map((account) => ({ + ...account, + usageLimits: { + ...account.usageLimits, + windows: account.usageLimits.windows.map((window) => ({ ...window, usedPercent: 99 })), + }, + })), + }; + let current: ReadonlyArray = [cached]; + let refresh: Effect.Effect = Effect.sync(() => { + current = [roomLeft]; + }); + const lookup = UsageLimitSources.UsageLimitResetFallback.pipe( + Effect.flatMap((fallback) => + fallback.resetAt(ProviderDriverKind.make("claudeAgent"), "http://hub.test", null), + ), + Effect.provide( + UsageLimitSources.layerResetFallback.pipe( + Layer.provide( + Layer.mock(UsageLimitSources.UsageLimitSources)({ + current: Effect.sync(() => current), + refresh: Effect.suspend(() => refresh), + }), + ), + ), + ), + ); + // The last poll saw room; the account was spent after it. + expect(yield* lookup).toBe(at(2)); + current = [cached]; + refresh = Effect.never; + const stalled = yield* Effect.forkChild(lookup); + yield* TestClock.adjust("5 seconds"); + expect(yield* Fiber.join(stalled)).toBeNull(); + }), +); diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts index 7d40b0fb9ecea..c591931843411 100644 --- a/apps/server/src/usage/UsageLimitSources.ts +++ b/apps/server/src/usage/UsageLimitSources.ts @@ -3,6 +3,7 @@ import { UsageLimitSourceError, type UsageLimitSourceConsumeResetCreditInput, type ProviderConsumeResetCreditResult, + type ProviderDriverKind, type ServerSettings, UsageLimitSourceConfig, settingsSecretLiteral, @@ -26,6 +27,7 @@ import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretReso import * as SecretResolverLayer from "../secrets/SecretResolver.ts"; import { resolveSettingsSecrets } from "../secrets/settingsSecretValue.ts"; import * as Settings from "../serverSettings.ts"; +import { windowLimitsModel } from "../provider/claudeUsageLimits.ts"; import { makeCliproxyApi } from "./cliproxyApi.ts"; export class UsageLimitSources extends Context.Service< @@ -79,7 +81,14 @@ export const make = Effect.gen(function* () { config: UsageLimitSourceConfig, ) { const checkedAt = DateTime.formatIso(yield* DateTime.now); - const base = { id, kind: config.kind, label: sourceLabel(id, config), checkedAt } as const; + const url = URL.parse(config.url); + const base = { + id, + kind: config.kind, + label: sourceLabel(id, config), + ...(url && /^https?:$/.test(url.protocol) ? { origin: url.origin } : {}), + checkedAt, + } as const; const managementKey = yield* readManagementKey(config); if (managementKey.length === 0) { return { ...base, accounts: [], error: missingManagementKey(config) }; @@ -198,3 +207,64 @@ export const make = Effect.gen(function* () { export const layer = Layer.effect(UsageLimitSources, make).pipe( Layer.provide(SecretResolverLayer.layer), ); + +/** A hub answers with a usage limit only when every account it routes the driver to is spent. */ +export function hubPoolResetAt( + sources: ReadonlyArray, + driver: ProviderDriverKind, + model: string | null, + now: number, +): string | null { + let earliest: number | null = null; + for (const source of sources) { + for (const account of source.accounts) { + if (account.driver !== driver) continue; + // An unread account may be the one still blocked, so its refill is unknown. + if (account.usageLimits.unavailable) return null; + const spent = account.usageLimits.windows.filter( + (window) => window.usedPercent >= 100 && windowLimitsModel(window, model), + ); + if (spent.length === 0) return null; + const resets = spent.map((window) => Date.parse(window.resetsAt ?? "")); + if (resets.some((reset) => !Number.isFinite(reset))) return null; + const recoversAt = Math.max(...resets); + if (recoversAt <= now) return null; + earliest = earliest === null ? recoversAt : Math.min(earliest, recoversAt); + } + } + return earliest === null ? null : DateTime.formatIso(DateTime.makeUnsafe(earliest)); +} + +export class UsageLimitResetFallback extends Context.Reference<{ + readonly resetAt: ( + driver: ProviderDriverKind, + endpoint: string, + model: string | null, + ) => Effect.Effect; +}>("t3/usage/UsageLimitResetFallback", { + defaultValue: () => ({ resetAt: () => Effect.succeed(null) }), +}) {} + +export const layerResetFallback = Layer.effect( + UsageLimitResetFallback, + Effect.gen(function* () { + const sources = yield* UsageLimitSources; + return { + resetAt: Effect.fn("UsageLimitResetFallback.resetAt")(function* (driver, endpoint, model) { + // Only the hub at the instance's endpoint serves its turns. + const atEndpoint = Effect.map(sources.current, (current) => + current.filter((source) => source.origin === endpoint), + ); + if ((yield* atEndpoint).length === 0) return null; + // The pool usually ran out after the last poll, so the cached accounts still show room. + yield* sources.refresh.pipe(Effect.timeout("5 seconds"), Effect.ignore); + return hubPoolResetAt( + yield* atEndpoint, + driver, + model, + DateTime.toEpochMillis(yield* DateTime.now), + ); + }), + }; + }), +); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index 81f3d1ec289aa..dc3f7ac927147 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -3106,7 +3106,7 @@ describe("UsageService", () => { 60 + 20 * (version === 4 ? 1 : 2), ); yield* upgraded.awaitPersisted; - assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v15.json"); + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v16.json"); assert.deepStrictEqual( (yield* Effect.promise(() => NodeFSP.readdir(stateDir))) .filter((name) => name.startsWith("usage-scan-cache")) diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 84291da51a189..09348d5818a2e 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -285,6 +285,46 @@ describe("scan cache round trip", () => { ...codex(0), position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, }); + // The migrated entries persist without a state and load again under the current version. + expect(decodeScanCache(parse(makeScanCacheWriter()(restored, {})), TEST_FORMAT_MAP)).toEqual( + restored, + ); + }); + + it("restarts a grown v15 Codex entry, whose baseline time can be older than its totals", () => { + const request = { + input_tokens: 100, + cached_input_tokens: 0, + cache_write_input_tokens: 0, + output_tokens: 20, + reasoning_output_tokens: 0, + total_tokens: 120, + }; + const entry: CachedFile = { + size: 10, + mtimeMs: 100, + provider: "codex", + records: [record({ provider: "codex", model: "gpt-6-astra", dedupeKey: null })], + tailRecords: [], + malformedRecords: 0, + position: position({ + state: { + ...initialCodexScanState(), + model: "gpt-6-astra", + lastCumulativeUsage: request, + latestCumulativeAtMs: 1_786_000_000_000, + }, + }), + }; + const current = parse(makeScanCacheWriter()(new Map([["/codex.jsonl", entry]]), {})); + + expect( + decodeScanCache({ ...current, version: 15 }, TEST_FORMAT_MAP).get("/codex.jsonl"), + ).toEqual({ + ...entry, + position: { resumeOffset: 0, guardLength: 0, guardHash: 0, state: null }, + }); + expect(decodeScanCache(current, TEST_FORMAT_MAP).get("/codex.jsonl")).toEqual(entry); }); it("re-parses a Claude transcript cached before 1-hour cache writes were counted", () => { diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index b571dd3708f63..e75691d2b8465 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -10,7 +10,7 @@ import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; import { mergeUsageCopies } from "./usageAggregation.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 15 as const; +const USAGE_SCAN_CACHE_VERSION = 16 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -18,8 +18,9 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * the newer one; older files are removed once it is saved. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v15.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v16.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v15.json", "usage-scan-cache-v14.json", "usage-scan-cache-v13.json", "usage-scan-cache-v12.json", @@ -308,9 +309,10 @@ export function decodeScanCache( // A corrupt state disqualifies the entry: resuming with it would attach // appended usage to the wrong model or replay fork-copied history. if (!legacy && !isValidState.get(entry.p)?.(entry.cs)) continue; - // Before v15 the state lacks the latest snapshot time that keeps a re-emitted older snapshot - // from billing twice, so a grown file re-parses whole instead of resuming. - const resumable = !legacy && !(entry.p === "codex" && version < 15); + // Before v16 a Codex baseline can lack the time of its latest move, or carry an older one, + // and that time keeps a re-emitted older snapshot from billing twice. A grown file re-parses + // whole instead of resuming. + const resumable = !legacy && !(entry.p === "codex" && version < 16); const provider = entry.p; const records = decodeRecords(entry.r, provider); diff --git a/apps/server/src/vcs/GitVcsDriver.test.ts b/apps/server/src/vcs/GitVcsDriver.test.ts index 89580e0937af7..a8c0052452ed7 100644 --- a/apps/server/src/vcs/GitVcsDriver.test.ts +++ b/apps/server/src/vcs/GitVcsDriver.test.ts @@ -861,6 +861,63 @@ it.effect.each([1_700_000_000, 1_700_000_000.9999])( }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("a branch switch landing after the snapshot belongs to the next checkpoint", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-checkpoint-switch-race-" }); + const git = (args: ReadonlyArray) => + driver.execute({ operation: "checkpoint-test", cwd, args }); + yield* git(["init"]); + yield* git(["config", "user.name", "Test"]); + yield* git(["config", "user.email", "test@test.com"]); + yield* fileSystem.writeFileString(path.join(cwd, "f.txt"), "A\n"); + yield* git(["add", "."]); + yield* git(["commit", "-m", "a"]); + yield* git(["checkout", "-b", "b"]); + yield* fileSystem.writeFileString(path.join(cwd, "f.txt"), "B\n"); + yield* git(["commit", "-am", "b"]); + yield* git(["checkout", "-"]); + const [first, second, third] = ["1", "2", "3"].map((turn) => + CheckpointRef.make(`refs/t3/checkpoints/switch-race/${turn}`), + ) as [CheckpointRef, CheckpointRef, CheckpointRef]; + const racedDriver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: Effect.fn(function* (input: VcsProcess.VcsProcessInput) { + const result = yield* liveProcess.run(input); + if (input.args.includes("write-tree")) yield* git(["checkout", "b"]).pipe(Effect.orDie); + return result; + }), + }), + ); + const changedSince = (fromCheckpointRef: CheckpointRef, toCheckpointRef: CheckpointRef) => + Effect.gen(function* () { + const refs = { cwd, fromCheckpointRef, toCheckpointRef }; + return { + patch: yield* driver.checkpoints.diffCheckpoints({ ...refs, ignoreWhitespace: false }), + authored: yield* driver.checkpoints.listAuthoredPaths(refs), + }; + }); + + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef: first }); + yield* racedDriver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: second, + previousCheckpointRef: first, + }); + yield* driver.checkpoints.captureCheckpoint({ + cwd, + checkpointRef: third, + previousCheckpointRef: second, + }); + + assert.deepEqual(yield* changedSince(first, second), { patch: "", authored: null }); + assert.deepEqual(yield* changedSince(second, third), { patch: "", authored: null }); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + it.effect("checkpoint capture preserves racy edits made after resetting the index", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1051,6 +1108,7 @@ it.effect.each(["committed", "unborn"] as const)( assert.deepStrictEqual(commands, [ "rev-parse", + ...(head === "committed" ? ["log"] : []), "config", ...(head === "committed" ? ["read-tree", "ls-files"] : []), "add", @@ -1273,6 +1331,87 @@ it.effect("restores a checkpoint before the first commit without staging its fil }).pipe(Effect.scoped, Effect.provide(layerGitContract)), ); +it.effect("restores edits to skip-worktree files whose checkpoint content matches HEAD", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const driver = yield* GitVcsDriver.makeVcsDriverShape(); + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-skip-worktree-restore-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + const skippedPath = path.join(cwd, "skipped.txt"); + yield* fileSystem.writeFileString(skippedPath, "original\n"); + yield* git(["add", "skipped.txt"]); + yield* git(["commit", "-m", "add skipped file"]); + yield* git(["update-index", "--skip-worktree", "skipped.txt"]); + yield* driver.checkpoints.captureCheckpoint({ cwd, checkpointRef }); + yield* fileSystem.writeFileString(skippedPath, "later\n"); + + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ cwd, checkpointRef, fallbackToHead: false }), + ); + + assert.strictEqual(yield* fileSystem.readFileString(skippedPath), "original\n"); + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + +it.effect("sparse restore rewrites manual skip-worktree files and keeps exclusions absent", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const liveProcess = yield* VcsProcess.VcsProcess; + // One byte per chunk, so the index listing splits inside every record. + const driver = yield* GitVcsDriver.makeVcsDriverShape().pipe( + Effect.provideService(VcsProcess.VcsProcess, { + run: (input) => { + const onStdoutChunk = input.onStdoutChunk; + return liveProcess.run( + onStdoutChunk === undefined + ? input + : { + ...input, + onStdoutChunk: (chunk) => { + for (let index = 0; index < chunk.length; index++) + onStdoutChunk(chunk.subarray(index, index + 1)); + }, + }, + ); + }, + }), + ); + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sparse-restore-" }); + const { git, checkpointRef } = yield* makeCheckpointFixture(driver, cwd); + for (const name of ["in/normal", "in/skipped", "in/s space", "out/deep/absent", "out/stray"]) { + yield* fs.makeDirectory(path.dirname(path.join(cwd, name)), { recursive: true }); + yield* fs.writeFileString(path.join(cwd, name), "original\n"); + } + yield* git(["add", "."]); + yield* git(["commit", "-m", "sparse fixture"]); + yield* git(["sparse-checkout", "set", "--cone", "--sparse-index", "in"]); + // Keeps Git from clearing the bit on files that are present. + yield* git(["config", "sparse.expectFilesOutsideOfPatterns", "true"]); + yield* git(["update-index", "--skip-worktree", "in/skipped", "in/s space"]); + const captureCwd = path.join(cwd, "in"); + yield* driver.checkpoints.captureCheckpoint({ cwd: captureCwd, checkpointRef }); + yield* fs.writeFileString(path.join(cwd, "in/skipped"), "later\n"); + yield* fs.writeFileString(path.join(cwd, "in/s space"), "later\n"); + yield* fs.writeFileString(path.join(cwd, "in/normal"), "later\n"); + + for (const restoreCwd of [captureCwd, cwd]) { + assert.isTrue( + yield* driver.checkpoints.restoreCheckpoint({ + cwd: restoreCwd, + checkpointRef, + fallbackToHead: false, + }), + ); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/skipped")), "original\n"); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/s space")), "original\n"); + assert.strictEqual(yield* fs.readFileString(path.join(cwd, "in/normal")), "original\n"); + assert.isFalse(yield* fs.exists(path.join(cwd, "out"))); + } + }).pipe(Effect.scoped, Effect.provide(layerGitContract)), +); + // The real VCS process, spawning `command` wherever the driver runs git. const vcsProcessSpawning = (command: string) => Layer.effect( diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index ff0eac7c00093..4084e531f2302 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -458,6 +458,8 @@ export class GitVcsDriver extends Context.Service< input: VcsSwitchRefInput, ) => Effect.Effect; readonly initRepo: (input: VcsInitInput) => Effect.Effect; + /** Drops cached refs after something outside this driver changed them, such as a clone into `cwd`. */ + readonly invalidateRefs: (cwd: string) => Effect.Effect; readonly listLocalBranchNames: (cwd: string) => Effect.Effect; } >()("t3/vcs/GitVcsDriver") {} @@ -467,6 +469,10 @@ const FLAGGED_INDEX_ENTRIES_MAX_BYTES = 1024 * 1024; const CHECKPOINT_RECOVERY_MAX_CANDIDATES = 64; const CHECKPOINT_RECOVERY_TIMEOUT = "5 seconds"; const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; +// Reflog subjects that only point a ref at an existing commit. Anything else counts as creating +// one, so an unknown subject keeps its commit attributed. +const REF_MOVE_REFLOG_SUBJECT = + /^(?:$|(?:checkout|reset|branch|clone|fetch)\b|[^:]*\((?:start|finish|abort|reset)\): |(?:merge|pull|rebase|cherry-pick)\b[^()]*: fast-forward$)/i; const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [ "-c", "core.fsmonitor=false", @@ -585,6 +591,10 @@ const gitCommand = Effect.fn("GitVcsDriver.gitCommand")( }), ); +const HEAD_MOVES_SCAN_LIMIT = 512; +const HEAD_MARK_TRAILER = "T3-Head-Moved-At"; +const HEAD_MARK_TRAILER_PATTERN = new RegExp(`^${HEAD_MARK_TRAILER}: (\\d+) (\\d+)$`, "m"); + export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -922,13 +932,14 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( const headExists = result.exitCode === 0; const headChecked = headExists || result.exitCode === 1; const lines = result.stdout.split("\n"); - const [gitCommonDir = "", indexPath = "", prefix = ""] = lines; + const [gitCommonDir = "", indexPath = "", prefix = "", head = ""] = lines; if (headChecked && lines.length === (headExists ? 5 : 4) && lines.at(-1) === "") { return { gitCommonDir: gitCommonDir.trim(), indexPath: indexPath.trim(), prefix, headExists, + head: headExists ? head : undefined, }; } // Git before 2.31 echoes --path-format, and a path containing a newline spans lines. @@ -944,6 +955,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( indexPath: undefined, prefix: prefixResult.stdout.replace(/\n$/, ""), headExists: headChecked ? headExists : yield* hasHeadCommit(cwd), + head: undefined, }; }); @@ -965,6 +977,64 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( // core.longpaths is disabled in the user's Git configuration. const longPaths = hostPlatform === "win32" ? ["-c", "core.longpaths=true"] : []; + // Newest first: the commit each HEAD move landed on, when, and Git's reason for it. + const readHeadMoves = (cwd: string) => + execute({ + operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION, + cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--walk-reflogs", + "-n", + String(HEAD_MOVES_SCAN_LIMIT), + "--date=unix", + "--format=%H %gd %gs", + "HEAD", + "--", + ], + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => + result.exitCode !== 0 + ? [] + : result.stdout.split("\n").flatMap((line) => { + const [, to, at, reason] = /^([0-9a-f]+) HEAD@\{(\d+)\} (.*)$/.exec(line) ?? []; + return to === undefined || at === undefined || reason === undefined + ? [] + : [{ to, at, reason }]; + }), + ), + Effect.orElseSucceed(() => []), + ); + + // A checkpoint taken after a branch switch has a second parent: the checkpoint before it with + // the switch applied, which is where that turn started. Other ranges start at `from` itself. + const resolveTurnStart = (input: VcsDriver.VcsListAuthoredPathsInput) => + execute({ + operation: "GitVcsDriver.checkpoints.resolveTurnStart", + cwd: input.cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--no-walk=unsorted", + "--format=%H %P", + `${input.fromCheckpointRef}^{commit}`, + `${input.toCheckpointRef}^2`, + ], + allowNonZeroExit: true, + }).pipe( + Effect.map((result): string => { + const [fromLine = "", startLine = ""] = result.stdout.trimEnd().split("\n"); + const [start = "", , startedFrom] = startLine.split(" "); + return result.exitCode === 0 && startedFrom === fromLine.split(" ")[0] + ? start + : input.fromCheckpointRef; + }), + ); + const checkpoints: VcsDriver.VcsCheckpointOps = { captureCheckpoint: Effect.fn("GitVcsDriver.checkpoints.captureCheckpoint")(function* (input) { const operation = VcsProcess.CHECKPOINT_CAPTURE_OPERATION; @@ -979,9 +1049,18 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "-c", "splitIndex.sharedIndexExpire=never", ]; - const { gitCommonDir, indexPath, prefix, headExists } = yield* resolveCaptureRepository( + const { gitCommonDir, indexPath, prefix, headExists, head } = yield* resolveCaptureRepository( input.cwd, ); + // Read before the snapshot and pinned to the same HEAD: a switch that lands while files are + // being staged then belongs to the next checkpoint instead of being applied to this one. + const headMoves = head === undefined ? [] : yield* readHeadMoves(input.cwd); + const lastMove = headMoves.at(0); + // Moves share a second, so the mark also counts how many of that second it has seen. + const headMark = + lastMove !== undefined && lastMove.to === head + ? `${lastMove.at} ${headMoves.filter((move) => move.at === lastMove.at).length}` + : undefined; const indexId = yield* random.uuidV4(); const tempIndexPath = path.join(gitCommonDir, `t3-checkpoint-index-${indexId}`); const hostEnv = yield* HostProcess.Environment; @@ -1331,8 +1410,137 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); } - const message = `t3 checkpoint ref=${input.checkpointRef}`; - // HEAD is the parent so listAuthoredPaths can see how HEAD moved between checkpoints. + // Switching branches rewrites files the turn never wrote, and only HEAD's reflog tells a + // switch from a reset. The trailer marks where that reflog stood for the next checkpoint. + const turnStart = + headMark === undefined || input.previousCheckpointRef === undefined + ? null + : yield* Effect.gen(function* () { + const previous = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "-c", + "log.showSignature=false", + "log", + "--no-walk", + "--format=%H %T %ct %P%n%B", + `${input.previousCheckpointRef}^{commit}`, + ], + allowNonZeroExit: true, + }); + if (previous.exitCode !== 0) return null; + const [commit = "", tree = "", capturedAt = "", previousHead = ""] = previous.stdout + .slice(0, previous.stdout.indexOf("\n")) + .split(" "); + const [, markedAt, markedCount] = + HEAD_MARK_TRAILER_PATTERN.exec(previous.stdout) ?? []; + const oldestMarked = headMoves.findLastIndex((move) => move.at === markedAt); + // -1 when the scan ended inside the marked second, so the count cannot be placed. + const since = + oldestMarked === HEAD_MOVES_SCAN_LIMIT - 1 + ? -1 + : oldestMarked - Number(markedCount) + 1; + if (headMoves[since]?.to !== previousHead) return null; + const switches = headMoves + .slice(0, since) + .map((move, index) => ({ ...move, from: headMoves[index + 1]!.to })) + .filter( + (move) => + move.reason.startsWith("checkout: moving from ") && move.from !== move.to, + ) + .toReversed(); + const landedOn = switches.at(-1)?.to; + if (landedOn === undefined) return null; + + yield* execute({ + operation, + cwd: input.cwd, + args: [...indexConfig, "-c", "index.sparse=false", "read-tree", tree], + env: commitEnv, + }); + for (const { from, to } of switches) { + const changes = yield* execute({ + operation, + cwd: input.cwd, + args: [ + "-c", + "core.quotePath=true", + "diff-tree", + "-r", + "--no-renames", + from, + to, + ], + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }); + // A switch succeeds only where the files it replaces were unmodified, so each + // changed path takes the destination's version. Mode 000000 drops the path. + const entries = changes.stdout + .split("\n") + // A switch leaves a submodule's own checkout where it was. + .filter((line) => line !== "" && !/^:(?:160000 |[0-7]{6} 160000 )/.test(line)) + .map((line) => + line.replace( + /^:[0-7]{6} ([0-7]{6}) [0-9a-f]+ ([0-9a-f]+) [A-Z]\t/, + "$1 $2\t", + ), + ); + if (entries.length === 0) continue; + yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...indexConfig, + "-c", + "index.sparse=false", + "update-index", + "--index-info", + ], + stdin: `${entries.join("\n")}\n`, + env: commitEnv, + }); + } + const startTree = (yield* execute({ + operation, + cwd: input.cwd, + args: [...indexConfig, ...durableWrite, "write-tree"], + env: commitEnv, + })).stdout.trim(); + if (startTree === "" || startTree === tree) return null; + const startCommit = yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...durableWrite, + "commit-tree", + startTree, + "-p", + landedOn, + "-p", + commit, + "-m", + `t3 checkpoint turn start ref=${input.checkpointRef}`, + ], + // listAuthoredPaths reads commits newer than the start as the turn's own. + env: { ...commitEnv, GIT_COMMITTER_DATE: `${capturedAt} +0000` }, + }); + return startCommit.stdout.trim() || null; + }).pipe( + Effect.catch((cause) => + Effect.logWarning("checkpoint branch switch turn start failed", { + cwd: input.cwd, + checkpointRef: input.checkpointRef, + cause: String(cause), + }).pipe(Effect.as(null)), + ), + ); + + const message = `t3 checkpoint ref=${input.checkpointRef}${ + headMark === undefined ? "" : `\n\n${HEAD_MARK_TRAILER}: ${headMark}` + }`; + // HEAD is the first parent so listAuthoredPaths can see how HEAD moved between checkpoints. const commitTreeResult = yield* execute({ operation, cwd: input.cwd, @@ -1340,7 +1548,8 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ...durableWrite, "commit-tree", treeOid, - ...(headExists ? ["-p", "HEAD"] : []), + ...(headExists ? ["-p", head ?? "HEAD"] : []), + ...(turnStart === null ? [] : ["-p", turnStart]), "-m", message, ], @@ -1390,20 +1599,90 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( }); // An empty index and checkpoint have nothing for git restore's pathspec to match. if (tracked.stdout.length > 0) { + const sparseConfig = yield* execute({ + operation, + cwd: input.cwd, + args: ["config", "--bool", "core.sparseCheckout"], + allowNonZeroExit: true, + }); + const sparseCheckout = sparseConfig.stdout.trim() === "true"; + const restore = [...longPaths, "restore", "--source", commitOid, "--worktree", "--staged"]; + // restore leaves skip-worktree paths alone. Outside a sparse checkout every such bit was + // set by hand and capture recorded the file, so override them all. yield* execute({ operation, cwd: input.cwd, - args: [ - ...longPaths, - "restore", - "--source", - commitOid, - "--worktree", - "--staged", - "--", - ".", - ], + args: [...restore, ...(sparseCheckout ? [] : ["--ignore-skip-worktree-bits"]), "--", "."], }); + if (sparseCheckout) { + // Sparse exclusions stay excluded; only skip-worktree paths the rules select are manual. + const manual = yield* Effect.gen(function* () { + const skipped: string[] = []; + let recordStart = true; + let keep = false; + let record: Uint8Array[] = []; + yield* vcsProcess.run({ + operation, + command: "git", + cwd: input.cwd, + args: ["ls-files", "--full-name", "--sparse", "-v", "-z", "--", "."], + maxOutputBytes: 4_096, + outputMode: "truncate", + // The index can be huge; keep only the "S "/"s " records of the NUL-delimited list. + onStdoutChunk: (chunk) => { + let start = 0; + while (start < chunk.length) { + const end = chunk.indexOf(0, start); + if (recordStart) { + keep = chunk[start] === 83 || chunk[start] === 115; + record = []; + } + if (keep) { + record.push(Buffer.from(chunk.subarray(start, end === -1 ? undefined : end))); + if (end !== -1) { + const entry = Buffer.concat(record).subarray(2); + record = []; + // Sparse directory entries are exclusions; stdin cannot carry non-UTF-8. + if (entry.at(-1) !== 47 && NodeBuffer.isUtf8(entry)) + skipped.push(entry.toString("utf8")); + } + } + recordStart = end !== -1; + if (!recordStart) break; + start = end + 1; + } + }, + }); + if (skipped.length === 0) return skipped; + const stdin = skipped.join("\0") + "\0"; + // check-rules echoes a subset of its input, so the input size bounds its output. + const rules = yield* execute({ + operation, + cwd: input.cwd, + args: ["sparse-checkout", "check-rules", "-z"], + stdin, + maxOutputBytes: Buffer.byteLength(stdin), + outputMode: "error", + }); + return rules.stdout.split("\0").filter((entry) => entry.length > 0); + }).pipe( + // A Git without ls-files --sparse or check-rules keeps the plain restore's result. + Effect.orElseSucceed((): string[] => []), + ); + if (manual.length > 0) { + yield* execute({ + operation, + cwd: input.cwd, + args: [ + ...restore, + "--ignore-skip-worktree-bits", + "--pathspec-from-file=-", + "--pathspec-file-nul", + ], + stdin: manual.map((entry) => `:(top,literal)${entry}\0`).join(""), + }); + } + } } // Restoring away the last tracked file can remove a nested workspace directory. const recreateWorkspace = fileSystem.makeDirectory(input.cwd, { recursive: true }).pipe( @@ -1501,15 +1780,13 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "checkpoint.fallback_from_to_head": input.fallbackFromToHead, }); - let fromRevision: string = input.fromCheckpointRef; + let fromRevision = yield* resolveTurnStart(input); if (input.fallbackFromToHead === true) { const resolvedFromCommit = yield* resolveCheckpointCommit( input.cwd, input.fromCheckpointRef, ); - if (resolvedFromCommit) { - fromRevision = resolvedFromCommit; - } else { + if (!resolvedFromCommit) { const headCommit = yield* resolveHeadCommit(input.cwd); if (!headCommit) { return yield* new VcsProcessExitError({ @@ -1568,25 +1845,36 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( listAuthoredPaths: Effect.fn("GitVcsDriver.checkpoints.listAuthoredPaths")(function* (input) { const operation = "GitVcsDriver.checkpoints.listAuthoredPaths"; + const turnStart = yield* resolveTurnStart(input); const heads = yield* execute({ operation, cwd: input.cwd, args: [ "log", "--no-walk=unsorted", - "--format=%P %ct", - `${input.fromCheckpointRef}^{commit}`, + "--format=%ct %P", + `${turnStart}^{commit}`, `${input.toCheckpointRef}^{commit}`, ], }); const [fromLine = "", toLine = ""] = heads.stdout.trimEnd().split("\n"); - const [startHead = "", capturedAt = ""] = fromLine.split(" "); - const [endHead = ""] = toLine.split(" "); + const [capturedAt = "", startHead = ""] = fromLine.split(" "); + const [, endHead = ""] = toLine.split(" "); if (startHead === "" || endHead === "" || startHead === endHead) { return null; } - const listPaths = (args: ReadonlyArray) => + const listLines = (args: ReadonlyArray, stdin?: string) => + execute({ + operation, + cwd: input.cwd, + // log.showSignature prints verification text into the output. + args: ["-c", "log.showSignature=false", ...args], + ...(stdin === undefined ? {} : { stdin }), + maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, + outputMode: "error", + }).pipe(Effect.map((result) => result.stdout.split("\n").filter((line) => line !== ""))); + const listPaths = (args: ReadonlyArray, stdin?: string) => execute({ operation, cwd: input.cwd, @@ -1602,26 +1890,73 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( "--no-renames", "--no-ext-diff", ], + ...(stdin === undefined ? {} : { stdin }), maxOutputBytes: VcsDriver.CHECKPOINT_DIFF_MAX_OUTPUT_BYTES, outputMode: "error", }).pipe(Effect.map((result) => result.stdout.split("\0"))); + + // A commit is an import when a fetch delivered it since the previous checkpoint and no + // reflog in any worktree shows this repository creating it. --all covers every worktree's + // HEAD, and with --walk-reflogs --since compares each entry's own time. + const listImportedCommits = Effect.gen(function* () { + const entries = (yield* listLines([ + "log", + "--walk-reflogs", + "--all", + `--since=@${capturedAt}`, + "--format=%H %gD %gs", + ])).map((line) => { + const [commit = "", selector = "", ...subject] = line.split(" "); + return { + commit, + fetched: selector.startsWith("refs/remotes/"), + subject: subject.join(" "), + }; + }); + // A push records commits this repository already had. + const fetchedTips = new Set( + entries + .filter((entry) => entry.fetched && entry.subject !== "update by push") + .map((entry) => entry.commit), + ); + if (fetchedTips.size === 0) return fetchedTips; + // Fetching another branch can deliver a commit that was made here and pushed. + const createdHere = new Set( + entries + .filter((entry) => !entry.fetched && !REF_MOVE_REFLOG_SUBJECT.test(entry.subject)) + .map((entry) => entry.commit), + ); + const fetched = yield* listLines( + ["rev-list", `--since=@${capturedAt}`, "--stdin"], + `${[...fetchedTips, `^${startHead}`].join("\n")}\n`, + ); + return new Set(fetched.filter((commit) => !createdHere.has(commit))); + }); + // Remerge diffs retain merge conflict fixes while excluding clean upstream changes. - const pathLists = yield* Effect.all( + const [recentCommits, ...pathLists] = yield* Effect.all( [ - listPaths(["diff", startHead, `${input.fromCheckpointRef}^{commit}`]), + listLines(["rev-list", `--since=@${capturedAt}`, `${startHead}..${endHead}`]), + listPaths(["diff", startHead, `${turnStart}^{commit}`]), listPaths(["diff", endHead, `${input.toCheckpointRef}^{commit}`]), listPaths(["log", "--format=", "--diff-merges=remerge", `${endHead}..${startHead}`]), - listPaths([ - "log", - "--format=", - "--diff-merges=remerge", - `--since=@${capturedAt}`, - `${startHead}..${endHead}`, - ]), ], { concurrency: "unbounded" }, ); - return new Set(pathLists.flat().filter((path) => path.length > 0)); + // Without readable reflogs every recent commit stays attributed, as before. + const importedCommits = + recentCommits.length === 0 + ? new Set() + : yield* listImportedCommits.pipe(Effect.orElseSucceed(() => new Set())); + const ownCommits = recentCommits.filter((commit) => !importedCommits.has(commit)); + const ownCommitPaths = + ownCommits.length === 0 + ? [] + : yield* listPaths( + ["log", "--no-walk=unsorted", "--stdin", "--format=", "--diff-merges=remerge"], + `${ownCommits.join("\n")}\n`, + ); + return new Set([...pathLists.flat(), ...ownCommitPaths].filter((path) => path.length > 0)); }), deleteCheckpointRefs: Effect.fn("GitVcsDriver.checkpoints.deleteCheckpointRefs")( diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d46666cb468d0..060beadad39f7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -722,6 +722,26 @@ it.effect("reads a branch whose name starts with a parenthesis as attached", () ).pipe(Effect.provide(layerTest)), ); +it.effect("follows a checkout made outside the driver after refs were cached", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["branch", "feature/outside"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.listRefs({ cwd }); + + yield* git(cwd, ["switch", "feature/outside"]); + + const refs = (yield* driver.listRefs({ cwd })).refs; + const previous = refs.find((ref) => ref.name === initialBranch); + assert.isTrue(refs.find((ref) => ref.name === "feature/outside")?.current); + assert.isFalse(previous?.current); + assert.isNull(previous?.worktreePath ?? null); + }), + ).pipe(Effect.provide(layerTest)), +); + it.effect.each(["on a branch", "detached", "unborn"] as const)( "reads only the repository root for review requests that ignore the branch when %s", (state) => @@ -4323,6 +4343,39 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { insertions: 1, deletions: 1, }); + const preview = yield* driver.getReviewDiffPreview({ cwd, metadataOnly: true }); + assert.deepStrictEqual( + preview.sources.find((source) => source.kind === "working-tree")?.files, + [ + { path: "asset.data", previousPath: null, additions: 0, deletions: 1 }, + { path: "ordinary.txt", previousPath: null, additions: 1, deletions: 0 }, + ], + ); + }), + ); + + it.effect("keeps an oversized untracked file out of the review diff", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + yield* writeTextFile(cwd, "README.md", "# tracked change\n"); + yield* writeTextFile(cwd, "ordinary.txt", "new\n"); + yield* writeTextFile(cwd, "large.data", ""); + // Sparse: the logical size is over the budget without allocating it. + yield* fileSystem.truncate(pathService.join(cwd, "large.data"), 257 * 1024 * 1024); + + const preview = yield* driver.getReviewDiffPreview({ cwd, metadataOnly: true }); + + const source = preview.sources.find((source) => source.kind === "working-tree")!; + assert.isUndefined(source.files); + assert.isUndefined(source.patchesDeferred); + assert.isTrue(source.truncated); + assert.include(source.diff, "+# tracked change"); + assert.include(source.diff, "b/ordinary.txt"); + assert.notInclude(source.diff, "large.data"); }), ); @@ -4637,6 +4690,28 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("does not report a default branch the remote deleted after the clone", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-origin-"); + yield* initRepoWithCommit(cwd); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", "development"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", "development", "development:main"]); + yield* git(cwd, ["remote", "set-head", "origin", "development"]); + yield* git(remote, ["--git-dir=.", "symbolic-ref", "HEAD", "refs/heads/main"]); + yield* git(cwd, ["push", "origin", "--delete", "development"]); + yield* git(cwd, ["fetch", "--prune", "origin"]); + + const driver = yield* GitVcsDriver.GitVcsDriver; + const defaultBranch = yield* driver.resolveDefaultBranchName(cwd, "origin"); + + assert.notEqual(defaultBranch, "development"); + assert.isNull(yield* driver.resolveWorktreeBaseRemote({ cwd, refName: "origin/HEAD" })); + }), + ); + it.effect.each(["checkout", "bare-backed worktree"] as const)( "uses the only remote's HEAD for default-branch detection without origin in a %s", (layout) => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 32042a0ff5e5f..2a0c6772d8d28 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -81,8 +81,8 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; -// git diff --numstat reads every untracked byte (~5 ms/MB), so status totals skip larger untracked input. -const UNTRACKED_TOTALS_MAX_BYTES = 256 * 1024 * 1024; +// git diff reads every untracked byte (~5 ms/MB), so larger untracked input stays out of the review index. +const REVIEW_UNTRACKED_MAX_BYTES = 256 * 1024 * 1024; // The listing walks the whole untracked tree before the cap applies, so a folder whose listing // failed (too many files, output limit, timeout) is not listed again on every status poll. const UNTRACKED_TOTALS_RETRY_MIN_MS = 60_000; @@ -551,7 +551,7 @@ function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): return null; } const refName = trimmed.slice(prefix.length).trim(); - return refName.length > 0 ? refName : null; + return refName.length > 0 && refName !== "HEAD" ? refName : null; } function isMissingGitCwdError(error: GitCommandError): boolean { @@ -1495,23 +1495,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : null; }); + const readCurrentBranch = (operation: string, cwd: string) => + executeGit(operation, cwd, ["symbolic-ref", "--quiet", "HEAD"], { + timeoutMs: 5_000, + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => (result.exitCode === 0 ? branchNameFromHeadRef(result.stdout) : null)), + ); + const resolveRepositoryPathsUncached = Effect.fn("resolveRepositoryPathsUncached")(function* ( cwd: string, ) { const gitCommonDir = yield* readGitCommonDir(cwd); if (gitCommonDir === null) return null; - const [worktreeRoot, currentBranchResult] = yield* Effect.all( + const [worktreeRoot, currentBranch] = yield* Effect.all( [ readWorktreeRoot(cwd), - executeGit( - "GitVcsDriver.resolveRepositoryPaths.currentBranch", - cwd, - ["symbolic-ref", "--quiet", "HEAD"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ), + readCurrentBranch("GitVcsDriver.resolveRepositoryPaths.currentBranch", cwd), ], { concurrency: 2 }, ); @@ -1523,8 +1523,6 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map((physicalCwd) => path.relative(worktreeRoot, physicalCwd) === ""), Effect.orElseSucceed(() => undefined), ); - const currentBranch = - currentBranchResult.exitCode === 0 ? branchNameFromHeadRef(currentBranchResult.stdout) : null; return { gitCommonDir, @@ -1721,7 +1719,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* executeGit( "GitVcsDriver.resolveDefaultBranchName", cwd, - [...gitDirArgs, "symbolic-ref", `refs/remotes/${remoteName}/HEAD`], + // Unlike `symbolic-ref`, this fails when the remote deleted the branch HEAD points at. + [ + ...gitDirArgs, + "rev-parse", + "--verify", + "--quiet", + "--symbolic-full-name", + `refs/remotes/${remoteName}/HEAD`, + ], { allowNonZeroExit: true }, ).pipe( Effect.map((result) => { @@ -3242,7 +3248,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const prepareReviewIndex = Effect.fn("prepareReviewIndex")(function* ( cwd: string, untrackedPaths: ReadonlyArray, - maxBytes?: number, + allowPartial: boolean, ) { const [stagedDeletionsStdout, indexValue] = yield* Effect.all( [ @@ -3270,21 +3276,28 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { concurrency: 2 }, ); const stagedDeletions = new Set(stagedDeletionsStdout.split("\0").filter(Boolean)); - const pathsToAdd = untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)); - if (pathsToAdd.length === 0) return undefined; - if (maxBytes !== undefined) { - const sizes = yield* Effect.forEach( - pathsToAdd, - (relativePath) => - fileSystem.lstat(path.resolve(cwd, relativePath)).pipe( - Effect.map((info) => (info.type === "File" ? Number(info.size) : 0)), - Effect.orElseSucceed(() => 0), - ), - { concurrency: 16 }, - ); - // null: over the byte budget, so the caller reports totals as unavailable. - if (sizes.reduce((total, size) => total + size, 0) > maxBytes) return null; + // Staged deletions never enter the index, so their worktree copies must not spend the budget. + const candidates = untrackedPaths.filter((relativePath) => !stagedDeletions.has(relativePath)); + const sizes = yield* Effect.forEach( + candidates, + (relativePath) => + fileSystem.lstat(path.resolve(cwd, relativePath)).pipe( + Effect.map((info) => (info.type === "File" ? Number(info.size) : 0)), + Effect.orElseSucceed(() => 0), + Effect.map((size) => ({ relativePath, size })), + ), + { concurrency: 16 }, + ); + // Smallest first, so which files fit does not depend on how their names sort. + const pathsToAdd: string[] = []; + let bytes = 0; + for (const { relativePath, size } of sizes.toSorted((left, right) => left.size - right.size)) { + bytes += size; + if (bytes > REVIEW_UNTRACKED_MAX_BYTES) break; + pathsToAdd.push(relativePath); } + const omitted = pathsToAdd.length < candidates.length; + if (pathsToAdd.length === 0 || (omitted && !allowPartial)) return { env: undefined, omitted }; const indexPath = path.isAbsolute(indexValue.trim()) ? indexValue.trim() @@ -3337,7 +3350,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { env, stdin: `${pathsToAdd.join("\0")}\0` }, ); - return env; + return { env, omitted }; }); const readEmptyTreeHash = Effect.fn("readEmptyTreeHash")(function* (cwd: string) { @@ -3353,8 +3366,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const prepareUntrackedReviewIndexOrReason = Effect.fn("prepareUntrackedReviewIndex")(function* ( cwd: string, pathArgs: ReadonlyArray, - onlyPath?: string, - maxBytes?: number, + onlyPath: string | undefined, + allowPartial: boolean, ) { const untracked = yield* executeGit( "GitVcsDriver.review.listUntracked", @@ -3373,10 +3386,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (candidate) => onlyPath === undefined || candidate === onlyPath || candidate === `${onlyPath}/`, ); - if (paths.length === 0) return { env: undefined }; + if (paths.length === 0) return { env: undefined, omitted: false }; if (paths.length > REVIEW_UNTRACKED_MAX_FILES) return { unavailable: "Too many untracked files to count." }; - const env = yield* prepareReviewIndex(cwd, paths, maxBytes).pipe( + const index = yield* prepareReviewIndex(cwd, paths, allowPartial).pipe( Effect.catchTags({ PlatformError: (cause) => Effect.fail( @@ -3390,15 +3403,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), }), ); - if (env === null) return { unavailable: "Untracked files are too large to count." }; - return { env }; + if (index.omitted && !allowPartial) + return { unavailable: "Untracked files are too large to count." }; + return index; }); const prepareUntrackedReviewIndex = ( cwd: string, pathArgs: ReadonlyArray, onlyPath?: string, ) => - prepareUntrackedReviewIndexOrReason(cwd, pathArgs, onlyPath).pipe( + prepareUntrackedReviewIndexOrReason(cwd, pathArgs, onlyPath, true).pipe( Effect.map((result) => ("unavailable" in result ? null : result)), ); @@ -3490,12 +3504,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } // Empty status can mean untracked files are hidden; retain the full scan. - const untracked = yield* prepareUntrackedReviewIndexOrReason( - cwd, - pathspecs, - undefined, - UNTRACKED_TOTALS_MAX_BYTES, - ); + const untracked = yield* prepareUntrackedReviewIndexOrReason(cwd, pathspecs, undefined, false); if ("unavailable" in untracked) { const count = remembered?.roots === rootsKey ? remembered.count + 1 : 1; untrackedTotalsFailures.delete(cwd); @@ -3846,9 +3855,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { const untracked = input.trackedOnly - ? { env: undefined } + ? { env: undefined, omitted: false } : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); - const metadataOnly = input.metadataOnly === true && !input.file && untracked !== null; + // Untracked files left out make the file list partial, so the bounded patch is sent instead. + const complete = untracked !== null && !untracked.omitted; + const metadataOnly = input.metadataOnly === true && !input.file && complete; const [dirty, base] = review.mergeBase === dirtyRef ? yield* readTrackedDiff(dirtyRef, untracked?.env, metadataOnly).pipe( @@ -3861,7 +3872,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ], { concurrency: 2 }, ); - if (untracked !== null) return [dirty, base] as const; + if (complete) return [dirty, base] as const; const incomplete = (ref: string | null, result: typeof dirty) => ref === null ? result : { ...result, files: undefined, stdoutTruncated: true }; return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const; @@ -4217,7 +4228,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* executeGit( "GitVcsDriver.listRefs.defaultRef", fetchCwd, - [...gitDirArgs, "symbolic-ref", "refs/remotes/origin/HEAD"], + [ + ...gitDirArgs, + "rev-parse", + "--verify", + "--quiet", + "--symbolic-full-name", + "refs/remotes/origin/HEAD", + ], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -4245,7 +4263,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* } const defaultBranch = defaultRefResult.exitCode === 0 - ? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") : null; const parsedWorktreeEntries = worktreeListResult.exitCode === 0 @@ -4448,22 +4466,33 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; } - const snapshot = yield* resolveListRefsSnapshot( - repositoryPaths.gitCommonDir, - input.refresh === true, + // Both caches outlive a checkout made outside T3 Code, so this checkout's branch is read + // on every call and replaces whatever the cached snapshot claims for it. + const [snapshot, currentBranch] = yield* Effect.all( + [ + resolveListRefsSnapshot(repositoryPaths.gitCommonDir, input.refresh === true), + readCurrentBranch("GitVcsDriver.listRefs.currentBranch", input.cwd).pipe( + Effect.orElseSucceed(() => repositoryPaths.currentBranch), + ), + ], + { concurrency: 2 }, ); - const hasCurrentWorktreeBranch = - repositoryPaths.worktreeRoot !== null && - snapshot.localBranches.some((ref) => ref.worktreePath === repositoryPaths.worktreeRoot); - const localBranches = snapshot.localBranches.map((ref) => ({ - ...ref, - worktreePath: - ref.worktreePath ?? - (ref.name === repositoryPaths.currentBranch ? repositoryPaths.worktreeRoot : null), - current: hasCurrentWorktreeBranch - ? ref.worktreePath === repositoryPaths.worktreeRoot - : ref.name === repositoryPaths.currentBranch, - })); + const { worktreeRoot } = repositoryPaths; + const localBranches = snapshot.localBranches.map((ref) => { + const current = ref.name === currentBranch; + return { + ...ref, + worktreePath: + worktreeRoot === null + ? ref.worktreePath + : current + ? worktreeRoot + : ref.worktreePath === worktreeRoot + ? null + : ref.worktreePath, + current, + }; + }); const combinedBranches = input.includeMatchingRemoteRefs ? [...localBranches, ...snapshot.remoteBranches] : dedupeRemoteBranchesWithLocalMatches([...localBranches, ...snapshot.remoteBranches]); @@ -5036,7 +5065,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* remoteName: "origin", branchName: input.refName, }; - return remoteNames.includes(remoteName) ? { remoteName, branchName } : null; + // `/HEAD` is the remote's default-branch pointer, not a branch it can serve. + return remoteNames.includes(remoteName) && branchName !== "HEAD" + ? { remoteName, branchName } + : null; }); const fetchWorktreeBaseCommit: GitVcsDriver.GitVcsDriver["Service"]["fetchWorktreeBaseCommit"] = @@ -5578,6 +5610,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* withListRefsInvalidation(input.cwd, switchRef(input)); }), initRepo: initRepoWithListRefsInvalidation, + invalidateRefs: Effect.fn("GitVcsDriver.invalidateRefs")(function* (cwd) { + // First, so a cached "not a repository" cannot end the ref invalidation early. + const cacheKey = normalizeRepositoryPathsCacheKey(cwd); + yield* Cache.invalidate(repositoryPathsRefreshCache, cacheKey); + yield* Cache.invalidate(repositoryPathsCache, cacheKey); + return yield* withListRefsInvalidation(cwd, Effect.void); + }), listLocalBranchNames, listWorktreePaths, }); diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index b382922c5ab27..383db4302543f 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -14,6 +14,8 @@ import * as VcsProcess from "./VcsProcess.ts"; export interface VcsCaptureCheckpointInput { readonly cwd: string; readonly checkpointRef: CheckpointRef; + /** The checkpoint this one follows, so a turn that switched branches starts where it landed. */ + readonly previousCheckpointRef?: CheckpointRef; } export interface VcsRestoreCheckpointInput { diff --git a/apps/server/src/workspace/IgnorePatterns.test.ts b/apps/server/src/workspace/IgnorePatterns.test.ts new file mode 100644 index 0000000000000..f10345566eca5 --- /dev/null +++ b/apps/server/src/workspace/IgnorePatterns.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "@effect/vitest"; + +import { parseIgnoreFile } from "./IgnorePatterns.ts"; + +const decide = (contents: string, path: string, isFolder = false) => + parseIgnoreFile(contents).decide(path, isFolder); + +describe("parseIgnoreFile", () => { + it("lets the last matching pattern decide, including negations", () => { + expect(decide("*keep*\n!*keep*\n", "sub/keep-link.ts")).toBe("included"); + expect(decide("!*keep*\n*keep*\n", "sub/keep-link.ts")).toBe("ignored"); + expect(decide("# comment\n\nother\n", "keep.ts")).toBeUndefined(); + }); + + it("anchors patterns that contain a slash and matches bare names at any depth", () => { + expect(decide("link", "a/b/link")).toBe("ignored"); + expect(decide("/link", "a/link")).toBeUndefined(); + expect(decide("/link", "link")).toBe("ignored"); + expect(decide("a/link", "x/a/link")).toBeUndefined(); + expect(decide("a/*.ts", "a/b/c.ts")).toBeUndefined(); + expect(decide("link", "blink")).toBeUndefined(); + expect(decide("link", "a/blink")).toBeUndefined(); + }); + + it("supports globstars, classes, escapes, and folder-only patterns", () => { + expect(decide("**/gen/*.ts", "gen/a.ts")).toBe("ignored"); + expect(decide("a/**/b", "a/x/y/b")).toBe("ignored"); + expect(decide("a/**/b", "a/b")).toBe("ignored"); + expect(decide("foo/**/bar", "foo/xbar")).toBeUndefined(); + expect(decide("foo/**/bar", "foo/x/ybar")).toBeUndefined(); + expect(decide("out/**", "out/x/y")).toBe("ignored"); + expect(decide("link-[0-9]", "link-7")).toBe("ignored"); + expect(decide("link-[!0-9]", "link-7")).toBeUndefined(); + expect(decide("link-?", "link-/")).toBeUndefined(); + expect(decide("\\!bang\n\\#hash\nstar\\*", "!bang")).toBe("ignored"); + expect(decide("\\!bang\n\\#hash\nstar\\*", "#hash")).toBe("ignored"); + expect(decide("\\!bang\n\\#hash\nstar\\*", "starx")).toBeUndefined(); + expect(decide("dist/", "dist")).toBeUndefined(); + expect(decide("dist/", "dist", true)).toBe("ignored"); + }); + + it("matches adversarial patterns in linear time", () => { + // A backtracking regex takes seconds to reject this pair; the vitest timeout catches that. + const pattern = `${"a*".repeat(20)}b\n`; + expect(decide(pattern, `${"a".repeat(200)}c`)).toBeUndefined(); + expect(decide(pattern.repeat(50), `${"a".repeat(1_000)}c`)).toBeUndefined(); + expect(decide(pattern, `${"a".repeat(200)}b`)).toBe("ignored"); + }); + + it("parses unclosed classes in linear time", () => { + // Rescanning the rest of the line for each `[` stalls for over a minute here; linear takes ms. + expect(decide("[".repeat(30_000), "[".repeat(30_000))).toBe("ignored"); + expect(decide(`${"[".repeat(30_000)}]`, "x")).toBeUndefined(); + expect(decide("[a][", "a[")).toBe("ignored"); + }); +}); diff --git a/apps/server/src/workspace/IgnorePatterns.ts b/apps/server/src/workspace/IgnorePatterns.ts new file mode 100644 index 0000000000000..1180b02316ef9 --- /dev/null +++ b/apps/server/src/workspace/IgnorePatterns.ts @@ -0,0 +1,170 @@ +/** + * Gitignore-syntax matching for `.ignore` files, which git cannot evaluate for us. Patterns come + * from the repository, so each runs as an NFA over the path (O(pattern × path)): a backtracking + * regex stalls for seconds on `a*a*a*…b`. POSIX `[:class:]` names are not supported. + */ + +type Token = + | { readonly type: "char"; readonly char: string } + | { readonly type: "one" } + | { readonly type: "class"; readonly negated: boolean; readonly ranges: ReadonlyArray } + | { readonly type: "star" } + | { readonly type: "any" } + /** A leading or inner `**` segment: nothing, or anything ending in `/`. */ + | { readonly type: "folders" }; + +interface Pattern { + readonly tokens: ReadonlyArray; + readonly negated: boolean; + readonly folderOnly: boolean; +} + +export type IgnoreDecision = "ignored" | "included"; + +function parseClass(chars: ReadonlyArray, start: number) { + let index = start + 1; + const negated = chars[index] === "!" || chars[index] === "^"; + if (negated) index += 1; + const ranges: string[] = []; + for (let first = true; index < chars.length; first = false) { + let char = chars[index]!; + if (char === "]" && !first) + return { token: { type: "class", negated, ranges } as const, end: index }; + if (char === "\\" && index + 1 < chars.length) char = chars[++index]!; + if (chars[index + 1] === "-" && index + 2 < chars.length && chars[index + 2] !== "]") { + let last = chars[index + 2]!; + index += 2; + if (last === "\\" && index + 1 < chars.length) last = chars[++index]!; + ranges.push(char, last); + } else { + ranges.push(char, char); + } + index += 1; + } + return undefined; +} + +function parseLine(rawLine: string): Pattern | undefined { + let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine; + // Trailing spaces are dropped unless escaped. + while (line.endsWith(" ") && !line.endsWith("\\ ")) line = line.slice(0, -1); + if (line === "" || line.startsWith("#")) return undefined; + const negated = line.startsWith("!"); + if (negated) line = line.slice(1); + else if (line.startsWith("\\!") || line.startsWith("\\#")) line = line.slice(1); + const folderOnly = line.endsWith("/") && !line.endsWith("\\/"); + if (folderOnly) line = line.slice(0, -1); + if (line === "") return undefined; + const anchored = line.slice(0, -1).includes("/"); + if (line.startsWith("/")) line = line.slice(1); + + const chars = Array.from(line); + const tokens: Token[] = anchored ? [] : [{ type: "folders" }]; + // A `[` that never closes leaves every later `[` unclosed too, so one failed scan settles them + // all; rescanning the suffix for each would make `[[[[…` quadratic. + let classesClose = true; + for (let index = 0; index < chars.length; index += 1) { + const char = chars[index]!; + if (char === "*" && chars[index + 1] === "*") { + const atSegmentStart = index === 0 || chars[index - 1] === "/"; + const next = chars[index + 2]; + if (atSegmentStart && next === "/") { + tokens.push({ type: "folders" }); + index += 2; + continue; + } + if (atSegmentStart && next === undefined) { + tokens.push({ type: "any" }); + index += 1; + continue; + } + } + if (char === "*") tokens.push({ type: "star" }); + else if (char === "?") tokens.push({ type: "one" }); + else if (char === "[") { + const parsed = classesClose ? parseClass(chars, index) : undefined; + if (!parsed) classesClose = false; + if (parsed) { + tokens.push(parsed.token); + index = parsed.end; + } else tokens.push({ type: "char", char }); + } else if (char === "\\" && index + 1 < chars.length) { + tokens.push({ type: "char", char: chars[++index]! }); + } else tokens.push({ type: "char", char }); + } + return { tokens, negated, folderOnly }; +} + +/** + * States are token positions. A `folders` token that has consumed part of a segment is `~position` + * instead: it may only finish after the next `/`, so an inner globstar never matches `xbar` as `bar`. + */ +function matches(tokens: ReadonlyArray, path: ReadonlyArray): boolean { + let states = new Set(); + const add = (set: Set, position: number) => { + // Wildcards also match nothing, so reaching one reaches the token after it. + for (; position <= tokens.length && !set.has(position); position += 1) { + set.add(position); + const type = tokens[position]?.type; + if (type !== "star" && type !== "any" && type !== "folders") return; + } + }; + add(states, 0); + for (const char of path) { + const next = new Set(); + for (const state of states) { + const position = state < 0 ? ~state : state; + const token = tokens[position]; + if (!token) continue; + switch (token.type) { + case "char": + if (token.char === char) add(next, position + 1); + break; + case "one": + if (char !== "/") add(next, position + 1); + break; + case "class": { + let inRange = false; + for (let index = 0; index < token.ranges.length && !inRange; index += 2) { + inRange = token.ranges[index]! <= char && char <= token.ranges[index + 1]!; + } + if (char !== "/" && inRange !== token.negated) add(next, position + 1); + break; + } + case "star": + if (char !== "/") add(next, position); + break; + case "any": + add(next, position); + break; + case "folders": + if (char === "/") add(next, position); + else next.add(~position); + break; + } + } + if (next.size === 0) return false; + states = next; + } + return states.has(tokens.length); +} + +export interface IgnoreFile { + /** The last pattern that matches decides; `undefined` when none does. */ + readonly decide: (relativePath: string, isFolder: boolean) => IgnoreDecision | undefined; +} + +export function parseIgnoreFile(contents: string): IgnoreFile { + const patterns = contents.split("\n").flatMap((line) => parseLine(line) ?? []); + return { + decide: (relativePath, isFolder) => { + const path = Array.from(relativePath); + for (let index = patterns.length - 1; index >= 0; index -= 1) { + const pattern = patterns[index]!; + if (pattern.folderOnly && !isFolder) continue; + if (matches(pattern.tokens, path)) return pattern.negated ? "included" : "ignored"; + } + return undefined; + }, + }; +} diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 348b5f877ac24..521e127779984 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -433,6 +433,20 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }); }), ); + + it.effect("finds ignored files that sort past the listing limit", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ git: true }); + yield* writeTextFile(cwd, ".gitignore", "*.secret\n"); + for (let index = 1; index <= 205; index += 1) { + yield* writeTextFile(cwd, `file-${String(index).padStart(3, "0")}.secret`, "s"); + } + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const listed = yield* workspaceEntries.listIgnoredFiles({ cwd, query: "file-205" }); + expect(listed.files).toContainEqual({ path: "file-205.secret", byteLength: 1 }); + }), + ); }); describe("search", () => { @@ -532,6 +546,133 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); + it.effect("indexes symlinked files and directories inside the workspace", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-" }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* fileSystem.symlink("src", path.join(cwd, "src-link")); + yield* fileSystem.symlink("src/index.ts", path.join(cwd, "index-link.ts")); + const symlinkEntries = [ + { kind: "directory", path: "src-link" }, + { kind: "file", path: "index-link.ts" }, + ]; + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entry of symlinkEntries) { + expect(searched.entries).toContainEqual(expect.objectContaining(entry)); + expect(listed.entries).toContainEqual(expect.objectContaining(entry)); + } + }), + ); + it.effect("skips symlinks that ignore rules hide or that leave the workspace", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const outside = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-outside-" }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* writeTextFile(cwd, ".ignore", "custom-link\n"); + yield* fileSystem.symlink("src", path.join(cwd, "custom-link")); + yield* fileSystem.symlink("src/index.ts", path.join(cwd, "tracked-link.ts")); + yield* fileSystem.symlink("src", path.join(cwd, "ignored-link")); + yield* fileSystem.symlink("src", path.join(cwd, "kept-link")); + yield* fileSystem.symlink(outside, path.join(cwd, "outside-link")); + yield* git(cwd, ["add", "tracked-link.ts"]); + yield* writeTextFile(cwd, ".gitignore", "tracked-link.ts\nignored-link\n"); + // A submodule path makes `git check-ignore` refuse the whole batch without --no-index. + const submodule = path.join(cwd, "vendor/sub"); + yield* writeTextFile(submodule, "a.ts", "export {};"); + yield* git(submodule, ["init"]); + yield* git(submodule, ["add", "a.ts"]); + yield* git(submodule, [ + "-c", + "user.name=t", + "-c", + "user.email=t@t", + "commit", + "-m", + "init", + ]); + yield* git(cwd, ["add", "vendor/sub"]); + yield* fileSystem.symlink("a.ts", path.join(submodule, "sublink.ts")); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("kept-link"); + expect(paths).toContain("vendor/sub/sublink.ts"); + expect(paths).not.toContain("custom-link"); + expect(paths).not.toContain("tracked-link.ts"); + expect(paths).not.toContain("ignored-link"); + expect(paths).not.toContain("outside-link"); + } + }), + ); + it.effect("lets the nearest .ignore rule decide a symlink, and git's rules still hide it", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, ".gitignore", "*keep*\n"); + yield* writeTextFile(cwd, ".ignore", "!*keep*\n*hide*\n"); + yield* writeTextFile(cwd, "sub/.ignore", "!*hide*\n"); + yield* writeTextFile(cwd, "keep-real.ts", "export {};"); + yield* writeTextFile(cwd, "sub/hide-real.ts", "export {};"); + yield* fileSystem.symlink("keep-real.ts", path.join(cwd, "keep-link.ts")); + yield* fileSystem.symlink("hide-real.ts", path.join(cwd, "sub/hide-link.ts")); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).toContain("sub/hide-link.ts"); + expect(paths).not.toContain("keep-link.ts"); + } + // The real files are shown or hidden by the same rules. + const listedPaths = listed.entries.map((entry) => entry.path); + expect(listedPaths).toContain("sub/hide-real.ts"); + expect(listedPaths).not.toContain("keep-real.ts"); + }), + ); + it.effect("matches .ignore rules against whole names and treats folder links as links", () => + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-symlinks-", git: true }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* writeTextFile(cwd, "src/index.ts", "export {};"); + yield* writeTextFile(cwd, ".gitignore", "blink\n"); + // `!link` must not re-include `blink`, and `folder-link/` does not apply to a link. + yield* writeTextFile(cwd, ".ignore", "!link\nfolder-link/\n"); + yield* fileSystem.symlink("src", path.join(cwd, "blink")); + yield* fileSystem.symlink("src", path.join(cwd, "folder-link")); + yield* writeTextFile(cwd, "sub/blink", "regular"); + + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searched = yield* searchWorkspaceEntries({ cwd, query: "link", limit: 100 }); + const listed = yield* workspaceEntries.list({ cwd }); + + for (const entries of [searched.entries, listed.entries]) { + const paths = entries.map((entry) => entry.path); + expect(paths).not.toContain("blink"); + expect(paths).not.toContain("sub/blink"); + expect(paths).toContain("folder-link"); + } + }), + ); it.effect("finds a path inside a gitignored nested git worktree only by its exact path", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-worktree-", git: true }); @@ -822,10 +963,13 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { if (created.ok) { const finder = created.value; finders += 1; - // The synchronous rescan waits on fff's picker lock on the event loop. + // The synchronous rescan and grep wait on fff's picker lock on the event loop. finder.scanFiles = () => { throw new Error("refresh must not rescan on the JS thread"); }; + finder.grep = () => { + throw new Error("search must not grep on the JS thread"); + }; const scanFilesAsync = finder.scanFilesAsync.bind(finder); finder.scanFilesAsync = () => { rescans += 1; diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.ts index cac706f7ca4a2..43c8fae4dfcaf 100644 --- a/apps/server/src/workspace/WorkspaceEntries.ts +++ b/apps/server/src/workspace/WorkspaceEntries.ts @@ -576,9 +576,13 @@ export const make = Effect.gen(function* () { }) .pipe(Effect.orElseSucceed(() => undefined)); if (!result || result.exitCode !== 0) return { files: [], truncated: false }; + // Filter before the cap so files sorting past it stay reachable by search. + const query = input.query?.toLowerCase() ?? ""; const paths = result.stdout .split("\0") - .filter((entry) => entry.length > 0 && !entry.endsWith("/")) + .filter( + (entry) => entry.length > 0 && !entry.endsWith("/") && entry.toLowerCase().includes(query), + ) .toSorted(); const files = yield* Effect.promise(() => Promise.all( diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index c01600842f2f6..45102e4c1cfea 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -4,14 +4,18 @@ import { type GrepCursor, type GrepOptions, type GrepResult, + type WatchEvent, } from "@ff-labs/fff-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { afterEach, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import * as VcsProcess from "../vcs/VcsProcess.ts"; @@ -43,7 +47,7 @@ it.effect("filters image searches before applying the result limit", () => ...Array.from({ length: 200 }, (_, index) => fileItem(`src/file-${index}.ts`)), fileItem("public/icon.svg"), ]; - const fileSearch = vi.fn(() => ({ + const fileSearch = vi.fn(async () => ({ ok: true as const, value: { items, @@ -55,7 +59,12 @@ it.effect("filters image searches before applying the result limit", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: fileSearch, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); @@ -89,7 +98,7 @@ it.effect("fetches past a first page of Git-ignored results", () => fileItem("hidden/c.ts"), fileItem("src/a.ts"), ]; - const fileSearch = vi.fn((_query: string, options?: { pageSize?: number }) => ({ + const fileSearch = vi.fn(async (_query: string, options?: { pageSize?: number }) => ({ ok: true as const, value: { items: items.slice(0, options?.pageSize), @@ -101,7 +110,12 @@ it.effect("fetches past a first page of Git-ignored results", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: fileSearch, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); @@ -123,7 +137,12 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - fileSearch: vi.fn(() => ({ + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + fileSearchAsync: vi.fn(async () => ({ ok: true as const, value: { items, scores: [], totalMatched: 1, totalFiles: 1 }, })), @@ -174,7 +193,7 @@ it.effect("continues whole-word searches after a filtered grep page", () => filteredFileCount: 1, nextCursor: cursor, }); - const grep = vi.fn((_query: string, options?: GrepOptions) => + const grep = vi.fn(async (_query: string, options?: GrepOptions) => options?.cursor ? { ok: true as const, value: grepResult("needle", [[0, 6]], null) } : { @@ -185,7 +204,12 @@ it.effect("continues whole-word searches after a filtered grep page", () => const finder = { destroy: vi.fn(), waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), - grep, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: () => ({ ok: true as const, value: () => undefined }), + grepAsync: grep, } as unknown as FileFinder; vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); @@ -215,6 +239,249 @@ it.effect("continues whole-word searches after a filtered grep page", () => ).pipe(Effect.provide(testLayer)), ); +function fakeSymlinkFinder( + directories: ReadonlyArray, + options: { + readonly indexed?: ReadonlyArray<{ + readonly path: string; + readonly kind: "file" | "directory"; + }>; + readonly watchFailures?: number; + } = {}, +) { + const watchers: Array<(events: ReadonlyArray) => void> = []; + let watchFailures = options.watchFailures ?? 0; + // fff's pageIndex is an offset into the results, not a page number. + const directorySearch = vi.fn( + async (_query: string, searchOptions?: { pageIndex?: number; pageSize?: number }) => { + const offset = searchOptions?.pageIndex ?? 0; + const items = directories.slice(offset, offset + (searchOptions?.pageSize ?? 100)); + return { + ok: true as const, + value: { + items: items.map((relativePath) => ({ relativePath })), + totalMatched: directories.length, + }, + }; + }, + ); + const indexedItems = (options.indexed ?? []).map((entry) => ({ + type: entry.kind, + item: { relativePath: entry.path, fileName: entry.path.split("/").at(-1) }, + })); + const finder = { + destroy: vi.fn(), + waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), + // fff's isScanning waits on the picker lock on the JS thread. + isScanning: () => { + throw new Error("isScanning must not run on the JS thread"); + }, + getScanProgressAsync: async () => ({ + ok: true as const, + value: { isScanning: false }, + }), + watch: (callback: (events: ReadonlyArray) => void) => { + if (watchFailures > 0) { + watchFailures -= 1; + throw new Error("File system watcher is not ready"); + } + watchers.push(callback); + return { ok: true as const, value: () => undefined }; + }, + directorySearchAsync: directorySearch, + fileSearchAsync: async () => { + const items = indexedItems.flatMap((entry) => (entry.type === "file" ? [entry.item] : [])); + return { ok: true as const, value: { items, scores: [], totalMatched: items.length } }; + }, + mixedSearchAsync: async () => ({ + ok: true as const, + value: { items: indexedItems, totalMatched: indexedItems.length }, + }), + } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); + return { + directorySearch, + notifyWatchers: (events: ReadonlyArray) => + watchers.forEach((watcher) => watcher(events)), + }; +} + +const listedPaths = (searchIndex: WorkspaceSearchIndex.WorkspaceSearchIndex["Service"]) => + searchIndex.list().pipe(Effect.map((result) => result.entries.map((entry) => entry.path))); + +it.effect("reads symlinks again after the watcher reports a change", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts")); + const { directorySearch, notifyWatchers } = fakeSymlinkFinder([]); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const concurrent = yield* Effect.all( + Array.from({ length: 8 }, () => listedPaths(searchIndex)), + { concurrency: "unbounded" }, + ); + yield* fileSystem.remove(path.join(cwd, "old-link.ts")); + yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts")); + const beforeNotice = yield* listedPaths(searchIndex); + // Editing a file cannot move a link, so it does not cost a rescan. + notifyWatchers([{ kind: "modified", path: path.join(cwd, "a.ts") }]); + const afterEdit = yield* listedPaths(searchIndex); + notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]); + const afterNotice = yield* listedPaths(searchIndex); + // fff reports a link replaced in place as modified. + yield* fileSystem.remove(path.join(cwd, "new-link.ts")); + yield* fileSystem.symlink(outside, path.join(cwd, "new-link.ts")); + notifyWatchers([{ kind: "modified", path: path.join(cwd, "new-link.ts") }]); + const afterReplace = yield* listedPaths(searchIndex); + + expect(concurrent).toEqual(Array.from({ length: 8 }, () => ["old-link.ts"])); + expect(beforeNotice).toEqual(["old-link.ts"]); + expect(afterEdit).toEqual(["old-link.ts"]); + expect(afterNotice).toEqual(["new-link.ts"]); + expect(afterReplace).toEqual([]); + expect(directorySearch).toHaveBeenCalledTimes(3); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("answers from the last symlink scan while a slow rescan runs", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-stale-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "old-link.ts")); + const { notifyWatchers } = fakeSymlinkFinder([]); + // Holding git's ignore check open keeps the rescan from finishing. + const gate = yield* Deferred.make(); + let holdIgnoreChecks = false; + const vcsProcess = yield* VcsProcess.VcsProcess; + const searchIndex = yield* WorkspaceSearchIndex.make(cwd).pipe( + Effect.provideService(VcsProcess.VcsProcess, { + ...vcsProcess, + run: (input) => + holdIgnoreChecks && input.operation === "WorkspaceSearchIndex.listGitIgnored" + ? Deferred.await(gate).pipe(Effect.andThen(vcsProcess.run(input))) + : vcsProcess.run(input), + }), + ); + expect(yield* listedPaths(searchIndex)).toEqual(["old-link.ts"]); + + holdIgnoreChecks = true; + yield* fileSystem.symlink("a.ts", path.join(cwd, "new-link.ts")); + notifyWatchers([{ kind: "created", path: path.join(cwd, "new-link.ts") }]); + const duringRescan = yield* Effect.forkChild(listedPaths(searchIndex)); + yield* TestClock.adjust("1 second"); + expect(yield* Fiber.join(duringRescan)).toEqual(["old-link.ts"]); + + yield* Deferred.succeed(gate, undefined); + expect(yield* listedPaths(searchIndex)).toEqual(["new-link.ts", "old-link.ts"]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("keeps symlinks once the watcher subscribes after starting late", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-watch-" }); + yield* fileSystem.writeFileString(path.join(cwd, "a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "link.ts")); + const { directorySearch } = fakeSymlinkFinder([], { watchFailures: 2 }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const scansAfterRound: number[] = []; + for (let round = 0; round < 5; round += 1) { + expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]); + expect(yield* listedPaths(searchIndex)).toEqual(["link.ts"]); + scansAfterRound.push(directorySearch.mock.calls.length); + yield* TestClock.adjust("1 minute"); + } + + // An unwatched scan serves reads only briefly; the third has a watcher and is kept. + expect(scansAfterRound).toEqual([1, 2, 3, 3, 3]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect( + "lists a symlink the watcher indexed once, with the link's kind, and drops rejected ones", + () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-dupe-" }); + const outside = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-outside-" }); + yield* fileSystem.makeDirectory(path.join(cwd, "src")); + yield* fileSystem.symlink("src", path.join(cwd, "src-link")); + // A link the scan rejects stays out even when the watcher indexed it. + yield* fileSystem.symlink(outside, path.join(cwd, "outside-link")); + fakeSymlinkFinder([], { + indexed: [ + { path: "outside-link", kind: "file" }, + { path: "src-link", kind: "file" }, + { path: "link-file.ts", kind: "file" }, + ], + }); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + const searched = yield* searchIndex.search("link", 10); + const files = yield* searchIndex.search("link", 1, "file"); + const listed = yield* searchIndex.list(); + + expect(searched.entries).toEqual([ + { path: "src-link", kind: "directory" }, + { path: "link-file.ts", kind: "file" }, + ]); + // The dropped link does not take the only slot. + expect(files).toEqual({ + entries: [{ path: "link-file.ts", kind: "file" }], + truncated: false, + }); + expect(listed.entries).toEqual([ + { path: "link-file.ts", kind: "file" }, + { path: "src-link", kind: "directory" }, + ]); + }), + ).pipe(Effect.provide(testLayer)), +); + +it.effect("finds symlinks in folders past the first page of the index", () => + Effect.scoped( + Effect.gen(function* () { + if ((yield* HostProcess.Platform) === "win32") return; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-symlink-pages-" }); + yield* fileSystem.makeDirectory(path.join(cwd, "late")); + yield* fileSystem.writeFileString(path.join(cwd, "late/a.ts"), ""); + yield* fileSystem.symlink("a.ts", path.join(cwd, "late/link.ts")); + // Folders fff lists but that are gone by the time they are read are skipped. + const firstPage = Array.from({ length: 1_000 }, (_, index) => `missing-${index}`); + const { directorySearch } = fakeSymlinkFinder([...firstPage, "late"]); + + const searchIndex = yield* WorkspaceSearchIndex.make(cwd); + + expect(yield* listedPaths(searchIndex)).toEqual(["late", "late/link.ts"]); + expect(directorySearch.mock.calls.map(([, options]) => options?.pageIndex)).toEqual([ + 0, 1_000, + ]); + }), + ).pipe(Effect.provide(testLayer)), +); + // fff reads HOME on Linux and macOS but the user profile on Windows, so a temp HOME cannot stand in there. it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "refuses to index a workspace rooted at the home directory", diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 5d5d39bf55612..22e307c182616 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics nodeBuiltinImport:off - readdir with file types avoids an lstat per child +import * as NodeFSP from "node:fs/promises"; import * as NodeModule from "node:module"; import type { @@ -7,11 +9,18 @@ import type { GrepCursor, MixedItem, Result, + WatchEvent, + WatchUnsubscribe, } from "@ff-labs/fff-node"; +import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as LayerMap from "effect/LayerMap"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import type { @@ -24,8 +33,10 @@ import type { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; +import { scoreSubsequenceMatch } from "@t3tools/shared/searchRanking"; import * as VcsProcess from "../vcs/VcsProcess.ts"; +import { type IgnoreDecision, type IgnoreFile, parseIgnoreFile } from "./IgnorePatterns.ts"; // fff-node's native library stays external; single-executables require disk packages instead of importing them. const requireForFff = NodeModule.createRequire(import.meta.url); @@ -38,6 +49,13 @@ const WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000; const WORKSPACE_INDEX_IDLE_TTL = "15 minutes"; const CONTENT_SEARCH_TIME_BUDGET_MS = 250; const CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100; +const SYMLINK_SCAN_CONCURRENCY = 16; +// A scan no watcher can invalidate is reused this long, so typing does not rescan every folder. +const UNWATCHED_SYMLINK_SCAN_TTL_MS = 2_000; +// A rescan that outlasts this leaves the read on the previous scan. +const SYMLINK_RESCAN_WAIT = "5 millis"; +// Each page is a synchronous native call; small pages let searches run between them. +const SYMLINK_DIRECTORY_PAGE_SIZE = 1_000; export class WorkspaceSearchIndexCreateFailed extends Schema.TaggedError()( "WorkspaceSearchIndexCreateFailed", @@ -290,6 +308,135 @@ function withDirectoryAncestors(entries: ReadonlyArray): ProjectEn return [...entryByPath.values()]; } +interface ScannedDirectory { + readonly directory: string; + readonly links: ReadonlyArray; + /** Every symlink in the folder, including ones dropped for leaving the workspace. */ + readonly linkPaths: ReadonlyArray; + /** A nested repository (or the workspace's own), whose ignore rules own what is below it. */ + readonly isRepository: boolean; + readonly ignoreFile: string | undefined; +} + +const joinEntryPath = (directory: string, name: string) => + directory ? `${directory}/${name}` : name; + +/** + * fff skips symlinks, and `followSymlinks` drops file links, dedupes folder links, and walks out + * of the workspace. So links are read from the folders fff already indexed (ignore rules applied), + * without descending into them, and kept only when they resolve inside the workspace. + */ +const scanDirectory = Effect.fn("WorkspaceSearchIndex.scanDirectory")(function* ( + fileSystem: FileSystem.FileSystem, + path: Path.Path, + cwd: string, + root: string, + directory: string, +) { + // Effect's readDirectory returns bare names; one lstat per child would cost far more. + const children = yield* Effect.promise(() => + NodeFSP.readdir(path.join(cwd, directory), { withFileTypes: true }).catch(() => []), + ); + const links: ProjectEntry[] = []; + const linkPaths: string[] = []; + let isRepository = false; + let ignoreFile: string | undefined; + for (const child of children) { + if (child.name === ".git") isRepository = true; + if (child.name === ".ignore" && child.isFile()) { + ignoreFile = yield* fileSystem + .readFileString(path.join(cwd, directory, child.name)) + .pipe(Effect.orElseSucceed(() => undefined)); + } + if (!child.isSymbolicLink()) continue; + const entryPath = joinEntryPath(directory, child.name); + linkPaths.push(entryPath); + const absolutePath = path.join(cwd, entryPath); + const target = yield* Effect.all([ + fileSystem.realPath(absolutePath), + fileSystem.stat(absolutePath), + ]).pipe(Effect.orElseSucceed(() => undefined)); + if (!target) continue; + const relative = path.relative(root, target[0]); + if ( + relative === ".." || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) || + relative.split(path.sep).includes(".git") || + (target[1].type !== "Directory" && target[1].type !== "File") + ) { + continue; + } + links.push({ path: entryPath, kind: target[1].type === "Directory" ? "directory" : "file" }); + } + return { directory, links, linkPaths, isRepository, ignoreFile } satisfies ScannedDirectory; +}); + +/** Whether `entryPath` is `directory` itself or below it. */ +const isWithin = (entryPath: string, directory: string) => + directory === "" || entryPath.startsWith(`${directory}/`); + +/** + * fff reads `.ignore` files alongside git's rules, and like ripgrep the nearest one that matches + * decides, ahead of any `.gitignore`. `ignoreFiles` is ordered deepest folder first. + */ +function decideByIgnoreFiles( + entry: ProjectEntry, + ignoreFiles: ReadonlyArray<{ readonly directory: string; readonly file: IgnoreFile }>, +): IgnoreDecision | undefined { + for (const { directory, file } of ignoreFiles) { + if (!isWithin(entry.path, directory) || entry.path === directory) continue; + const relative = directory ? entry.path.slice(directory.length + 1) : entry.path; + // Like git and ripgrep, a link is never a folder to a folder-only rule, whatever it targets. + const decision = file.decide(relative, false); + if (decision) return decision; + } + return undefined; +} + +/** Places each symlink before the first index result that matches the query less closely. */ +function mergeSymlinkMatches( + indexed: ProjectSearchEntriesResult, + linkPaths: ReadonlySet, + symlinks: ReadonlyArray, + query: string, + limit: number, +): ProjectSearchEntriesResult { + if (linkPaths.size === 0) return indexed; + // fff's watcher indexes links created after its scan, under a kind of its own choosing, so a + // path it already returned takes the link's kind (or drops out of a kind-filtered search). + const symlinkByPath = new Map(symlinks.map((entry) => [entry.path, entry])); + const score = (entry: ProjectEntry) => + scoreSubsequenceMatch(entry.path.toLowerCase(), query) ?? Number.POSITIVE_INFINITY; + const indexedPaths = new Set(indexed.entries.map((entry) => entry.path)); + const pending = symlinks + .flatMap((entry) => { + const entryScore = score(entry); + return Number.isFinite(entryScore) && !indexedPaths.has(entry.path) + ? [{ entry, score: entryScore }] + : []; + }) + .toSorted((left, right) => left.score - right.score); + const entries: ProjectEntry[] = []; + let nextPending = 0; + for (const indexedEntry of indexed.entries) { + const entry = linkPaths.has(indexedEntry.path) + ? symlinkByPath.get(indexedEntry.path) + : indexedEntry; + if (!entry) continue; + const entryScore = score(entry); + while (nextPending < pending.length && pending[nextPending]!.score < entryScore) { + entries.push(pending[nextPending++]!.entry); + } + entries.push(entry); + } + for (; nextPending < pending.length; nextPending += 1) entries.push(pending[nextPending]!.entry); + return { + entries: entries.slice(0, limit), + truncated: indexed.truncated || entries.length > limit, + }; +} + // fff applies .gitignore files only; Git also ignores paths from .git/info/exclude and the global excludes file. const listGitIgnoredPaths = Effect.fn("WorkspaceSearchIndex.listGitIgnoredPaths")(function* ( vcsProcess: VcsProcess.VcsProcess["Service"], @@ -401,6 +548,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( variant: WorkspaceSearchIndexVariant = "paths", ) { const hostIsWindows = yield* HostProcess.isWindows; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) => Effect.try({ try: () => finder.destroy(), @@ -430,22 +579,32 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }), ); - const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning(); + // fff's isScanning takes the picker lock too, so progress is read off the JS thread. + const isScanning = Effect.promise(async () => { + try { + const progress = await finder.getScanProgressAsync(); + return !progress.ok || progress.value.isScanning; + } catch { + return true; + } + }); + const hasIncompleteInitialScan = () => (initialScanTimedOut ? isScanning : Effect.succeed(false)); const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* ( query: string, pageSize: number, operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch", - execute: () => Result, + execute: () => Promise>, ): Effect.fn.Return { - const result = yield* Effect.try({ + // fff's searches wait on its picker lock, which its watcher can hold for minutes. + const result = yield* Effect.tryPromise({ try: execute, catch: (cause) => new WorkspaceSearchIndexSearchFailed({ cwd, queryLength: query.length, pageSize, - reason: `FileFinder.${operation} threw unexpectedly.`, + reason: `FileFinder.${operation} rejected unexpectedly.`, cause, }), }); @@ -460,12 +619,233 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( return result.value; }); + const root = yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => cwd)); + + const listIndexedDirectories = Effect.fn("WorkspaceSearchIndex.listIndexedDirectories")( + function* () { + const directories: string[] = []; + // fff's pageIndex is an offset into the results, not a page number. + for (let pageIndex = 0; ; pageIndex += SYMLINK_DIRECTORY_PAGE_SIZE) { + const result = yield* Effect.promise(async () => { + try { + return await finder.directorySearchAsync("", { + pageIndex, + pageSize: SYMLINK_DIRECTORY_PAGE_SIZE, + }); + } catch { + return undefined; + } + }); + if (!result?.ok) return directories; + for (const item of result.value.items) { + const directory = trimDirectorySeparator(toPosixPath(item.relativePath, hostIsWindows)); + if (directory) directories.push(directory); + } + if (result.value.items.length < SYMLINK_DIRECTORY_PAGE_SIZE) return directories; + } + }, + ); + + /** Ignore rules belong to the repository that owns a path, so each one answers for its own. */ + const listGitIgnored = Effect.fn("WorkspaceSearchIndex.listGitIgnored")(function* ( + repository: string, + entries: ReadonlyArray, + ) { + const relativePaths = entries.map((entry) => + repository ? entry.path.slice(repository.length + 1) : entry.path, + ); + const repositoryCwd = path.join(cwd, repository); + const result = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnored", + command: "git", + // fff applies ignore rules to tracked paths too, so the index is not consulted. + args: ["-c", "core.fsmonitor=false", "check-ignore", "--no-index", "-z", "--stdin"], + cwd: repositoryCwd, + stdin: `${relativePaths.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 10_000, + maxOutputBytes: 16 * 1024 * 1024, + }) + .pipe(Effect.orElseSucceed(() => undefined)); + // Exit 1 means nothing matched. + if (result?.exitCode === 1) return []; + if (result?.exitCode !== 0 || result.stdoutTruncated) { + // Outside git no rules apply (git exits before reading stdin, so the cause is lost). + // Any other failure hides the repository's links rather than leaking ones it ignores. + const insideRepository = yield* vcsProcess + .run({ + operation: "WorkspaceSearchIndex.listGitIgnored", + command: "git", + args: ["rev-parse", "--git-dir"], + cwd: repositoryCwd, + timeoutMs: 10_000, + }) + .pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + return insideRepository ? entries.map((entry) => entry.path) : []; + } + return result.stdout + .split("\0") + .filter(Boolean) + .map((relativePath) => (repository ? `${repository}/${relativePath}` : relativePath)); + }); + + const scanSymlinkEntries = Effect.fn("WorkspaceSearchIndex.scanSymlinkEntries")(function* () { + const indexComplete = !(yield* isScanning); + const directories = yield* listIndexedDirectories(); + const scanned = yield* Effect.forEach( + ["", ...directories], + (directory) => scanDirectory(fileSystem, path, cwd, root, directory), + { concurrency: SYMLINK_SCAN_CONCURRENCY }, + ); + const candidates = scanned.flatMap((directory) => directory.links); + const linkPaths = new Set(scanned.flatMap((directory) => directory.linkPaths)); + if (candidates.length === 0) return { entries: candidates, linkPaths, indexComplete }; + + const ignoreFiles = scanned + .flatMap(({ directory, ignoreFile }) => + ignoreFile === undefined ? [] : [{ directory, file: parseIgnoreFile(ignoreFile) }], + ) + .toSorted((left, right) => right.directory.length - left.directory.length); + const decisions = new Map( + candidates.map((entry) => [entry.path, decideByIgnoreFiles(entry, ignoreFiles)]), + ); + const repositories = [ + "", + ...scanned.flatMap(({ directory, isRepository }) => + isRepository && directory ? [directory] : [], + ), + ].toSorted((left, right) => right.length - left.length); + const entriesByRepository = Map.groupBy( + candidates.filter((entry) => decisions.get(entry.path) === undefined), + (entry) => + repositories.find( + (repository) => isWithin(entry.path, repository) && entry.path !== repository, + ) ?? "", + ); + const ignored = new Set( + (yield* Effect.forEach( + entriesByRepository, + ([repository, entries]) => listGitIgnored(repository, entries), + { concurrency: 4 }, + )).flat(), + ); + return { + entries: candidates.filter((entry) => + decisions.get(entry.path) === undefined + ? !ignored.has(entry.path) + : decisions.get(entry.path) === "included", + ), + linkPaths, + indexComplete, + }; + }); + + // One scan runs at a time and outlives the reads that started it. Only the first read waits for + // it in full: after that a change or expiry marks the result stale, and reads wait briefly for + // the rescan before answering from the last finished one, so file churn cannot stall search. + type SymlinkScan = Effect.Success>; + let lastSymlinkScan: SymlinkScan | undefined; + let lastSymlinkScanExpiresAt: number | undefined; + let pendingSymlinkScan: Deferred.Deferred | undefined; + let symlinkScanStale = false; + let knownLinkPaths: ReadonlySet = new Set(); + const invalidateSymlinkScan = () => { + symlinkScanStale = true; + }; + const isKnownLink = (absolutePath: string) => + [cwd, root].some((base) => + knownLinkPaths.has(toPosixPath(path.relative(base, absolutePath), hostIsWindows)), + ); + const onWatchBatch = (events: ReadonlyArray) => { + // fff reports a link replaced in place as `modified`, so edits to known links count too. + const editsOnly = events.every( + (event) => + event.kind === "modified" && + !/(^|[\\/])\.(git)?ignore$/.test(event.path) && + !isKnownLink(event.path), + ); + if (!editsOnly) invalidateSymlinkScan(); + }; + // fff refuses subscriptions until its watcher is up, which can trail the initial scan, so + // each read retries until one is in place. + let unwatch: WatchUnsubscribe | undefined; + yield* Effect.addFinalizer(() => Effect.sync(() => unwatch?.())); + const ensureWatching = () => { + if (unwatch) return true; + try { + const result = finder.watch(onWatchBatch); + if (result.ok) unwatch = result.value; + } catch { + // Not ready yet; the next read tries again. + } + return unwatch !== undefined; + }; + const indexScope = yield* Effect.scope; + const startSymlinkScan = Effect.fn("WorkspaceSearchIndex.startSymlinkScan")(function* () { + symlinkScanStale = false; + // Subscribing before the scan starts means no change during it goes unseen. + const watched = ensureWatching(); + const done = yield* Deferred.make(); + pendingSymlinkScan = done; + yield* scanSymlinkEntries().pipe( + Effect.tap((result) => + Effect.gen(function* () { + lastSymlinkScan = result; + knownLinkPaths = result.linkPaths; + // Without a watcher, or before fff has seen every folder, the result is kept only briefly. + lastSymlinkScanExpiresAt = + watched && result.indexComplete + ? undefined + : (yield* Clock.currentTimeMillis) + UNWATCHED_SYMLINK_SCAN_TTL_MS; + }), + ), + Effect.onExit((exit) => + Effect.sync(() => { + pendingSymlinkScan = undefined; + }).pipe(Effect.andThen(Deferred.done(done, exit))), + ), + Effect.forkIn(indexScope), + ); + return done; + }); + const listSymlinkEntries = Effect.fn("WorkspaceSearchIndex.listSymlinkEntries")(function* () { + if ( + lastSymlinkScanExpiresAt !== undefined && + (yield* Clock.currentTimeMillis) >= lastSymlinkScanExpiresAt + ) { + symlinkScanStale = true; + } + const pending = + pendingSymlinkScan ?? + (lastSymlinkScan === undefined || symlinkScanStale ? yield* startSymlinkScan() : undefined); + let result = lastSymlinkScan; + if (pending && result === undefined) { + result = yield* Deferred.await(pending); + } else if (pending) { + const fresh = yield* Deferred.await(pending).pipe(Effect.timeoutOption(SYMLINK_RESCAN_WAIT)); + if (Option.isSome(fresh)) result = fresh.value; + } + if (result === undefined) + return yield* Effect.die("The symlink scan finished without a result."); + return { + // Git's ignore rules hide a link the same way searchVisible hides the files it indexes. + entries: result.entries.filter( + (entry) => !isIgnoredPath(ignoredPaths, entry.path, hostIsWindows), + ), + linkPaths: result.linkPaths, + }; + }); + // Grows the first page until hidden entries can no longer crowd visible ones out of it. const searchVisible = Effect.fn("WorkspaceSearchIndex.searchVisible")(function* ( query: string, pageSize: number, operation: "directorySearch" | "fileSearch" | "mixedSearch", - execute: (pageSize: number) => Result>, + execute: (pageSize: number) => Promise>>, pathOf: (item: I) => string, ): Effect.fn.Return, WorkspaceSearchIndexSearchFailed> { let size = pageSize; @@ -522,21 +902,25 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }), ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void })); ignoredPaths = yield* listGitIgnoredPaths(vcsProcess, cwd, hostIsWindows); + invalidateSymlinkScan(); }); const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")( function* () { - const incompleteBeforeQuery = hasIncompleteInitialScan(); + const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); const result = yield* searchVisible( "", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", - (pageSize) => finder.mixedSearch("", { pageSize }), + (pageSize) => finder.mixedSearchAsync("", { pageSize }), mixedItemPath, ); const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES, hostIsWindows); - const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) => - left.path.localeCompare(right.path), + const symlinks = yield* listSymlinkEntries(); + // fff's watcher can index a link the scan rejected; only accepted links are listed. + const indexed = mapped.entries.filter((entry) => !symlinks.linkPaths.has(entry.path)); + const sortedEntries = withDirectoryAncestors([...indexed, ...symlinks.entries]).toSorted( + (left, right) => left.path.localeCompare(right.path), ); const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES); return { @@ -553,35 +937,45 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( kind: ProjectEntryKind | undefined, imageOnly: boolean | undefined, ) { - const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1); + const { entries: allSymlinks, linkPaths } = yield* listSymlinkEntries(); + const symlinks = allSymlinks.filter((entry) => + imageOnly + ? entry.kind === "file" && isProjectFaviconPath(entry.path) + : kind === undefined || entry.kind === kind, + ); + // Index results that are filtered-out links get dropped in the merge, so fetch past them. + const indexLimit = limit + linkPaths.size - symlinks.length; + const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, indexLimit + 1); + const merge = (indexed: ProjectSearchEntriesResult) => + mergeSymlinkMatches(indexed, linkPaths, symlinks, query, limit); if (kind === "file" || imageOnly) { const result = yield* searchVisible( query, pageSize, "fileSearch", - (size) => finder.fileSearch(query, { pageSize: size }), + (size) => finder.fileSearchAsync(query, { pageSize: size }), (item) => item.relativePath, ); - return mapFileSearchResult(result, limit, hostIsWindows, imageOnly); + return merge(mapFileSearchResult(result, indexLimit, hostIsWindows, imageOnly)); } if (kind === "directory") { const result = yield* searchVisible( query, pageSize, "directorySearch", - (size) => finder.directorySearch(query, { pageSize: size }), + (size) => finder.directorySearchAsync(query, { pageSize: size }), (item) => item.relativePath, ); - return mapDirectorySearchResult(result, limit, hostIsWindows); + return merge(mapDirectorySearchResult(result, indexLimit, hostIsWindows)); } const result = yield* searchVisible( query, pageSize, "mixedSearch", - (size) => finder.mixedSearch(query, { pageSize: size }), + (size) => finder.mixedSearchAsync(query, { pageSize: size }), mixedItemPath, ); - return mapMixedSearchResult(result, limit, hostIsWindows); + return merge(mapMixedSearchResult(result, indexLimit, hostIsWindows)); }); const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( @@ -591,7 +985,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths. // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working. const query = rawQuery.replaceAll("[", ""); - const incompleteBeforeQuery = hasIncompleteInitialScan(); + const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); let mapped = yield* searchNames(query, limit, kind, imageOnly); if (mapped.entries.length === 0 && query.includes("{")) { mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly); @@ -616,7 +1010,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( do { const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now())); const result = yield* runSearch(input.query, input.limit, "grep", () => - finder.grep(searchQuery, { + finder.grepAsync(searchQuery, { mode: regexMode ? "regex" : "plain", smartCase: !input.caseSensitive && !regexMode, maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize), diff --git a/apps/server/src/workspace/restoreMissingWorktree.ts b/apps/server/src/workspace/restoreMissingWorktree.ts index ee423c47d06ab..dee23025dbf41 100644 --- a/apps/server/src/workspace/restoreMissingWorktree.ts +++ b/apps/server/src/workspace/restoreMissingWorktree.ts @@ -1,17 +1,22 @@ import { ThreadId, type ProjectId, type TerminalCwdNotFoundError } from "@t3tools/contracts"; +import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as ServerConfig from "../config.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import { scratchFolderRoot } from "../project/ManagedProjectFolders.ts"; import * as ProjectService from "../project/ProjectService.ts"; import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts"; import { isWithinRoot } from "./KnownWorkspaces.ts"; +import { withWorkspaceLease } from "./workspaceLease.ts"; import { TerminalCwdRecovery } from "../terminal/Manager.ts"; -class WorktreeRecreateError extends Schema.TaggedError()( +export class WorktreeRecreateError extends Schema.TaggedError()( "WorktreeRecreateError", { worktreePath: Schema.String, @@ -33,6 +38,9 @@ class WorktreeRecreateNoBaseError extends Schema.TaggedError root)); + if (path.dirname(folder) !== root && path.dirname(folder) !== realRoot) return; + yield* Effect.logWarning("recreating missing scratch folder", { + threadId: thread.id, + folder, + }); + yield* fileSystem.makeDirectory(folder, { recursive: true }); + }, + // Turn start reports a folder that is still missing. + Effect.orElseSucceed(() => undefined), + ); + + // Only folders holding nothing but leftovers are cleared, never user files. + const isLeftoverFolder = (worktreePath: string) => + fileSystem.exists(path.join(worktreePath, ".git")).pipe( + Effect.flatMap((hasGit) => + hasGit + ? Effect.succeed(false) + : fileSystem.readDirectory(worktreePath).pipe( + Effect.flatMap((entries) => + Effect.forEach(entries, (entry) => + LEFTOVER_WORKTREE_ENTRIES.has(entry) + ? fileSystem + .stat(path.join(worktreePath, entry)) + .pipe(Effect.map((info) => info.type === "Directory")) + : Effect.succeed(false), + ), + ), + Effect.map((leftovers) => leftovers.every(Boolean)), + ), + ), + Effect.orElseSucceed(() => false), + ); const resolveRecreateBase = Effect.fn("restoreMissingWorktree.resolveRecreateBase")(function* ( cwd: string, @@ -114,9 +167,11 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { return Effect.fn("restoreMissingWorktree")(function* (thread: WorktreeThread) { const { worktreePath, branch } = thread; - if (worktreePath === null || branch === null) return; + if (worktreePath === null) return; + if (branch === null) return yield* recreateScratchFolder(thread, worktreePath); const exists = yield* fileSystem.exists(worktreePath).pipe(Effect.orElseSucceed(() => true)); - if (exists || !(yield* isManagedWorktreePath(worktreePath))) return; + const leftover = exists && (yield* isLeftoverFolder(worktreePath)); + if ((exists && !leftover) || !(yield* isManagedWorktreePath(worktreePath))) return; const project = yield* projects.getById(thread.projectId).pipe( Effect.map(Option.getOrUndefined), Effect.orElseSucceed(() => undefined), @@ -127,7 +182,9 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { worktreePath, branch, }); - yield* recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch }).pipe( + // `git worktree add` refuses a non-empty target. + yield* (leftover ? fileSystem.remove(worktreePath, { recursive: true }) : Effect.void).pipe( + Effect.andThen(recreateMissingWorktree({ cwd: project.workspaceRoot, worktreePath, branch })), Effect.mapError((cause) => cause._tag === "WorktreeRecreateNoBaseError" ? cause @@ -137,6 +194,31 @@ export const makeRestoreMissingWorktree = Effect.gen(function* () { }); }); +export class ThreadWorktreeRestore extends Context.Service< + ThreadWorktreeRestore, + { + readonly restore: ( + thread: WorktreeThread, + ) => Effect.Effect; + } +>()("t3/workspace/restoreMissingWorktree/ThreadWorktreeRestore") {} + +// Turn start restores under the same lease, so concurrent restores see each other's worktree. +export const layerThreadWorktreeRestore = Layer.effect( + ThreadWorktreeRestore, + Effect.gen(function* () { + const path = yield* Path.Path; + const restore = yield* makeRestoreMissingWorktree; + return { + restore: Effect.fn("ThreadWorktreeRestore.restore")(function* (thread: WorktreeThread) { + return yield* thread.worktreePath === null + ? restore(thread) + : withWorkspaceLease(path.resolve(thread.worktreePath), restore(thread)); + }), + }; + }), +); + // Worktree setup uses terminals, so recovery must stay outside TerminalManager. export const makePrepareTerminalLaunch = Effect.fn( "restoreMissingWorktree.makePrepareTerminalLaunch", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index a28be4cfd0c5d..b7d85fc318fc4 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2986,7 +2986,7 @@ export const layerWsRpc = ( new ProjectMutationError({ commandId: mutation.commandId, message: - cause._tag === "ProjectNotEmptyError" + cause._tag === "ProjectNotEmptyError" || cause._tag === "ProjectInvalidError" ? cause.message : "Failed to mutate project.", cause, @@ -3164,7 +3164,15 @@ export const layerWsRpc = ( [WS_METHODS.vcsCreateWorktree]: (input) => gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsRemoveWorktree]: (input) => - gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + gitWorkflow.removeWorktree(input).pipe( + Effect.tap(() => refreshGitStatus(input.cwd)), + // Subscribers of the removed checkout learn it is no longer a repository. + Effect.tap(() => + vcsStatusBroadcaster + .refreshLocalStatus(input.path) + .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid), + ), + ), [WS_METHODS.vcsCreateRef]: (input) => gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), [WS_METHODS.vcsSwitchRef]: (input) => diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index 3291aa304d395..0ec539e5ae169 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -5,6 +5,7 @@ import { defineConfig, mergeConfig } from "vite-plus"; import baseConfig from "../../vite.config.ts"; import { loadRepoEnv } from "../../scripts/lib/public-config.ts"; +import { resolveTaggedSourceVersion } from "../../scripts/lib/tagged-source-version.ts"; import rootPackageJson from "../../package.json" with { type: "json" }; import packageJson from "./package.json" with { type: "json" }; import { WeightedShardSequencer } from "./src/testUtils/weightedShardSequencer.ts"; @@ -18,9 +19,12 @@ import { export { shouldBundleCliDependency }; const repoEnv = loadRepoEnv(); -const cliBuildChannel = /^[^-+]+-(?:nightly|preview)\./.test(packageJson.version) - ? "nightly" - : "latest"; +const serverManifestPath = NodePath.join(import.meta.dirname, "package.json"); +// The desktop packager passes APP_VERSION; it can equal the manifest at a commit tagged otherwise. +const buildVersion = + process.env.APP_VERSION?.trim() || + resolveTaggedSourceVersion(NodePath.join(import.meta.dirname, "../.."), packageJson.version); +const cliBuildChannel = /^[^-+]+-(?:nightly|preview)\./.test(buildVersion) ? "nightly" : "latest"; // Official release workflows set the telemetry channel; local builds and forks use "dev". const TELEMETRY_CHANNELS = ["stable", "nightly", "preview", "dev"]; const telemetryChannel = process.env.T3CODE_TELEMETRY_CHANNEL?.trim() || "dev"; @@ -88,6 +92,19 @@ export default mergeConfig( }, }, pack: { + plugins: [ + { + // Every server module reads its version from this manifest import. + name: "t3code:build-version", + load(id) { + if (NodePath.resolve(id) !== serverManifestPath) return; + return { + code: JSON.stringify({ ...packageJson, version: buildVersion }), + moduleType: "json", + }; + }, + }, + ], // SEA embeds one entry; expose the history worker as a hidden subcommand. entry: packBootstrap ? ["src/bin.ts"] diff --git a/apps/web/src/browser/ServerBrowserSurface.tsx b/apps/web/src/browser/ServerBrowserSurface.tsx index e32e8f76f1a9d..a881650f69bcf 100644 --- a/apps/web/src/browser/ServerBrowserSurface.tsx +++ b/apps/web/src/browser/ServerBrowserSurface.tsx @@ -46,6 +46,7 @@ export interface ServerBrowserHandle { readonly navigate: (url: string) => void; readonly history: (delta: -1 | 1) => void; readonly reload: (options?: { readonly ignoreCache?: boolean }) => void; + readonly stopLoading: () => void; readonly viewport: (setting: PreviewViewportSetting) => void; readonly canvas: () => HTMLCanvasElement | null; } @@ -311,6 +312,7 @@ export function ServerBrowserSurface(props: { history: (delta) => send({ type: "history", delta }), reload: (options) => send({ type: "reload", ...(options?.ignoreCache ? { ignoreCache: true } : {}) }), + stopLoading: () => send({ type: "stopLoading" }), viewport: (setting) => send({ type: "viewport", setting }), canvas: () => (!pdfUrl && hasFrameRef.current ? canvasRef.current : null), }), diff --git a/apps/web/src/browser/browserDefaults.ts b/apps/web/src/browser/browserDefaults.ts index bf1c2da40db87..5cc74bb1b7f0d 100644 --- a/apps/web/src/browser/browserDefaults.ts +++ b/apps/web/src/browser/browserDefaults.ts @@ -5,6 +5,7 @@ import { type DesktopPreviewTabDefaults, type PreviewAppearancePreference, type PreviewViewportSetting, + type PreviewZoomFactor, } from "@t3tools/contracts"; import { @@ -17,7 +18,7 @@ import { resolveResponsiveBrowserViewportSize } from "./browserViewportLayout"; export interface BrowserDefaults { readonly viewport: PreviewViewportSetting; - readonly zoomFactor: number; + readonly zoomFactor: PreviewZoomFactor; readonly appearance: PreviewAppearancePreference; readonly autoShowFloatingPreview: boolean; readonly profiles: ReadonlyArray; @@ -26,7 +27,7 @@ export interface BrowserDefaults { const toBrowserDefaults = (settings: { readonly browserDefaultViewport: PreviewViewportSetting; - readonly browserDefaultZoomFactor: number; + readonly browserDefaultZoomFactor: PreviewZoomFactor; readonly browserDefaultAppearance: PreviewAppearancePreference; readonly browserAutoShowFloatingPreview: boolean; readonly browserProfiles: ReadonlyArray; diff --git a/apps/web/src/browser/browserLinkTarget.ts b/apps/web/src/browser/browserLinkTarget.ts index f1c4e65a99913..74330bf3edbd4 100644 --- a/apps/web/src/browser/browserLinkTarget.ts +++ b/apps/web/src/browser/browserLinkTarget.ts @@ -7,6 +7,9 @@ import { import { ensureClientSettingsHydrated, getClientSettings } from "~/hooks/useSettings"; import { readEnvironmentScope } from "~/state/session"; import { isPreviewAvailableFor } from "./previewRuntime"; +import { isWebUrl } from "./webUrl"; + +export { isWebUrl }; export interface ResolveLinkTargetInput { readonly url: string; @@ -27,15 +30,6 @@ export function resolveLinkTarget(input: ResolveLinkTargetInput): BrowserLinkTar return "app"; } -export function isWebUrl(url: string): boolean { - try { - const { protocol } = new URL(url); - return protocol === "http:" || protocol === "https:"; - } catch { - return false; - } -} - /** Before hydration, the default "system" would ignore a saved "app" link target. */ export async function resolveBrowserLinkTargetPreference(): Promise { await ensureClientSettingsHydrated(); diff --git a/apps/web/src/browser/openFileInPreview.ts b/apps/web/src/browser/openFileInPreview.ts index a997ee2b552e4..db1a58e98dfb9 100644 --- a/apps/web/src/browser/openFileInPreview.ts +++ b/apps/web/src/browser/openFileInPreview.ts @@ -85,7 +85,9 @@ export async function openUrlInPreview(input: { url: input.url, viewport: defaults.viewport, profileId: input.profileId ?? defaults.profileId, - ...(runtime === undefined ? {} : { runtime }), + ...(runtime === undefined + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); return mapAtomCommandResult(result, (snapshot) => { diff --git a/apps/web/src/browser/webUrl.ts b/apps/web/src/browser/webUrl.ts new file mode 100644 index 0000000000000..19e637794b74b --- /dev/null +++ b/apps/web/src/browser/webUrl.ts @@ -0,0 +1,8 @@ +export function isWebUrl(url: string): boolean { + try { + const { protocol } = new URL(url); + return protocol === "http:" || protocol === "https:"; + } catch { + return false; + } +} diff --git a/apps/web/src/components/AddProjectToMachineDialog.tsx b/apps/web/src/components/AddProjectToMachineDialog.tsx index 3d9c064cfcb23..3bb70c8b609eb 100644 --- a/apps/web/src/components/AddProjectToMachineDialog.tsx +++ b/apps/web/src/components/AddProjectToMachineDialog.tsx @@ -26,6 +26,7 @@ import { useAddProjectTargets } from "../hooks/useAddProjectTargets"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments"; import { + COPIED_FILES_MAX_COUNT, COPYABLE_FILE_MAX_BYTES, addProjectToMachine, isDefaultCopiedFile, @@ -35,6 +36,7 @@ import { newProjectId } from "../lib/utils"; import { readProject, subscribeProject, useProject } from "../state/entities"; import { useEnvironments } from "../state/environments"; import { projectEnvironment } from "../state/projects"; +import { useDebouncedValue } from "../state/queries"; import { useEnvironmentQuery } from "../state/query"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { Button } from "./ui/button"; @@ -121,8 +123,10 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const [pathOverride, setPathOverride] = useState(null); const destinationPath = pathOverride ?? defaultPath; - const canListFiles = source?.serverConfig?.environment.capabilities.ignoredFileListing === true; - const ignoredFiles = useEnvironmentQuery( + const capabilities = source?.serverConfig?.environment.capabilities; + const canListFiles = capabilities?.ignoredFileListing === true; + const canSearchFiles = canListFiles && capabilities?.ignoredFileSearch === true; + const allIgnoredFiles = useEnvironmentQuery( project && canListFiles ? projectEnvironment.listIgnoredFiles({ environmentId: project.environmentId, @@ -130,13 +134,29 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe }) : null, ); + const [fileQuery, setFileQuery] = useState(""); + const sentFileQuery = useDebouncedValue(fileQuery.trim(), 120); + const searching = canSearchFiles && sentFileQuery.length > 0; + const searchedFiles = useEnvironmentQuery( + project && searching + ? projectEnvironment.listIgnoredFiles({ + environmentId: project.environmentId, + input: { cwd: project.workspaceRoot, query: sentFileQuery }, + }) + : null, + ); + const ignoredFiles = searching ? searchedFiles : allIgnoredFiles; const files = ignoredFiles.data?.files ?? []; - const [selected, setSelected] = useState | null>(null); - const selectedFiles = selected ?? defaultSelection(files); + // Keyed by path with the file kept, so picks made under one search survive the next. + const [selected, setSelected] = useState | null>(null); + const selectedFiles = selected ?? defaultSelection(allIgnoredFiles.data?.files ?? []); const copyable = files.filter((file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES); - const selectedBytes = files - .filter((file) => selectedFiles.has(file.path)) - .reduce((total, file) => total + file.byteLength, 0); + const allCopyableSelected = copyable.every((file) => selectedFiles.has(file.path)); + const atSelectionLimit = selectedFiles.size >= COPIED_FILES_MAX_COUNT; + const selectedBytes = [...selectedFiles.values()].reduce( + (total, file) => total + file.byteLength, + 0, + ); const [submitting, setSubmitting] = useState(false); const [error, setError] = useState(null); @@ -146,11 +166,19 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe const unavailable = project === null || target === null || - (canListFiles && ignoredFiles.data === null && ignoredFiles.error === null); - const toggleFile = (path: string, checked: boolean) => { - const next = new Set(selectedFiles); - if (checked) next.add(path); - else next.delete(path); + (canListFiles && allIgnoredFiles.data === null && allIgnoredFiles.error === null); + const toggleFile = (file: ProjectIgnoredFile, checked: boolean) => { + const next = new Map(selectedFiles); + if (!checked) next.delete(file.path); + else if (!atSelectionLimit) next.set(file.path, file); + setSelected(next); + }; + const toggleShownFiles = () => { + const next = new Map(selectedFiles); + for (const file of copyable) { + if (allCopyableSelected) next.delete(file.path); + else if (next.size < COPIED_FILES_MAX_COUNT) next.set(file.path, file); + } setSelected(next); }; @@ -198,7 +226,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe title: project.title, remoteUrl, destinationPath: destinationPath.trim(), - files: files.filter((file) => selectedFiles.has(file.path)).map((file) => file.path), + files: [...selectedFiles.keys()], }); close(); openClonedProject(scopeProjectRef(target.environmentId, projectId)); @@ -334,33 +362,41 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe {copyable.length > 0 ? ( <> - {selectedFiles.size} of {files.length} + {selectedFiles.size} of {allIgnoredFiles.data?.files.length ?? 0} {selectedBytes > 0 ? ` · ${formatBytes(selectedBytes)}` : ""} - ) : null} + {canSearchFiles && (allIgnoredFiles.data?.truncated || fileQuery.length > 0) ? ( + setFileQuery(event.target.value)} + // Enter would otherwise submit the clone. + onKeyDown={(event) => { + if (event.key === "Enter") event.preventDefault(); + }} + spellCheck={false} + autoComplete="off" + /> + ) : null} {ignoredFiles.error ? (

{ignoredFiles.error}

) : files.length === 0 ? (

- {ignoredFiles.isSuccess - ? "No ignored files to copy." - : "Finding ignored files…"} + {!ignoredFiles.isSuccess + ? "Finding ignored files…" + : searching + ? "No ignored files match." + : "No ignored files to copy."}

) : (
@@ -369,7 +405,8 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe key={file.path} file={file} checked={selectedFiles.has(file.path)} - onCheckedChange={(checked) => toggleFile(file.path, checked)} + disabled={atSelectionLimit && !selectedFiles.has(file.path)} + onCheckedChange={(checked) => toggleFile(file, checked)} /> ))}
@@ -377,6 +414,7 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe {ignoredFiles.data?.truncated ? (

Showing the first {files.length} files. + {canSearchFiles ? " Search to find the rest." : ""}

) : null}

@@ -415,29 +453,37 @@ function projectSubdirectory(repositoryRoot: string | undefined, workspaceRoot: : ""; } -function defaultSelection(files: readonly ProjectIgnoredFile[]): ReadonlySet { - return new Set( +function defaultSelection( + files: readonly ProjectIgnoredFile[], +): ReadonlyMap { + return new Map( files .filter( (file) => file.byteLength <= COPYABLE_FILE_MAX_BYTES && isDefaultCopiedFile(file.path), ) - .map((file) => file.path), + .map((file) => [file.path, file]), ); } function IgnoredFileRow({ file, checked, + disabled, onCheckedChange, }: { file: ProjectIgnoredFile; checked: boolean; + disabled: boolean; onCheckedChange: (checked: boolean) => void; }) { const tooLarge = file.byteLength > COPYABLE_FILE_MAX_BYTES; return (

Signed in diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.ts index 6cbbca418bd3e..fcc0614ea6a55 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.test.ts +++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts @@ -115,8 +115,10 @@ it("retains visible output and selection until a replacement subscription receiv threadId: "thread", terminalId: "term-1", }); + terminal.resetAndWrite.mockClear(); synchronizeTerminalOutput(terminal, cleared, observedCursor); - expect(terminal.resetAndWrite).toHaveBeenLastCalledWith(""); + expect(terminal.resetAndWrite).not.toHaveBeenCalled(); + expect(terminal.write).toHaveBeenLastCalledWith("\u001b[H\u001b[2J\u001b[3J"); }); it("reports an attach failure that leaves the output unchanged", () => { diff --git a/apps/web/src/components/auth/ApproveAgentSurface.tsx b/apps/web/src/components/auth/ApproveAgentSurface.tsx index 9f4863fe97d57..6568327d5d0e0 100644 --- a/apps/web/src/components/auth/ApproveAgentSurface.tsx +++ b/apps/web/src/components/auth/ApproveAgentSurface.tsx @@ -13,6 +13,7 @@ import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "rea import { isElectron } from "../../env"; import { runConnectMcpApproval } from "../../state/connectMcpApproval"; import { resolveClerkSignInProps } from "../clerk/authRedirect"; +import { retryClerkLoad, useClerkLoadFailed } from "../clerk/clerkLoadFailure"; import { Button } from "../ui/button"; import { Spinner } from "../ui/spinner"; import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page"; @@ -86,6 +87,7 @@ export function ApproveAgentSurface() { ); const clerk = useClerk(); const { isLoaded, isSignedIn } = useAuth(); + const loadFailed = useClerkLoadFailed(); const session = useAtomValue(managedRelaySessionAtom); const signInOpened = useRef(false); @@ -118,6 +120,21 @@ export function ApproveAgentSurface() { ); } + if (loadFailed) { + return ( + +

+ +
+ + ); + } + if (!isLoaded || (isSignedIn && session === null)) { return ( diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx index ce1745a6e51fd..6ccdd2b69b089 100644 --- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx +++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx @@ -52,6 +52,10 @@ function markdownDestination(src: string): string { return `<${escaped}>`; } +function parseImageDimension(value: string | number | undefined): number { + return Number(typeof value === "string" ? value.trim().replace(/px$/i, "") : value); +} + /** * `maxHeightRem` folds a height cap into the width bound: `max-height` alone * would not feed back through `aspect-ratio` once `width` is definite, so a @@ -62,8 +66,8 @@ export function authoredImageSizeStyle( height: string | number | undefined, maxHeightRem = 30, ): CSSProperties | undefined { - const parsedWidth = Number(width); - const parsedHeight = Number(height); + const parsedWidth = parseImageDimension(width); + const parsedHeight = parseImageDimension(height); const hasWidth = Number.isFinite(parsedWidth) && parsedWidth > 0; const hasHeight = Number.isFinite(parsedHeight) && parsedHeight > 0; if (hasWidth && hasHeight) { @@ -322,19 +326,61 @@ export function ChatMarkdownVideo(props: { ); } +type ChatMarkdownAssetResource = Extract< + AssetResource, + { + readonly _tag: + | "attachment" + | "workspace-file" + | "media-file" + | typeof SOURCE_CONTROL_MEDIA_ASSET + | "tool-output-image"; + } +>; + +export function assetMediaActionsSource(input: { + readonly environmentId: EnvironmentId; + readonly resource: ChatMarkdownAssetResource; + readonly kind: "image" | "video"; + readonly name: string; + readonly src: string | null; + readonly workspaceRoot?: string | undefined; + readonly originalUrl?: string | undefined; + readonly downloadable?: boolean | undefined; +}): MediaActionSource { + const { environmentId, resource } = input; + const path = + resource._tag === "media-file" + ? resource.path + : resource._tag === "workspace-file" && input.workspaceRoot + ? `${input.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}` + : undefined; + const reference = path + ? mediaFileReference(path, input.workspaceRoot) + : input.originalUrl + ? mediaUrlReference(input.originalUrl) + : undefined; + const relativePath = reference?.kind === "file" ? reference.relativePath : undefined; + return { + kind: input.kind, + name: input.name, + src: input.src, + ...(input.downloadable === false ? {} : { asset: { environmentId, resource } }), + ...(reference ? { reference } : {}), + ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file") + ? { + onOpenFile: () => + useRightPanelStore + .getState() + .openFile({ environmentId, threadId: resource.threadId }, relativePath), + } + : {}), + }; +} + export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: { readonly environmentId: EnvironmentId; - readonly resource: Extract< - AssetResource, - { - readonly _tag: - | "attachment" - | "workspace-file" - | "media-file" - | typeof SOURCE_CONTROL_MEDIA_ASSET - | "tool-output-image"; - } - >; + readonly resource: ChatMarkdownAssetResource; readonly kind?: "image" | "video"; readonly alt: string; readonly copyMarkdown?: string; @@ -366,18 +412,6 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props : undefined, ); const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource); - const path = - resource._tag === "media-file" - ? resource.path - : resource._tag === "workspace-file" && props.workspaceRoot - ? `${props.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}` - : undefined; - const reference = path - ? mediaFileReference(path, props.workspaceRoot) - : props.originalUrl - ? mediaUrlReference(props.originalUrl) - : undefined; - const relativePath = reference?.kind === "file" ? reference.relativePath : undefined; const fallbackSrc = assetUrl._tag === "Failure" ? props.fallbackSrc : undefined; const src = assetUrl._tag === "Success" @@ -394,26 +428,16 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props : maxHeightRem !== 30 ? { maxHeight: `${maxHeightRem}rem` } : undefined); - const actionsSource: MediaActionSource = { + const actionsSource = assetMediaActionsSource({ + environmentId: props.environmentId, + resource, kind: props.kind ?? "image", name: props.alt || (props.kind ?? "image"), src, - ...(fallbackSrc === undefined - ? { asset: { environmentId: props.environmentId, resource } } - : {}), - ...(reference ? { reference } : {}), - ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file") - ? { - onOpenFile: () => - useRightPanelStore - .getState() - .openFile( - { environmentId: props.environmentId, threadId: resource.threadId }, - relativePath, - ), - } - : {}), - }; + workspaceRoot: props.workspaceRoot, + originalUrl: props.originalUrl, + downloadable: fallbackSrc === undefined, + }); if (props.kind === "video") { return ( diff --git a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx index 0fe4cc14d3869..6df532afd074c 100644 --- a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx @@ -7,12 +7,14 @@ import { render } from "../../../test/render"; import { ComposerHandleContext, type ComposerHandleRef } from "../../composerHandleContext"; import { ComposerContextPermissions } from "../ComposerContextPermissions"; import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { focusRequestedPermission, markOpenToPermissions, useComposerMenuProps, } from "./composerEventScope"; import { ComposerFooterModeControls, ComposerPermissionsSection } from "./ComposerFooterControls"; +import { ComposerPickerFooter } from "./ComposerModelEffort"; import { runtimeModeConfig, runtimeModeOptions } from "./runtimeModeConfig"; const options = runtimeModeOptions.map((mode) => ({ mode, ...runtimeModeConfig[mode] })); @@ -106,6 +108,49 @@ it("returns focus to the editor after a pick", async () => { await vi.waitFor(() => expect(handle.focusAtEnd).toHaveBeenCalled()); }); +// Mirrors the model picker: a composer popover whose footer nests the Permissions menu. +function PickerWithPermissions() { + const [mode, setMode] = useState("full-access"); + const composerMenuProps = useComposerMenuProps(); + return ( + <> +

Timeline

+ + Model + + + + + + ); +} + +it("on a touch tablet, tapping outside the Permissions menu leaves the editor unfocused", async () => { + const realMatchMedia = window.matchMedia.bind(window); + using _touch = vi + .spyOn(window, "matchMedia") + .mockImplementation((query) => realMatchMedia(query === "(pointer: coarse)" ? "all" : query)); + const { handle, ui } = withComposer(); + await using screen = await render(ui, { router: false }); // no routes involved + await userEvent.click(screen.getByRole("button", { name: "Model" })); + await userEvent.click(page.getByRole("button", { name: "Permissions: Full access" })); + const fullAccess = page.getByRole("menuitemradio", { name: "Full access" }); + await expect.element(fullAccess).toBeInTheDocument(); + const permissionsTrigger = page.getByRole("button", { name: "Permissions: Full access" }); + // The first outside tap closes the Permissions menu, the second the picker around it. + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + await expect.element(fullAccess).not.toBeInTheDocument(); + await userEvent.click(screen.getByText("Timeline")); + await expect.element(permissionsTrigger).not.toBeInTheDocument(); + // Focusing the editor after a tap opens the on-screen keyboard on Android tablets. + expect(handle.focusAtEnd).not.toHaveBeenCalled(); +}); + it("opens on the checked permission when composer.mode marked the trigger", async () => { await using screen = await render(, { router: false }); // no routes involved const trigger = screen.getByRole("button", { name: "More" }); diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index cc8cfc53f4355..60168fdd0f343 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -86,6 +86,10 @@ vi.mock(import("~/assets/assetUrls"), async (original) => { stubbedAsset.url ? { _tag: "Success", url: stubbedAsset.url } : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState, + useAssetUrls: ((...args: Parameters) => + stubbedAsset.url + ? args[1].map(() => stubbedAsset.url) + : actual.useAssetUrls(...args)) as typeof actual.useAssetUrls, }; }); @@ -1687,6 +1691,7 @@ describe("MessagesTimeline attachments", () => { { threadRef: { environmentId: ENVIRONMENT_ID, threadId: ThreadId.make("thread-1") }, workspaceRoot: "/repo", + timelineEntries: [], onImageExpand, } as never } @@ -1723,6 +1728,38 @@ describe("MessagesTimeline attachments", () => { }), ); }); + + it("opens a viewed image with its collapsed siblings in the gallery", async () => { + stubbedAsset.url = + "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; + onTestFinished(() => { + stubbedAsset.url = ""; + }); + const onImageExpand = vi.fn["onImageExpand"]>(); + const read = (name: string) => + work(`read-${name}`, { + label: `Read ${name}`, + toolTitle: "Read", + tone: "tool", + itemType: "dynamic_tool", + toolLifecycleStatus: "completed", + viewedImagePath: `/repo/${name}`, + }); + await using screen = await renderTimeline( + [read("first.png"), read("second.png"), read("third.png")], + { onImageExpand, workspaceRoot: "/repo" }, + ); + await click(screen.button(/^Viewed image.*second\.png/)); + await screen.getByRole("button", { name: "Preview second.png" }).click(); + expect(onImageExpand).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + index: 1, + images: ["first.png", "second.png", "third.png"].map((name) => + expect.objectContaining({ name }), + ), + }), + ); + }); }); describe("MessagesTimeline thread find", () => { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index f928ba473566a..f123c032a3486 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -82,7 +82,9 @@ export function timelineEntryRunId(entry: TimelineEntry): RunId | null { if (entry.kind === "proposed-plan") { return entry.proposedPlan.runId; } - if (entry.kind === "html-render" || entry.kind === "mcp-app") return entry.runId; + if (entry.kind === "html-render" || entry.kind === "mcp-app" || entry.kind === "sent-message") { + return entry.runId; + } return entry.kind === "work" ? (entry.entry.runId ?? null) : null; } @@ -635,6 +637,12 @@ type MessagesTimelineRowContent = createdAt: string; htmlRender: HtmlRenderReference; } + | { + kind: "sent-message"; + id: string; + createdAt: string; + text: string; + } | { kind: "mcp-app"; id: string; @@ -807,6 +815,7 @@ function deriveSupersededAttemptFolds( (entry.kind === "event" && entry.projectedItem.item.type === "handoff") || entry.kind === "html-render" || entry.kind === "mcp-app" || + entry.kind === "sent-message" || timelineEntryIsPersistentResourceCard(entry) || liveSubagentEntryIds.has(entry.id) || (entry.kind === "work" && entry.entry.itemType === "system_notice") @@ -2124,6 +2133,16 @@ export function deriveMessagesTimelineRows(input: { continue; } + if (timelineEntry.kind === "sent-message") { + nextRows.push({ + kind: "sent-message", + id: timelineEntry.id, + createdAt: timelineEntry.createdAt, + text: timelineEntry.text, + }); + continue; + } + if (timelineEntry.kind === "mcp-app") { nextRows.push({ kind: "mcp-app", @@ -2708,6 +2727,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean return a.createdAt === bh.createdAt && htmlRenderReferencesEqual(a.htmlRender, bh.htmlRender); } + case "sent-message": { + const bs = b as typeof a; + return a.createdAt === bs.createdAt && a.text === bs.text; + } + case "mcp-app": { const bm = b as typeof a; return ( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 16c4e06200e43..c59e88b01d0ad 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -125,6 +125,7 @@ import { AssistantMetaTimelineRow, ProposedPlanTimelineRow, HtmlRenderTimelineRow, + SentMessageTimelineRow, McpAppTimelineRow, } from "./TimelineAssistantRows"; import { V2EventTimelineRow } from "./TimelineV2EventRow"; @@ -1094,6 +1095,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ .map((approval) => [approval.requestId, approval]), ); const sharedState: TimelineRowSharedState = { + timelineEntries, pendingApprovals: pendingApprovalsByRequestId, respondingRequestIds, canOperateThread, @@ -1624,7 +1626,9 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time row.kind === "event" || row.kind === "attempt-fold" || row.kind === "html-render" || - row.kind === "mcp-app" + row.kind === "sent-message" || + row.kind === "mcp-app" || + row.kind === "viewed-image" ? "pb-2" : "pb-4", (row.kind === "message" && row.message.role === "assistant") || @@ -1673,6 +1677,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time {row.kind === "assistant-meta" ? : null} {row.kind === "proposed-plan" ? : null} {row.kind === "html-render" ? : null} + {row.kind === "sent-message" ? : null} {row.kind === "mcp-app" ? : null} {row.kind === "working" ? : null} {row.kind === "worktree-setup" ? : null} diff --git a/apps/web/src/components/chat/TimelineAssistantRows.tsx b/apps/web/src/components/chat/TimelineAssistantRows.tsx index 804f48a4f3fb3..94c1d583a0c59 100644 --- a/apps/web/src/components/chat/TimelineAssistantRows.tsx +++ b/apps/web/src/components/chat/TimelineAssistantRows.tsx @@ -5,6 +5,7 @@ import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline"; import { type RunId, type TurnItemId } from "@t3tools/contracts"; import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows"; +import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup"; import { memo, use, useState } from "react"; import { type ChatMessage, type TurnDiffSummary } from "../../types"; import ChatMarkdown from "../ChatMarkdown"; @@ -31,6 +32,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { cn } from "~/lib/utils"; import { useUiStateStore } from "~/uiStateStore"; import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat"; +import { readThreadTurnItems } from "../../state/entities"; import { useV2ItemSupport } from "../../state/v2ItemSupport"; import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext"; import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"; @@ -77,6 +79,11 @@ export function AssistantTimelineRow({ text={messageText} renderInsights cwd={ctx.markdownCwd} + agentDirectories={() => + ctx.threadRef && row.projectedItem + ? agentWorkingDirectories(readThreadTurnItems(ctx.threadRef), row.projectedItem) + : [] + } threadRef={ctx.threadRef ?? undefined} isStreaming={Boolean(row.message.streaming)} lineBreaks={shouldPreserveAssistantLineBreaks(messageText)} @@ -138,6 +145,32 @@ export function AssistantTimelineRow({ ); } +/** Text an agent sent with `send_to_user`, shown as its own words. */ +export function SentMessageTimelineRow({ + row, +}: { + row: Extract; +}) { + const ctx = use(TimelineRowCtx); + + return ( +
+ T3 Code + +
+ ); +} + function AssistantForkButton({ projectedItem, }: { diff --git a/apps/web/src/components/chat/TimelineRowParts.tsx b/apps/web/src/components/chat/TimelineRowParts.tsx index 311def402e3ea..31a272bde1b70 100644 --- a/apps/web/src/components/chat/TimelineRowParts.tsx +++ b/apps/web/src/components/chat/TimelineRowParts.tsx @@ -1,6 +1,11 @@ -import { resolveViewedImageAsset } from "@t3tools/client-runtime/work-log/presentation"; +import { + resolveViewedImageAsset, + workEntriesViewedImagePaths, +} from "@t3tools/client-runtime/work-log/presentation"; import { use, useState } from "react"; -import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; +import { useAssetUrls } from "~/assets/assetUrls"; +import { workGroupImageGallery } from "./markdownImageGallery"; +import { assetMediaActionsSource, ChatMarkdownAssetImage } from "./ChatMarkdownMedia"; import { TimelineRowCtx, type TimelineRow } from "./timelineRowContext"; import { ToolActivityIconView } from "./TimelineToolActivityIcon"; import { ChevronRightIcon } from "lucide-react"; @@ -36,7 +41,7 @@ export function ViewedImageTimelineRow({ }: { row: Extract; }) { - const { threadRef, workspaceRoot, onImageExpand, timestampFormat } = use(TimelineRowCtx); + const { threadRef, workspaceRoot, timestampFormat } = use(TimelineRowCtx); const [expanded, setExpanded] = useState(false); const image = threadRef ? resolveViewedImageAsset(row.imagePath, { threadId: threadRef.threadId, workspaceRoot }) @@ -82,17 +87,70 @@ export function ViewedImageTimelineRow({ {expanded && image && threadRef ? (
- +
) : null} ); } + +function ViewedImagePreview({ row }: { row: Extract }) { + const { timelineEntries, threadRef, workspaceRoot, activeThreadEnvironmentId, onImageExpand } = + use(TimelineRowCtx); + const paths = workEntriesViewedImagePaths( + timelineEntries.flatMap((entry) => + entry.kind === "work" && entry.entry.runId === row.entry.runId ? [entry.entry] : [], + ), + ); + const viewed = threadRef + ? paths.flatMap((path) => { + const asset = resolveViewedImageAsset(path, { + threadId: threadRef.threadId, + workspaceRoot, + }); + return asset ? [{ path, asset }] : []; + }) + : []; + const environmentId = threadRef?.environmentId ?? activeThreadEnvironmentId; + const urls = useAssetUrls( + environmentId, + viewed.map(({ asset }) => asset.resource), + ); + const images = viewed.map(({ path, asset }, index) => { + const url = urls[index]; + if (!url) return { path, item: null }; + const src = url + asset.srcFragment; + return { + path, + item: { + src, + name: asset.alt.trim() || "image", + actionsSource: assetMediaActionsSource({ + environmentId, + resource: asset.resource, + kind: "image", + name: asset.alt || "image", + src, + workspaceRoot, + }), + }, + }; + }); + const image = threadRef + ? resolveViewedImageAsset(row.imagePath, { threadId: threadRef.threadId, workspaceRoot }) + : null; + if (!image || !threadRef) return null; + return ( + + onImageExpand(workGroupImageGallery(images, row.imagePath, preview)) + } + /> + ); +} diff --git a/apps/web/src/components/chat/composerEventScope.ts b/apps/web/src/components/chat/composerEventScope.ts index a0271b4a8257d..b71c338e61ec9 100644 --- a/apps/web/src/components/chat/composerEventScope.ts +++ b/apps/web/src/components/chat/composerEventScope.ts @@ -1,4 +1,5 @@ import { useComposerHandleContext } from "../../composerHandleContext"; +import { useMediaQuery } from "../../hooks/useMediaQuery"; const COMPOSER_FLOATING_LAYER_SELECTOR = [ '[data-composer-drawer-layer="true"]', @@ -11,19 +12,22 @@ export const composerFloatingLayerProps = { export function useComposerMenuProps() { const composerRef = useComposerHandleContext(); + const isCoarsePointer = useMediaQuery({ pointer: "coarse" }); return { ...composerFloatingLayerProps, - finalFocus: composerRef - ? () => { - const activeElement = document.activeElement; - if (activeElement !== document.body && !isInsideComposerFloatingLayer(activeElement)) { + // Focusing the editor on a touch device opens the on-screen keyboard, so the menu keeps its own focus return. + finalFocus: + composerRef && !isCoarsePointer + ? () => { + const activeElement = document.activeElement; + if (activeElement !== document.body && !isInsideComposerFloatingLayer(activeElement)) { + return false; + } + composerRef.current?.focusAtEnd(); return false; } - composerRef.current?.focusAtEnd(); - return false; - } - : undefined, + : undefined, }; } diff --git a/apps/web/src/components/chat/markdownImageGallery.test.ts b/apps/web/src/components/chat/markdownImageGallery.test.ts new file mode 100644 index 0000000000000..88a6171f8a96d --- /dev/null +++ b/apps/web/src/components/chat/markdownImageGallery.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { workGroupImageGallery } from "./markdownImageGallery"; + +const item = (name: string) => ({ src: `https://assets.test/${name}`, name }); + +describe("workGroupImageGallery", () => { + it("pages the clicked image through the group's resolved images", () => { + const clicked = { ...item("second.png"), src: "https://assets.test/second.png#fresh" }; + const viewed = [ + { path: "/repo/first.png", item: item("first.png") }, + { path: "/repo/pending.png", item: null }, + { path: "/repo/second.png", item: item("second.png") }, + { path: "/repo/third.png", item: item("third.png") }, + ]; + expect( + workGroupImageGallery(viewed, "/repo/second.png", { images: [clicked], index: 0 }), + ).toEqual({ images: [item("first.png"), clicked, item("third.png")], index: 1 }); + const single = { images: [clicked], index: 0 }; + expect(workGroupImageGallery(viewed, "/repo/other.png", single)).toBe(single); + }); +}); diff --git a/apps/web/src/components/chat/markdownImageGallery.ts b/apps/web/src/components/chat/markdownImageGallery.ts index ea49e5826be13..61265ac407054 100644 --- a/apps/web/src/components/chat/markdownImageGallery.ts +++ b/apps/web/src/components/chat/markdownImageGallery.ts @@ -47,3 +47,27 @@ export function markdownImageGallery( } return index < 0 ? { images: [selected], index: 0 } : { images, index }; } + +/** + * Widens the single-image preview of an image in an expanded tool row to the images its group + * viewed. Built from the group's entries: its thumbnail strip can be virtualized out of the DOM. + */ +export function workGroupImageGallery( + viewedImages: ReadonlyArray<{ readonly path: string; readonly item: ExpandedImageItem | null }>, + clickedPath: string | null, + preview: ExpandedImagePreview, +): ExpandedImagePreview { + const selected = preview.images[preview.index]; + if (preview.images.length !== 1 || !selected) return preview; + const images: ExpandedImageItem[] = []; + let index = -1; + for (const viewed of viewedImages) { + if (viewed.path === clickedPath) { + index = images.length; + images.push(selected); + } else if (viewed.item) { + images.push(viewed.item); + } + } + return index < 0 ? preview : { images, index }; +} diff --git a/apps/web/src/components/chat/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index cf64873e2b150..f82515b78bff0 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -22,7 +22,7 @@ import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRunt import { useEffect, useRef, createContext, type MouseEvent, type ReactNode } from "react"; import { type LegendListRef } from "@legendapp/list/react"; import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates"; -import type { PendingApproval } from "../../session-logic"; +import type { TimelineEntry, PendingApproval } from "../../session-logic"; import { type ChatFileAttachment } from "../../types"; import { ExpandedImagePreview } from "./ExpandedImagePreview"; import { type AssistantCitationTarget } from "./AssistantCitationSource"; @@ -44,6 +44,7 @@ export interface TurnItemSource { } export interface TimelineRowSharedState { + timelineEntries: ReadonlyArray; pendingApprovals: ReadonlyMap; respondingRequestIds: ReadonlyArray; canOperateThread: boolean; diff --git a/apps/web/src/components/chat/useComposerFocus.ts b/apps/web/src/components/chat/useComposerFocus.ts new file mode 100644 index 0000000000000..2dbf82308f457 --- /dev/null +++ b/apps/web/src/components/chat/useComposerFocus.ts @@ -0,0 +1,18 @@ +import type { ComposerHandleRef } from "../../composerHandleContext"; +import { useStableCallback } from "../../hooks/useStableCallback"; +import { isModelPickerOpen } from "../../modelPickerVisibility"; + +// Kept out of ChatView: a compiler-memoized closure there pins its render's scope, which pins the +// previous render's, so every thread copy ChatView showed stayed alive until it unmounted. +export function useComposerFocus(composerRef: ComposerHandleRef) { + const focusComposer = useStableCallback(() => { + composerRef.current?.focusAtEnd(); + }); + const scheduleComposerFocus = useStableCallback(() => { + window.requestAnimationFrame(() => { + // The model picker stays open through its own changes, so it keeps focus. + if (!isModelPickerOpen()) focusComposer(); + }); + }); + return { focusComposer, scheduleComposerFocus }; +} diff --git a/apps/web/src/components/chat/usePendingThreadRequests.ts b/apps/web/src/components/chat/usePendingThreadRequests.ts index da8d5bf7d32fa..e357066d1d7d3 100644 --- a/apps/web/src/components/chat/usePendingThreadRequests.ts +++ b/apps/web/src/components/chat/usePendingThreadRequests.ts @@ -22,7 +22,6 @@ import { useShallow } from "zustand/react/shallow"; import { type DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { useStableCallback } from "../../hooks/useStableCallback"; import { getUploadedAttachments, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; -import { reviewCommentContextRecord } from "../../lib/composerContextRecords"; import { buildPendingUserInputAnswers, setPendingUserInputCustomAnswer, @@ -33,6 +32,7 @@ import { carryDisplacedCustomAnswerIntoPrompt, withdrawDisplacedCustomAnswerFromPrompt, derivePendingUserInputProgress, + answerContextRecords, projectPendingUserInputAnswer, threadContextsReferencedByAnswer, } from "../../pendingUserInput"; @@ -300,10 +300,7 @@ export function usePendingThreadRequests(input: { if (userInputResponsesInFlight.current.has(responseKey)) return; const attachmentsByQuestionId = new Map(); const providerAnswers = { ...answers }; - // Diff comments land in the thread draft even when their chip is in an answer. - const reviewCommentRecords = ( - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.reviewComments ?? [] - ).map(reviewCommentContextRecord); + const threadDraft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); for (const question of pendingInput.questions) { const target = questionAttachmentDraftId( environmentId, @@ -313,10 +310,10 @@ export function usePendingThreadRequests(input: { ); if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return; const draft = useComposerDraftStore.getState().getComposerDraft(target); - providerAnswers[question.id] = projectPendingUserInputAnswer(answers[question.id], [ - ...(draft?.threadContexts ?? []), - ...reviewCommentRecords, - ]); + providerAnswers[question.id] = projectPendingUserInputAnswer( + answers[question.id], + answerContextRecords(draft, threadDraft), + ); const attachments = draft ? [...draft.images, ...draft.files] : []; if (attachments.length === 0) continue; const uploaded = getUploadedAttachments({ environmentId, images: attachments }); diff --git a/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx b/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx index 6b66bed808925..cb00e5ab97a50 100644 --- a/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx +++ b/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx @@ -1,8 +1,9 @@ import { UserButton, useAuth } from "@clerk/react"; -import { LogInIcon } from "lucide-react"; +import { LogInIcon, RotateCwIcon } from "lucide-react"; import { hasCloudPublicConfig } from "../../cloud/publicConfig"; import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar"; +import { retryClerkLoad, useClerkLoadFailed } from "./clerkLoadFailure"; import { T3_CONNECT_ACCOUNT_PAGES } from "./T3ConnectAccountPages"; import { useT3ConnectAuthPrompt } from "./useT3ConnectAuthPrompt"; @@ -49,8 +50,21 @@ function ConfiguredT3ConnectSidebarAvatar() { function ConfiguredT3ConnectSidebarSignIn() { const { isLoaded, isSignedIn } = useAuth(); + const loadFailed = useClerkLoadFailed(); const { openAuthPrompt } = useT3ConnectAuthPrompt(); + if (loadFailed) { + return ( + + + + + Retry T3 Connect + + + + ); + } if (!isLoaded || isSignedIn) return null; return ( diff --git a/apps/web/src/components/clerk/clerkLoadFailure.ts b/apps/web/src/components/clerk/clerkLoadFailure.ts new file mode 100644 index 0000000000000..b2fa0077d75ce --- /dev/null +++ b/apps/web/src/components/clerk/clerkLoadFailure.ts @@ -0,0 +1,11 @@ +import { useClerk } from "@clerk/react"; + +export function useClerkLoadFailed() { + return useClerk().status === "error"; +} + +export function retryClerkLoad() { + // Clerk caches its failed script load for the life of the page and never + // retries, so a reload is the only recovery. + window.location.reload(); +} diff --git a/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx b/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx index b87c0d5a88b28..c81c1853f173c 100644 --- a/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx +++ b/apps/web/src/components/clerk/useT3ConnectAuthPrompt.tsx @@ -2,10 +2,15 @@ import { useClerk } from "@clerk/react"; import { isElectron } from "../../env"; import { resolveClerkSignInProps } from "./authRedirect"; +import { retryClerkLoad } from "./clerkLoadFailure"; export function useT3ConnectAuthPrompt() { const clerk = useClerk(); const openAuthPrompt = () => { + if (clerk.status === "error") { + retryClerkLoad(); + return; + } clerk.openSignIn(resolveClerkSignInProps(window.location.href, isElectron)); }; return { openAuthPrompt }; diff --git a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx index 53085ecd50ea6..c287b6544b851 100644 --- a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx +++ b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx @@ -9,6 +9,7 @@ import { import { isElectron } from "../../env"; import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page"; import { resolveClerkSignInProps } from "../clerk/authRedirect"; +import { retryClerkLoad, useClerkLoadFailed } from "../clerk/clerkLoadFailure"; import { Button } from "../ui/button"; const invalidLinkMessage = { @@ -22,6 +23,7 @@ export function ConnectCliAuthorizeSurface() { const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href))); const clerk = useClerk(); const { isLoaded, isSignedIn } = useAuth(); + const loadFailed = useClerkLoadFailed(); const signInOpened = useRef(false); const redirecting = useRef(false); @@ -77,7 +79,13 @@ export function ConnectCliAuthorizeSurface() { : "Sign in to continue authorizing T3 Connect for your CLI." } /> - {isLoaded && !isSignedIn ? ( + {loadFailed ? ( +
+ +
+ ) : isLoaded && !isSignedIn ? (
+ {loadFailed ? ( + + ) : ( + + )} ); } diff --git a/apps/web/src/components/preview/PreviewChromeRow.tsx b/apps/web/src/components/preview/PreviewChromeRow.tsx index 90175cd0b4259..8008990cd2835 100644 --- a/apps/web/src/components/preview/PreviewChromeRow.tsx +++ b/apps/web/src/components/preview/PreviewChromeRow.tsx @@ -32,6 +32,7 @@ interface Props { onBack: () => void; onForward: () => void; onRefresh: () => void; + onStopLoading: () => void; onSubmit: (url: string) => void; onOpenInBrowser?: (() => void) | undefined; onCapture?: ((record: boolean) => void) | undefined; @@ -61,6 +62,7 @@ export function PreviewChromeRow({ onBack, onForward, onRefresh, + onStopLoading, onSubmit, onOpenInBrowser, onCapture, @@ -135,7 +137,7 @@ export function PreviewChromeRow({
diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx index 6eb6d0ba91076..f7cb3082491e9 100644 --- a/apps/web/src/components/preview/PreviewView.tsx +++ b/apps/web/src/components/preview/PreviewView.tsx @@ -334,6 +334,11 @@ export function PreviewView({ else if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId); }; + const handleStopLoading = () => { + if (isServerTab) serverSurfaceRef.current?.stopLoading(); + else if (previewBridge && runtimeTabId) void previewBridge.stopLoading(runtimeTabId); + }; + const adjustServerTab = async (change: Omit) => { if (!tabId) return; const result = await adjust({ @@ -984,6 +989,7 @@ export function PreviewView({ onBack={handleBack} onForward={handleForward} onRefresh={handleRefresh} + onStopLoading={handleStopLoading} onSubmit={(next) => void handleSubmitUrl(next)} onOpenInBrowser={tabId ? handleOpenInBrowser : undefined} onCapture={previewBridge && tabId && !isServerTab ? handleCapture : undefined} diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx new file mode 100644 index 0000000000000..9bb9e746ea12f --- /dev/null +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx @@ -0,0 +1,121 @@ +import "~/index.css"; + +import { RegistryContext } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { type DeviceServiceState, type EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { useState } from "react"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { + type PreviewMiniPlayerSource, + selectThreadPreviewMiniPlayer, + usePreviewMiniPlayerStore, +} from "../../previewMiniPlayerStore"; +import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { deviceEnvironment } from "../../state/device"; +import { ChatCanvas } from "../chat/ChatCanvas"; +import { createChatCanvasStore } from "../chat/canvasStore"; +import { deviceStreamScreenAtom } from "../device/deviceStreamSession"; +import { ThreadPreviewMiniPlayer, useThreadPreviewCanvasSource } from "./ThreadPreviewMiniPlayer"; + +vi.mock(import("../device/DeviceStreamView"), () => ({ + DeviceStreamView: (({ viewId }: { viewId: string }) => ( +
+ )) as never, +})); + +const threadRef = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-1")); +const phone: PreviewMiniPlayerSource = { + kind: "device", + hostId: "local", + deviceId: "phone", + platform: "ios", + name: "Phone", +}; + +function Harness() { + const [store] = useState(createChatCanvasStore); + const miniPlayer = usePreviewMiniPlayerStore((state) => + selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef), + ); + const preview = useThreadPreviewCanvasSource(threadRef, miniPlayer); + return ( + + {miniPlayer ? ( + + ) : null} + + ); +} + +it("holds its frame through a source change and stops when the gesture is interrupted", async () => { + using _state = vi + .spyOn(deviceEnvironment, "state") + .mockReturnValue(Atom.make>(AsyncResult.initial())); + using _store = { + [Symbol.dispose]: () => usePreviewMiniPlayerStore.getState().removeThread(threadRef), + }; + usePreviewMiniPlayerStore.getState().open(threadRef, phone); + const container = document.createElement("div"); + container.style.cssText = "display:flex;position:fixed;inset:0;width:1200px;height:800px"; + await using screen = await render( + + + , + { container }, + ); + const player = screen.container.querySelector("[data-preview-mini-player]")!; + const handle = (direction: string) => + player.querySelector(`[data-preview-mini-player-resize="${direction}"]`)!; + const rect = () => { + const { left, top, right, bottom } = player.getBoundingClientRect(); + return { left, top, right, bottom }; + }; + const point = (target: HTMLElement, type: string, x: number, y: number, buttons: number) => + act(() => + target.dispatchEvent( + new PointerEvent(type, { + pointerId: 1, + pointerType: "mouse", + isPrimary: true, + button: type === "pointermove" ? -1 : 0, + buttons, + clientX: x, + clientY: y, + bubbles: true, + cancelable: true, + }), + ), + ); + const viewId = screen.getByTestId("stream").element().getAttribute("data-view-id")!; + const portrait = rect(); + + // Held without moving while the device rotates: the frame waits for the release. + await point(handle("northwest"), "pointerdown", portrait.left, portrait.top, 1); + await act(() => + appAtomRegistry.set(deviceStreamScreenAtom(viewId), { + width: 1_000, + height: 2_000, + orientation: "landscape_left", + }), + ); + expect(rect()).toEqual(portrait); + + // The release never arrived, so the next buttonless move ends the gesture where it was held. + await point(handle("northwest"), "pointermove", portrait.left - 200, portrait.top - 200, 0); + const landscape = rect(); + expect({ right: landscape.right, bottom: landscape.bottom }).toEqual({ + right: portrait.right, + bottom: portrait.bottom, + }); + expect(landscape.right - landscape.left).toBe(2 * (landscape.bottom - landscape.top)); + await point(handle("northwest"), "pointermove", portrait.left - 300, portrait.top - 300, 1); + expect(rect()).toEqual(landscape); + + await point(handle("west"), "pointerdown", landscape.left, landscape.top + 10, 1); + await act(() => window.dispatchEvent(new Event("blur"))); + await point(handle("west"), "pointermove", landscape.left - 100, landscape.top + 10, 1); + expect(rect()).toEqual(landscape); +}); diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 8e6c8fc42068a..3e4dba8d879ca 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -6,6 +6,7 @@ import { type PointerEvent as ReactPointerEvent, type ReactNode, useEffect, + useEffectEvent, useRef, useState, } from "react"; @@ -59,28 +60,19 @@ import { previewBridge } from "./previewBridge"; import { PreviewUnreachable } from "./PreviewUnreachable"; import { showPreviewPopup } from "./showPreviewPopup"; import { - clampPreviewMiniPlayerPosition, + type PreviewMiniPlayerGesture, + settlePreviewMiniPlayerResize, + stepPreviewMiniPlayerGesture, +} from "./previewMiniPlayerGesture"; +import { PREVIEW_MINI_PLAYER_CORNER_RADIUS, PREVIEW_MINI_PLAYER_WEBVIEW_Z_INDEX, type PreviewMiniPlayerFrame, - resizePreviewMiniPlayer, resolveDeviceMiniPlayerCornerRadius, resolveDeviceMiniPlayerSourceSize, resolvePreviewMiniPlayerSourceSize, } from "./previewMiniPlayerLayout"; -interface PointerGesture { - readonly pointerId: number; - readonly pointerType: string; - readonly pointerX: number; - readonly pointerY: number; - readonly frame: PreviewMiniPlayerFrame; - readonly direction: BrowserViewportResizeDirection | null; - moved: boolean; -} - -const HANDLE_TAP_SLOP_PX = 6; - interface Props { readonly threadRef: ScopedThreadRef; readonly miniPlayer: PreviewMiniPlayerState; @@ -111,6 +103,13 @@ const useStreamedSourceSize = create<{ readonly viewport: PreviewStreamViewport; } | null>(() => null); +// The source size a resize in progress lays the frame out from, so a source that changes shape +// under a held handle cannot resize the player by itself. Same single slot as above. +const useHeldSourceSize = create<{ + readonly key: string; + readonly source: PreviewMiniPlayerSize; +} | null>(() => null); + const NO_DEVICE_SCREEN_ATOM = Atom.make(null).pipe( Atom.withLabel("device-stream-screen:none"), ); @@ -178,6 +177,11 @@ export function useThreadPreviewCanvasSource( ? deviceStreamScreenAtom(miniPlayerDeviceViewId(threadRef, source)) : NO_DEVICE_SCREEN_ATOM, ); + const heldSource = useHeldSourceSize((state) => + threadRef && sourceKey !== null && state?.key === streamedSourceKey(threadRef, sourceKey) + ? state.source + : null, + ); if (!miniPlayer || !source || sourceKey === null) return null; if (source.kind === "browser" && !browser.snapshot) return null; return { @@ -186,9 +190,10 @@ export function useThreadPreviewCanvasSource( position: miniPlayer.position, lastInteraction: miniPlayer.lastInteraction, source: - source.kind === "browser" + heldSource ?? + (source.kind === "browser" ? browser.sourceSize - : resolveDeviceMiniPlayerSourceSize(source.platform, screen), + : resolveDeviceMiniPlayerSourceSize(source.platform, screen)), }; } @@ -446,7 +451,8 @@ function MiniPlayerShell({ readonly children: (frame: PreviewMiniPlayerFrame) => ReactNode; }) { const canvas = useChatCanvas(); - const gestureRef = useRef(null); + const gestureRef = useRef(null); + const captureRef = useRef(null); // Touch toggles the pill after the tap's click so that click cannot land on the newly opened pill. const [pillOpen, setPillOpen] = useState(false); const handleTappedRef = useRef(false); @@ -463,6 +469,7 @@ function MiniPlayerShell({ }, [pillOpen]); const container = canvas?.container ?? null; const sourceKey = previewMiniPlayerSourceKey(miniPlayer.source); + const heldSourceKey = streamedSourceKey(threadRef, sourceKey); const frame = canvas?.previewKey === sourceKey ? canvas.layout.frame : null; const radius = frame ? cornerRadius(frame) : PREVIEW_MINI_PLAYER_CORNER_RADIUS; @@ -472,11 +479,54 @@ function MiniPlayerShell({ usePreviewMiniPlayerStore.getState().close(threadRef); }; + /** Every way a gesture stops comes through here; returns the gesture it ended. */ + const finishGesture = () => { + const gesture = gestureRef.current; + if (!gesture) return null; + gestureRef.current = null; + handleTappedRef.current = false; + const handle = captureRef.current; + captureRef.current = null; + if (handle?.hasPointerCapture(gesture.pointerId)) { + handle.releasePointerCapture(gesture.pointerId); + } + if (gesture.direction === null) return gesture; + useHeldSourceSize.setState((state) => (state?.key === heldSourceKey ? null : state), true); + const settled = + frame && container + ? settlePreviewMiniPlayerResize({ + frame, + direction: gesture.direction, + held: gesture.source, + source: sourceSize, + container, + }) + : null; + if (settled) { + usePreviewMiniPlayerStore + .getState() + .resize(threadRef, sourceKey, settled.width, { x: settled.x, y: settled.y }); + } + return gesture; + }; + const endInterruptedGesture = useEffectEvent(() => { + finishGesture(); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window blur ends a gesture whose release went to another window, and unmount ends one in progress + useEffect(() => { + window.addEventListener("blur", endInterruptedGesture); + return () => { + window.removeEventListener("blur", endInterruptedGesture); + useHeldSourceSize.setState((state) => (state?.key === heldSourceKey ? null : state), true); + }; + }, [heldSourceKey]); + const beginGesture = ( event: ReactPointerEvent, direction: BrowserViewportResizeDirection | null, ) => { if (event.button !== 0 || !frame) return; + finishGesture(); gestureRef.current = { pointerId: event.pointerId, pointerType: event.pointerType, @@ -484,8 +534,13 @@ function MiniPlayerShell({ pointerY: event.clientY, frame, direction, + source: sourceSize, moved: false, }; + captureRef.current = event.currentTarget; + if (direction !== null) { + useHeldSourceSize.setState({ key: heldSourceKey, source: sourceSize }, true); + } event.currentTarget.setPointerCapture(event.pointerId); event.preventDefault(); event.stopPropagation(); @@ -493,44 +548,39 @@ function MiniPlayerShell({ const handlePointerMove = (event: ReactPointerEvent) => { const gesture = gestureRef.current; - if (!gesture || gesture.pointerId !== event.pointerId || !container) return; - const delta = { x: event.clientX - gesture.pointerX, y: event.clientY - gesture.pointerY }; - if (!gesture.moved && Math.hypot(delta.x, delta.y) < HANDLE_TAP_SLOP_PX) return; - gesture.moved = true; + if (!gesture || !container) return; + const step = stepPreviewMiniPlayerGesture(gesture, event, container); + if (step.kind === "ignore") return; + if (step.kind === "end") { + finishGesture(); + return; + } + if (!gesture.moved) gestureRef.current = { ...gesture, moved: true }; const store = usePreviewMiniPlayerStore.getState(); - if (gesture.direction === null) { - store.move( - threadRef, - sourceKey, - clampPreviewMiniPlayerPosition( - { x: gesture.frame.x + delta.x, y: gesture.frame.y + delta.y }, - container, - gesture.frame, - ), - ); + if (step.kind === "move") { + store.move(threadRef, sourceKey, step.position); return; } - const next = resizePreviewMiniPlayer({ - start: gesture.frame, - direction: gesture.direction, - delta, - source: sourceSize, - container, - }); - store.resize(threadRef, sourceKey, next.width, { x: next.x, y: next.y }); + store.resize(threadRef, sourceKey, step.frame.width, { x: step.frame.x, y: step.frame.y }); }; const endGesture = (event: ReactPointerEvent) => { - const gesture = gestureRef.current; - if (gesture?.pointerId !== event.pointerId) return; - gestureRef.current = null; + if (gestureRef.current?.pointerId !== event.pointerId) return; + const gesture = finishGesture(); handleTappedRef.current = event.type === "pointerup" && - gesture.direction === null && + gesture?.direction === null && gesture.pointerType === "touch" && !gesture.moved; - if (event.currentTarget.hasPointerCapture(event.pointerId)) { - event.currentTarget.releasePointerCapture(event.pointerId); + }; + + // Capture can go without a release or cancel: the handle is replaced, or the platform takes it. + const handleLostCapture = (event: ReactPointerEvent) => { + if ( + gestureRef.current?.pointerId === event.pointerId && + captureRef.current === event.currentTarget + ) { + finishGesture(); } }; @@ -558,6 +608,7 @@ function MiniPlayerShell({ onPointerMove={handlePointerMove} onPointerUp={endGesture} onPointerCancel={endGesture} + onLostPointerCapture={handleLostCapture} onClick={() => { if (!handleTappedRef.current) return; handleTappedRef.current = false; @@ -634,6 +685,7 @@ function MiniPlayerShell({ onPointerMove={handlePointerMove} onPointerUp={endGesture} onPointerCancel={endGesture} + onLostPointerCapture={handleLostCapture} /> ))} diff --git a/apps/web/src/components/preview/openPreviewSession.test.ts b/apps/web/src/components/preview/openPreviewSession.test.ts index 005d44d9468c7..9acfd0eb6c050 100644 --- a/apps/web/src/components/preview/openPreviewSession.test.ts +++ b/apps/web/src/components/preview/openPreviewSession.test.ts @@ -97,6 +97,30 @@ describe("openPreviewSession", () => { }); }, ); + + it.each(["new tab", "link"] as const)( + "opens a server tab from a %s with the default zoom and appearance", + async (entryPoint) => { + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + browserDefaultZoomFactor: 0.8, + browserDefaultAppearance: "dark", + }); + const openPreview = vi.fn(async () => AsyncResult.success(snapshot)); + + if (entryPoint === "link") { + vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server"); + await openUrlInPreview({ openPreview, threadRef, url: "https://t3.chat/" }); + } else { + await openPreviewSession({ openPreview, threadRef, runtime: "server" }); + } + + expect(openPreview).toHaveBeenCalledExactlyOnceWith({ + environmentId: threadRef.environmentId, + input: expect.objectContaining({ runtime: "server", zoomFactor: 0.8, colorScheme: "dark" }), + }); + }, + ); }); describe("openUrlInPreview from a link", () => { diff --git a/apps/web/src/components/preview/openPreviewSession.ts b/apps/web/src/components/preview/openPreviewSession.ts index 99dc6c3e572c4..6c372888de5a2 100644 --- a/apps/web/src/components/preview/openPreviewSession.ts +++ b/apps/web/src/components/preview/openPreviewSession.ts @@ -45,7 +45,9 @@ export async function openPreviewSession( ...(input.url === undefined ? {} : { url: input.url }), viewport: input.viewport ?? defaults.viewport, profileId: input.profileId ?? defaults.profileId, - ...(runtime === undefined || runtime === "desktop" ? {} : { runtime }), + ...(runtime === undefined || runtime === "desktop" + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); if (result._tag === "Failure") { diff --git a/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts b/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts index 069a5782e7fdb..ab11752a66fef 100644 --- a/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts +++ b/apps/web/src/components/preview/openTerminalLinkInPreview.test.ts @@ -3,6 +3,8 @@ import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; +import type { OpenPreviewMutation } from "~/browser/openFileInPreview"; +import * as previewRuntime from "~/browser/previewRuntime"; import { openTerminalLinkInPreview } from "./openTerminalLinkInPreview"; vi.mock("~/previewStateStore", () => ({ @@ -36,6 +38,8 @@ vi.mock("~/browser/browserLinkTarget", () => ({ const hydratedDefaults = { viewport: { _tag: "fixed", width: 1280, height: 720 } as const, profileId: "work", + zoomFactor: 0.8, + appearance: "dark", }; const threadRef = { @@ -69,4 +73,24 @@ describe("openTerminalLinkInPreview", () => { expect(reportError).not.toHaveBeenCalled(); expect(fallbackToBrowser).not.toHaveBeenCalled(); }); + + it("opens a server tab with the default zoom and appearance", async () => { + vi.spyOn(previewRuntime, "previewRuntimeFor").mockReturnValue("server"); + const openPreview = vi.fn(async () => + AsyncResult.failure(Cause.interrupt()), + ); + + await openTerminalLinkInPreview({ + url: "https://t3.chat/", + threadRef, + openPreview, + fallbackToBrowser: vi.fn(), + forceBrowser: false, + }); + + expect(openPreview).toHaveBeenCalledExactlyOnceWith({ + environmentId: threadRef.environmentId, + input: expect.objectContaining({ runtime: "server", zoomFactor: 0.8, colorScheme: "dark" }), + }); + }); }); diff --git a/apps/web/src/components/preview/openTerminalLinkInPreview.ts b/apps/web/src/components/preview/openTerminalLinkInPreview.ts index d160c1ee7ea61..867cc528f9ae8 100644 --- a/apps/web/src/components/preview/openTerminalLinkInPreview.ts +++ b/apps/web/src/components/preview/openTerminalLinkInPreview.ts @@ -64,7 +64,9 @@ export async function openTerminalLinkInPreview( url: input.url, viewport: defaults.viewport, profileId: defaults.profileId, - ...(runtime === undefined ? {} : { runtime }), + ...(runtime === undefined + ? {} + : { runtime, zoomFactor: defaults.zoomFactor, colorScheme: defaults.appearance }), }, }); if (result._tag === "Failure") { diff --git a/apps/web/src/components/preview/previewMiniPlayerGesture.test.ts b/apps/web/src/components/preview/previewMiniPlayerGesture.test.ts new file mode 100644 index 0000000000000..1d9f9035ebf23 --- /dev/null +++ b/apps/web/src/components/preview/previewMiniPlayerGesture.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveChatCanvasLayout } from "../chat/chatCanvasLayout"; +import { + type PreviewMiniPlayerGesture, + settlePreviewMiniPlayerResize, + stepPreviewMiniPlayerGesture, +} from "./previewMiniPlayerGesture"; + +const container = { width: 1_440, height: 900 }; +const frame = { x: 996, y: 433, width: 268, height: 179 }; +const gesture: PreviewMiniPlayerGesture = { + pointerId: 1, + pointerType: "mouse", + pointerX: 996, + pointerY: 433, + frame, + direction: "northwest", + source: { width: 1_200, height: 800 }, + moved: true, +}; +const pointer = { pointerId: 1, buttons: 1, clientX: 936, clientY: 393 }; + +describe("stepPreviewMiniPlayerGesture", () => { + it("ends on a move without the primary button instead of following the hover", () => { + expect(stepPreviewMiniPlayerGesture(gesture, pointer, container).kind).toBe("resize"); + expect(stepPreviewMiniPlayerGesture(gesture, { ...pointer, buttons: 0 }, container)).toEqual({ + kind: "end", + }); + expect(stepPreviewMiniPlayerGesture(gesture, { ...pointer, buttons: 2 }, container)).toEqual({ + kind: "end", + }); + expect(stepPreviewMiniPlayerGesture(gesture, { ...pointer, pointerId: 2 }, container)).toEqual({ + kind: "ignore", + }); + }); + + it("resizes at the shape the gesture started with", () => { + const step = stepPreviewMiniPlayerGesture(gesture, pointer, container); + expect(step).toEqual({ kind: "resize", frame: { x: 936, y: 393, width: 328, height: 219 } }); + }); +}); + +describe("settlePreviewMiniPlayerResize", () => { + it("keeps the corner opposite the handle when the source changed shape mid-resize", () => { + const source = { width: 1_200, height: 1_000 }; + const settled = settlePreviewMiniPlayerResize({ + frame, + direction: "northwest", + held: gesture.source, + source, + container, + }); + expect(settled).toEqual({ x: 1_018, y: 407, width: 246, height: 205 }); + expect( + resolveChatCanvasLayout({ + container, + preview: { + key: "browser:tab", + width: settled!.width, + position: settled, + source, + lastInteraction: "resize", + }, + }).frame, + ).toEqual(settled); + expect( + settlePreviewMiniPlayerResize({ + frame, + direction: "northwest", + held: gesture.source, + source: { width: 600, height: 400 }, + container, + }), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/components/preview/previewMiniPlayerGesture.ts b/apps/web/src/components/preview/previewMiniPlayerGesture.ts new file mode 100644 index 0000000000000..6c5892eab73fd --- /dev/null +++ b/apps/web/src/components/preview/previewMiniPlayerGesture.ts @@ -0,0 +1,93 @@ +import type { BrowserViewportResizeDirection } from "~/browser/browserViewportLayout"; +import type { PreviewMiniPlayerPosition, PreviewMiniPlayerSize } from "~/previewMiniPlayerStore"; + +import { + clampPreviewMiniPlayerPosition, + type PreviewMiniPlayerFrame, + resizePreviewMiniPlayer, +} from "./previewMiniPlayerLayout"; + +const HANDLE_TAP_SLOP_PX = 6; + +export interface PreviewMiniPlayerGesture { + readonly pointerId: number; + readonly pointerType: string; + readonly pointerX: number; + readonly pointerY: number; + readonly frame: PreviewMiniPlayerFrame; + /** Null drags the player; a direction resizes it from that handle. */ + readonly direction: BrowserViewportResizeDirection | null; + /** The source size a resize keeps the frame's shape to until it ends. */ + readonly source: PreviewMiniPlayerSize; + readonly moved: boolean; +} + +interface GesturePointer { + readonly pointerId: number; + readonly buttons: number; + readonly clientX: number; + readonly clientY: number; +} + +export type PreviewMiniPlayerGestureStep = + | { readonly kind: "ignore" } + | { readonly kind: "end" } + | { readonly kind: "move"; readonly position: PreviewMiniPlayerPosition } + | { readonly kind: "resize"; readonly frame: PreviewMiniPlayerFrame }; + +/** What a pointer move does to the gesture in progress. */ +export function stepPreviewMiniPlayerGesture( + gesture: PreviewMiniPlayerGesture, + pointer: GesturePointer, + container: PreviewMiniPlayerSize, +): PreviewMiniPlayerGestureStep { + if (pointer.pointerId !== gesture.pointerId) return { kind: "ignore" }; + // A release the handle never saw (over a native view, another window) leaves only this trace. + if ((pointer.buttons & 1) === 0) return { kind: "end" }; + const delta = { x: pointer.clientX - gesture.pointerX, y: pointer.clientY - gesture.pointerY }; + if (!gesture.moved && Math.hypot(delta.x, delta.y) < HANDLE_TAP_SLOP_PX) { + return { kind: "ignore" }; + } + if (gesture.direction === null) { + return { + kind: "move", + position: clampPreviewMiniPlayerPosition( + { x: gesture.frame.x + delta.x, y: gesture.frame.y + delta.y }, + container, + gesture.frame, + ), + }; + } + return { + kind: "resize", + frame: resizePreviewMiniPlayer({ + start: gesture.frame, + direction: gesture.direction, + delta, + source: gesture.source, + container, + }), + }; +} + +/** + * The frame a finished resize leaves when the source changed shape under it: the new shape, with + * the edges opposite the handle where the gesture left them. Null when the shape is unchanged. + */ +export function settlePreviewMiniPlayerResize(input: { + readonly frame: PreviewMiniPlayerFrame; + readonly direction: BrowserViewportResizeDirection; + readonly held: PreviewMiniPlayerSize; + readonly source: PreviewMiniPlayerSize; + readonly container: PreviewMiniPlayerSize; +}): PreviewMiniPlayerFrame | null { + const { frame, direction, held, source, container } = input; + if (held.width * source.height === source.width * held.height) return null; + return resizePreviewMiniPlayer({ + start: frame, + direction, + delta: { x: 0, y: 0 }, + source, + container, + }); +} diff --git a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx index 212da0d088fe3..1b95a1a563aab 100644 --- a/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx +++ b/apps/web/src/components/pullRequest/PullRequestReviewAnnotation.tsx @@ -305,7 +305,7 @@ export function ReviewThreadCard({ contentEditable={false} onPointerDown={(event) => event.stopPropagation()} > -
+
{thread.isResolved ? ( ) : ( diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx index 9576820832323..0d505c3250f11 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.browser.test.tsx @@ -132,7 +132,8 @@ vi.mock(import("../files/projectFilesQueryState"), async (original) => ({ getProjectFileQueryAtom: () => missingProjectFile, })); -import { useComposerDraftStore } from "../../composerDraftStore"; +import { scopeProjectRef } from "@t3tools/client-runtime/environment"; +import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { appAtomRegistry } from "../../rpc/atomRegistry"; import { assetEnvironment } from "../../state/assets"; import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; @@ -418,6 +419,37 @@ describe("project settings permissions", () => { expect(screen.router.state.location.href).toBe(initialHref); }); + it("moves a draft on the removed checkout to a remaining checkout of the group", async () => { + setup(); + const draftId = DraftId.make("draft-handed-off"); + const [primaryProject, remoteProject] = state.projects; + const drafts = useComposerDraftStore.getState(); + drafts.setLogicalProjectDraftThreadId( + "github.com/example/shared-repo", + scopeProjectRef(primaryId, primaryProject!.id), + draftId, + ); + // "Add to another machine" hands the open draft to the new checkout this way. + drafts.setDraftThreadContext(draftId, { + projectRef: scopeProjectRef(remoteId, remoteProject!.id), + environmentSelection: "manual", + loadBalancedEnvironmentId: null, + }); + drafts.setPrompt(draftId, "keep this prompt"); + await using screen = await mountPanel(); + + await userEvent.click(removeCheckout(screen, "/work/remote")); + await vi.waitFor(() => expect(state.releaseUploads).toHaveBeenCalledOnce()); + + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toMatchObject({ + environmentId: primaryId, + projectId: primaryProject!.id, + }); + expect(useComposerDraftStore.getState().getComposerDraft(draftId)?.prompt).toBe( + "keep this prompt", + ); + }); + it("rechecks every removal target after confirmation before deleting or clearing drafts", async () => { setup(); const confirmed = deferred(); diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index c1e15267234b3..3f370ce7108d3 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -362,6 +362,13 @@ function ProjectDetail({ if (checkProjectAccess(members, "Failed to remove project")) return; const draftStore = useComposerDraftStore.getState(); + const remainingMember = allMembers.find( + (candidate) => + !members.some( + (member) => + member.environmentId === candidate.environmentId && member.id === candidate.id, + ), + ); for (const member of members) { if (checkProjectAccess([member], "Failed to remove project")) return; const memberThreads = projectThreads.filter( @@ -388,7 +395,13 @@ function ProjectDetail({ memberThreads.map((thread) => scopeThreadRef(thread.environmentId, thread.id)), ); const projectDraftThread = draftStore.getDraftThreadByProjectRef(projectRef); - if (projectDraftThread) { + if (projectDraftThread && remainingMember) { + draftStore.setDraftThreadContext(projectDraftThread.draftId, { + projectRef: scopeProjectRef(remainingMember.environmentId, remainingMember.id), + environmentSelection: "manual", + loadBalancedEnvironmentId: null, + }); + } else if (projectDraftThread) { draftStore.clearDraftThread(projectDraftThread.draftId); } draftStore.clearProjectDraftThreadId(projectRef); diff --git a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx index f5c4ee146db2a..cff46ee769b17 100644 --- a/apps/web/src/components/settings/ProviderAuthenticationSection.tsx +++ b/apps/web/src/components/settings/ProviderAuthenticationSection.tsx @@ -14,6 +14,7 @@ import { lazy, Suspense, useRef, useState } from "react"; import { CopyIcon } from "lucide-react"; import { writeTextToClipboard } from "../../hooks/useCopyToClipboard"; +import { isWebUrl } from "../../browser/webUrl"; import { ensureLocalApi } from "../../localApi"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; @@ -141,6 +142,10 @@ export function ProviderAuthenticationSection({ async function openBrowser() { if (!url || readOnly) return; + if (!isWebUrl(url)) { + setError("This sign-in link is not a web address, so it was not opened."); + return; + } const requiresConsent = interaction?.type === "browser" && interaction.requiresConsent; // Reserve tabs before awaiting consent; browsers block later opens. const pending = requiresConsent && !window.desktopBridge ? window.open("", "_blank") : null; diff --git a/apps/web/src/components/settings/SettingsPanels.logic.test.ts b/apps/web/src/components/settings/SettingsPanels.logic.test.ts index 7d89aeb8b6021..2704a5020221d 100644 --- a/apps/web/src/components/settings/SettingsPanels.logic.test.ts +++ b/apps/web/src/components/settings/SettingsPanels.logic.test.ts @@ -2,9 +2,16 @@ import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts"; import * as Duration from "effect/Duration"; import { describe, expect, it } from "vite-plus/test"; import { + autoSettleDaysField, + type AutoSettleDaysField, backgroundActivitySharedPolicySettings, + cancelAutoSettleDaysField, + commitAutoSettleDaysField, + editAutoSettleDaysField, + failAutoSettleDaysField, getChangedBrowserSettingLabels, hasChangedBackgroundActivitySettings, + syncAutoSettleDaysField, } from "./SettingsPanels.logic"; describe("background activity settings restore", () => { @@ -115,3 +122,80 @@ describe("getChangedBrowserSettingLabels", () => { ]); }); }); + +describe("auto-settle days field", () => { + const type = (field: AutoSettleDaysField, ...drafts: string[]) => + drafts.reduce(editAutoSettleDaysField, field); + + it("saves only the finished edit, never a value typed on the way", () => { + const typed = type(autoSettleDaysField(14), "1", "", "3", "30"); + expect(typed.pending).toBeNull(); + + const committed = commitAutoSettleDaysField(typed); + expect(committed.submit).toBe(30); + expect(commitAutoSettleDaysField(committed.field).submit).toBeNull(); + + const confirmed = syncAutoSettleDaysField(committed.field, 30); + expect(confirmed).toMatchObject({ saved: 30, draft: "30", pending: null }); + }); + + it.each(["", "0", "91", "1.5", "abc"])("restores the saved value for %j", (draft) => { + const committed = commitAutoSettleDaysField(type(autoSettleDaysField(14), draft)); + expect(committed.submit).toBeNull(); + expect(committed.field.draft).toBe("14"); + }); + + it("a rejected save falls back to the saved value and can be retried", () => { + const submitted = commitAutoSettleDaysField(type(autoSettleDaysField(14), "30")).field; + expect(failAutoSettleDaysField(submitted, submitted.revision).draft).toBe("14"); + + const rejectedWhileCleared = failAutoSettleDaysField(type(submitted, ""), submitted.revision); + expect(rejectedWhileCleared.draft).toBe(""); + expect(commitAutoSettleDaysField(rejectedWhileCleared).field.draft).toBe("14"); + expect(commitAutoSettleDaysField(type(rejectedWhileCleared, "30")).submit).toBe(30); + }); + + it("retyping a value that saved on only some environments sends it again", () => { + const submitted = commitAutoSettleDaysField(type(autoSettleDaysField(14), "30")).field; + const partlySaved = failAutoSettleDaysField( + syncAutoSettleDaysField(submitted, 30), + submitted.revision, + ); + expect(commitAutoSettleDaysField(partlySaved).submit).toBeNull(); + expect(commitAutoSettleDaysField(type(partlySaved, "3", "30")).submit).toBe(30); + }); + + it("returning to the saved value while another save is in flight saves it again", () => { + const submitted = commitAutoSettleDaysField(type(autoSettleDaysField(14), "30")).field; + const back = commitAutoSettleDaysField(type(submitted, "14")); + expect(back.submit).toBe(14); + expect(failAutoSettleDaysField(back.field, submitted.revision)).toBe(back.field); + + const settled = syncAutoSettleDaysField(back.field, 14); + expect(settled.pending).toBeNull(); + expect(syncAutoSettleDaysField(settled, 14)).toBe(settled); + expect(syncAutoSettleDaysField(settled, 20).draft).toBe("20"); + }); + + it("keeps a later save in flight when an earlier one is confirmed", () => { + const first = commitAutoSettleDaysField(type(autoSettleDaysField(14), "30")).field; + const second = commitAutoSettleDaysField(type(first, "60")).field; + const firstConfirmed = syncAutoSettleDaysField(second, 30); + expect(firstConfirmed).toMatchObject({ saved: 30, draft: "60", pending: 60 }); + expect(failAutoSettleDaysField(firstConfirmed, second.revision)).toMatchObject({ + draft: "30", + pending: null, + }); + }); + + it("a cancelled edit restores the saved value and saves nothing", () => { + const cancelled = cancelAutoSettleDaysField(type(autoSettleDaysField(14), "1")); + expect(cancelled).toMatchObject({ draft: "14", dirty: false }); + expect(commitAutoSettleDaysField(cancelled).submit).toBeNull(); + }); + + it("keeps a draft in progress when the saved value changes underneath it", () => { + const typing = type(autoSettleDaysField(14), "4"); + expect(syncAutoSettleDaysField(typing, 30)).toMatchObject({ saved: 30, draft: "4" }); + }); +}); diff --git a/apps/web/src/components/settings/SettingsPanels.logic.ts b/apps/web/src/components/settings/SettingsPanels.logic.ts index bfcccf7a0769b..5927f5cbeab42 100644 --- a/apps/web/src/components/settings/SettingsPanels.logic.ts +++ b/apps/web/src/components/settings/SettingsPanels.logic.ts @@ -8,7 +8,11 @@ import type { SidebarProjectGroupingMode, UnifiedSettings, } from "@t3tools/contracts"; -import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; +import { + DEFAULT_UNIFIED_SETTINGS, + MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, + MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, +} from "@t3tools/contracts/settings"; import { getBackgroundActivityBaseProfile, normalizeBackgroundActivitySettings, @@ -271,3 +275,73 @@ export function backgroundActivityOverrideSettings( }, }; } + +/** + * Saving a shorter age settles threads at once, so typing stays in `draft` until the edit is + * finished. `pending` is the submission in flight; `saved` is the only value a draft falls back to. + */ +export interface AutoSettleDaysField { + readonly saved: number; + readonly draft: string; + readonly dirty: boolean; + readonly pending: number | null; + readonly revision: number; +} + +export function autoSettleDaysField(saved: number): AutoSettleDaysField { + return { saved, draft: String(saved), dirty: false, pending: null, revision: 0 }; +} + +export function syncAutoSettleDaysField( + field: AutoSettleDaysField, + saved: number, +): AutoSettleDaysField { + // An earlier save can be confirmed while a later one is still in flight. + const pending = field.pending === saved ? null : field.pending; + if (field.saved === saved && pending === field.pending) return field; + return { + ...field, + saved, + pending, + draft: field.dirty ? field.draft : String(pending ?? saved), + }; +} + +export function editAutoSettleDaysField( + field: AutoSettleDaysField, + draft: string, +): AutoSettleDaysField { + return { ...field, draft, dirty: true }; +} + +export function cancelAutoSettleDaysField(field: AutoSettleDaysField): AutoSettleDaysField { + return { ...field, draft: String(field.pending ?? field.saved), dirty: false }; +} + +export function commitAutoSettleDaysField(field: AutoSettleDaysField): { + readonly field: AutoSettleDaysField; + readonly submit: number | null; +} { + const current = field.pending ?? field.saved; + const days = field.draft.trim() === "" ? Number.NaN : Number(field.draft); + if ( + !Number.isInteger(days) || + days < MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS || + days > MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS + ) { + return { field: { ...field, draft: String(current), dirty: false }, submit: null }; + } + const settled = { ...field, draft: String(days), dirty: false }; + // An edit ending on the saved value is sent again: a save can land on the shown environment + // and fail on another, and retyping the number is how it is retried. + if (!field.dirty || days === field.pending) return { field: settled, submit: null }; + return { field: { ...settled, pending: days, revision: field.revision + 1 }, submit: days }; +} + +export function failAutoSettleDaysField( + field: AutoSettleDaysField, + revision: number, +): AutoSettleDaysField { + if (field.revision !== revision) return field; + return { ...field, pending: null, draft: field.dirty ? field.draft : String(field.saved) }; +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 238b7f2a60a09..591e34a058a75 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -89,6 +89,11 @@ import { ScopedSwitch } from "./ScopedSwitch"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { + autoSettleDaysField, + cancelAutoSettleDaysField, + commitAutoSettleDaysField, + editAutoSettleDaysField, + failAutoSettleDaysField, getChangedBrowserSettingLabels, getChangedTypographySettingLabels, hasChangedBackgroundActivitySettings, @@ -96,6 +101,7 @@ import { projectGroupingModeFromToggle, readLastEnabledProjectGroupingMode, rememberEnabledProjectGroupingMode, + syncAutoSettleDaysField, } from "./SettingsPanels.logic"; import { SETTINGS_PICKER_TRIGGER_CLASSNAME, @@ -742,14 +748,21 @@ function AutoSettleDaysInput({ onCommit, }: { value: number; - onCommit: (days: number) => void; + onCommit: (days: number, options: { onFailed: () => void }) => void; }) { - const [draft, setDraft] = useState(String(value)); - const [draftSource, setDraftSource] = useState(value); - if (draftSource !== value) { - setDraftSource(value); - setDraft(String(value)); - } + const [stored, setField] = useState(() => autoSettleDaysField(value)); + const field = syncAutoSettleDaysField(stored, value); + if (field !== stored) setField(field); + + const commit = () => { + const next = commitAutoSettleDaysField(field); + setField(next.field); + if (next.submit === null) return; + const { revision } = next.field; + onCommit(next.submit, { + onFailed: () => setField((current) => failAutoSettleDaysField(current, revision)), + }); + }; return ( { - setDraft(event.target.value); - const parsed = Number(event.target.value); - if ( - Number.isInteger(parsed) && - parsed >= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS && - parsed <= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS - ) { - onCommit(parsed); + value={field.draft} + onChange={(event) => setField(editAutoSettleDaysField(field, event.target.value))} + onBlur={commit} + onKeyDown={(event) => { + if (event.nativeEvent.isComposing) return; + if (event.key === "Enter") commit(); + if (event.key === "Escape" && field.dirty) { + // An unhandled Escape closes the settings page, and the blur that follows would save. + event.preventDefault(); + event.stopPropagation(); + setField(cancelAutoSettleDaysField(field)); } }} - onBlur={() => setDraft(String(value))} aria-label="Days of inactivity before auto-settle" /> ); @@ -2103,7 +2116,9 @@ export function ThreadsSettingsPanel() { control={ updateSettings({ sidebarAutoSettleAfterDays: days })} + onCommit={(days, options) => + updateSettings({ sidebarAutoSettleAfterDays: days }, options) + } /> } /> diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 93c3a30f44e72..00bd227c6181f 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -527,6 +527,18 @@ function PoolBar({ index={position + 1} showAccountName={pool.columns.length > 1} /> + ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? ( +
+ + $0 cap +
) : null, )}
diff --git a/apps/web/src/composer-markdown-source.ts b/apps/web/src/composer-markdown-source.ts index c4119b981b18c..c57985f12e345 100644 --- a/apps/web/src/composer-markdown-source.ts +++ b/apps/web/src/composer-markdown-source.ts @@ -221,9 +221,9 @@ function collapseRegion(tr: Transaction, region: TextRange, type: MarkType): voi function collapseMarkdownSource( tr: Transaction, keep: (region: TextRange) => boolean = () => false, -): void { +): TextRange[] { const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK]; - if (!type) return; + if (!type) return []; const regions: TextRange[] = []; for (const region of sourceRegions(tr.doc, type)) { const extended = withAdjacentDelimiters(tr.doc, region); @@ -235,6 +235,7 @@ function collapseMarkdownSource( if (keep(region)) tr.addMark(region.from, region.to, type.create()); else collapseRegion(tr, region, type); } + return regions; } function mapSelection(tr: Transaction, selection: Selection, map: (pos: number) => number) { @@ -248,7 +249,14 @@ function mapSelection(tr: Transaction, selection: Selection, map: (pos: number) /** Parses all shown source first, so a command that splits it keeps its styles. */ export const collapseShownMarkdownSource: Command = ({ tr }) => { - collapseMarkdownSource(tr); + const { selection } = tr; + const type = tr.doc.type.schema.marks[MARKDOWN_SOURCE_MARK]; + const marks = tr.storedMarks ?? selection.$from.marks(); + const regions = collapseMarkdownSource(tr); + // A caret after the closing markers is outside the styles, though parsed text there is inclusive. + if (type && selection.empty && regions.some(({ to }) => to === selection.from)) { + tr.setStoredMarks(type.removeFromSet(marks)); + } return true; }; diff --git a/apps/web/src/composer-rich-text-doc.test.ts b/apps/web/src/composer-rich-text-doc.test.ts index e8a4bdccfcc48..7e50f3773ff35 100644 --- a/apps/web/src/composer-rich-text-doc.test.ts +++ b/apps/web/src/composer-rich-text-doc.test.ts @@ -954,7 +954,7 @@ describe("pasting into a path query", () => { }); it("parses markdown when the paste does not continue a path query", () => { - expect(boldText(paste("Open ", "src/__test__.tsx"))).toEqual(["test"]); + expect(boldText(paste("Open ", "__test__ now"))).toEqual(["test"]); expect(boldText(paste("Open @a ", "__b__"))).toEqual(["b"]); expect(boldText(paste("Open @", " __b__"))).toEqual(["b"]); }); diff --git a/apps/web/src/composer-rich-text.test.ts b/apps/web/src/composer-rich-text.test.ts index f967cfd3a30fa..00c5a44b90809 100644 --- a/apps/web/src/composer-rich-text.test.ts +++ b/apps/web/src/composer-rich-text.test.ts @@ -51,6 +51,58 @@ describe("composer rich text markdown", () => { ]); }); + // regression: #25180 underscores in URLs and paths were read as emphasis + it("keeps underscores inside URLs, paths, and filenames literal", () => { + for (const text of [ + "Read https://example.com/_handle_/status/1 and open src/__test__.tsx", + "https://example.com/~_user_/a", + "_build_/file.ts", + "edit __init__.py, then", + "see __init__.py:42", + "open src/_a.ts_ and example.com/_handle_.", + "/" + "_".repeat(50_000) + "a", + ]) { + expect(parseInlineMarkdown(text)).toEqual([{ text, marks: [] }]); + } + for (const [text, styled, mark, rest] of [ + ["_see src/a_b.ts_ now", "see src/a_b.ts", "italic", " now"], + ["_read/write access_ now", "read/write access", "italic", " now"], + ["__read/write access__ now", "read/write access", "bold", " now"], + ["_see src/_a.ts_(optional)", "see src/_a.ts", "italic", "(optional)"], + ["__see src/__a.ts__(optional)", "see src/__a.ts", "bold", "(optional)"], + ["_see src/_a.ts_.", "see src/_a.ts", "italic", "."], + ["_notes.md_ here", "notes.md", "italic", " here"], + ["_e.g._ this", "e.g.", "italic", " this"], + ["_and_/or", "and", "italic", "/or"], + ] as const) { + expect(parseInlineMarkdown(text)).toEqual([ + { text: styled, marks: [mark] }, + { text: rest, marks: [] }, + ]); + } + for (const [text, first, second, mark] of [ + ["_yes_/_no_", "yes", "no", "italic"], + ["__yes__/__no__.", "yes", "no", "bold"], + ["_a_b_/_no_", "a_b", "no", "italic"], + ] as const) { + expect(parseInlineMarkdown(text).slice(0, 3)).toEqual([ + { text: first, marks: [mark] }, + { text: "/", marks: [] }, + { text: second, marks: [mark] }, + ]); + } + expect(parseInlineMarkdown("and/_or_")).toEqual([ + { text: "and/", marks: [] }, + { text: "or", marks: ["italic"] }, + ]); + expect(parseInlineMarkdown("_build_/file.ts and _x_, __init__.py and __y__")).toEqual([ + { text: "_build_/file.ts and ", marks: [] }, + { text: "x", marks: ["italic"] }, + { text: ", __init__.py and ", marks: [] }, + { text: "y", marks: ["bold"] }, + ]); + }); + it("keeps code span contents literal", () => { expect(parseInlineMarkdown("`**not bold**`")).toEqual([ { text: "**not bold**", marks: ["code"] }, diff --git a/apps/web/src/composer-rich-text.ts b/apps/web/src/composer-rich-text.ts index 49cca9f5ec93a..80d7679492f4a 100644 --- a/apps/web/src/composer-rich-text.ts +++ b/apps/web/src/composer-rich-text.ts @@ -23,9 +23,52 @@ function sameMarks(left: readonly RichTextMark[], right: readonly RichTextMark[] return left.length === right.length && left.every((mark, index) => mark === right[index]); } +// Brackets, quotes, commas, and Markdown delimiters end a URL or path token; a lone `~` does not. +const PATH_TOKEN = /(?:[\p{L}\p{N}_/.:@%+=&?#-]|(? { + const literal = new Set(); + if (!text.includes("_")) return literal; + for (const match of text.matchAll(PATH_TOKEN)) { + const token = match[0]; + let bodyEnd = token.length; + while (bodyEnd > 0 && ".:?".includes(token[bodyEnd - 1]!)) bodyEnd -= 1; + if (EMPHASIS_ALTERNATIVES.test(token.slice(0, bodyEnd))) continue; + while (bodyEnd > 0 && token[bodyEnd - 1] === "_") bodyEnd -= 1; + const body = token.slice(0, bodyEnd); + // A slash alone is prose (`and/_or_`); a path also has a dot, a scheme or port, or a root. + const isPath = body.includes("/") + ? /^~?\/|[.:]/.test(body) + : FILE_EXTENSION.test(body.slice(body.lastIndexOf("."))); + if (!isPath) continue; + let closesInside = false; + let start = body.indexOf("_"); + while (start !== -1) { + let end = start; + while (body[end] === "_") end += 1; + if (start > 0) { + literal.add(match.index + start); + closesInside ||= !/\w/.test(body[end]!); + } + start = body.indexOf("_", end); + } + // A leading run could only pair with a run inside the name, as in `__init__.py`. + if (closesInside && body[0] === "_") literal.add(match.index); + } + return literal; +} + // Pieces keep source offsets, so callers can map parsed text back onto the // characters it came from; parsing only drops delimiters. function parseInlineMarkdownPieces(text: string): SourcePiece[] { + const literalRuns = literalUnderscoreRuns(text); const root: SourcePiece[] = []; const stack: { delimiter: string; mark: RichTextMark; start: number; pieces: SourcePiece[] }[] = []; @@ -68,6 +111,11 @@ function parseInlineMarkdownPieces(text: string): SourcePiece[] { } let end = index; while (text[end] === char) end += 1; + if (literalRuns.has(index)) { + push(index, end); + index = end; + continue; + } const before = text[index - 1] ?? ""; const after = text[end] ?? ""; const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !/\w/.test(after)); diff --git a/apps/web/src/composer-undo-grouping.ts b/apps/web/src/composer-undo-grouping.ts index 8ccad3a5896bf..2aa3f2a59a310 100644 --- a/apps/web/src/composer-undo-grouping.ts +++ b/apps/web/src/composer-undo-grouping.ts @@ -7,15 +7,21 @@ export const COMPOSER_UNDO_GROUP_DELAY = 1000; export type ComposerChangeKind = "insert" | "delete" | "other"; -/** Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. */ +const CLIPBOARD_EDIT_META = "composerClipboardEdit"; + +/** + * Tag custom paste/cut dispatches; ProseMirror only tags its built-in paths. + * Not `uiEvent`: Tiptap's paste rules would style the already parsed paste a second time. + */ export function markAsClipboardEdit(tr: Transaction, event: "paste" | "cut"): Transaction { - return tr.setMeta("uiEvent", event); + return tr.setMeta(CLIPBOARD_EDIT_META, event); } function changeKindOf(tr: Transaction): ComposerChangeKind | null { if (!tr.docChanged) return null; const uiEvent = tr.getMeta("uiEvent"); if (uiEvent === "paste" || uiEvent === "drop" || uiEvent === "cut") return "other"; + if (tr.getMeta(CLIPBOARD_EDIT_META) != null) return "other"; // IME input replaces its own range on each keystroke; it is still typing. if (tr.getMeta("composition") != null) return "insert"; let kind: ComposerChangeKind | null = null; diff --git a/apps/web/src/lib/addProjectToMachine.ts b/apps/web/src/lib/addProjectToMachine.ts index 2d3bdc5259c88..4143498832e53 100644 --- a/apps/web/src/lib/addProjectToMachine.ts +++ b/apps/web/src/lib/addProjectToMachine.ts @@ -21,6 +21,9 @@ import { sourceControlEnvironment } from "../state/sourceControl"; /** Matches the server's read cap: a larger file would arrive truncated. */ export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024; +/** The server lists at most this many ignored files, so one pick never exceeded it. */ +export const COPIED_FILES_MAX_COUNT = 200; + const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/; /** Env files are the ignored files people almost always want on a new machine. */ diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.ts index b505a4f416200..69aaa68492885 100644 --- a/apps/web/src/localApi.ts +++ b/apps/web/src/localApi.ts @@ -1,5 +1,6 @@ import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/contracts"; +import { isWebUrl } from "./browser/webUrl"; import { requestConfirmDialog } from "./confirmDialog"; import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback"; import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage"; @@ -27,6 +28,7 @@ export function createLocalApi(): LocalApi { return; } + if (!isWebUrl(url)) throw new Error("Unable to open link."); window.open(url, "_blank", "noopener,noreferrer"); }, openSystemSettings: async (pane) => { diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.ts index f57c2d9150709..a2494e9d79275 100644 --- a/apps/web/src/pendingUserInput.test.ts +++ b/apps/web/src/pendingUserInput.test.ts @@ -1,10 +1,11 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { formatInlineContextReference } from "./lib/composerContextReferences"; -import { reviewCommentContextRecord, threadContextReference } from "./lib/composerContextRecords"; +import { threadContextReference } from "./lib/composerContextRecords"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { + answerContextRecords, carryDisplacedCustomAnswerIntoPrompt, derivePendingUserInputProgress, projectPendingUserInputAnswer, @@ -28,9 +29,9 @@ describe("projectPendingUserInputAnswer", () => { ); }); - // regression: #28022 a review comment chip in an answer reached the agent as a bare link - it("sends review comment chips with the comment text and diff", () => { - const comment = reviewCommentContextRecord({ + // regression: #28022, #36293 review comment and preview annotation chips in an answer reached the agent as bare links + it("sends thread draft chips with their full content", () => { + const reviewComment = { id: "file-comment-1", sectionId: "branch", sectionTitle: "Changes", @@ -41,15 +42,36 @@ describe("projectPendingUserInputAnswer", () => { text: "Rename this to line two updated", diff: "@@ -0,0 +2,1 @@\n+line two changed", fenceLanguage: "diff", + }; + const annotation = { + id: "annotation-1", + pageUrl: "http://localhost:3000/", + pageTitle: "Home", + comment: "FIRST NOTE: this features section looks too bare; add three feature cards", + elements: [], + regions: [], + strokes: [], + styleChanges: [], + screenshot: null, + createdAt: "2026-01-01T00:00:00.000Z", + }; + const records = answerContextRecords(undefined, { + reviewComments: [reviewComment], + previewAnnotations: [annotation], }); - const answer = `See my note: ${formatInlineContextReference({ - kind: "review-comment", - contextId: comment.contextId, - label: comment.label, - })}`; - const projected = projectPendingUserInputAnswer(answer, [comment]); + const answer = `See my notes: ${records + .map((record) => + formatInlineContextReference({ + kind: record.kind, + contextId: record.contextId, + label: record.label, + }), + ) + .join(" ")}`; + const projected = projectPendingUserInputAnswer(answer, records); expect(projected).toContain("Rename this to line two updated"); expect(projected).toContain("+line two changed"); + expect(projected).toContain(`comment: ${annotation.comment}`); }); // regression: #18789 answers to pending questions lost exact text and option values diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.ts index 1afc298ca94a8..d356978021e26 100644 --- a/apps/web/src/pendingUserInput.ts +++ b/apps/web/src/pendingUserInput.ts @@ -1,4 +1,6 @@ import type { + PreviewAnnotationContextRecord, + PreviewAnnotationPayload, ReviewCommentContextRecord, ThreadContextRecord, UserInputQuestion, @@ -17,10 +19,40 @@ import { } from "@t3tools/client-runtime/state/pending-user-input"; import { collectInlineContextIds } from "./lib/composerContextReferences"; +import { + previewAnnotationContextRecord, + reviewCommentContextRecord, +} from "./lib/composerContextRecords"; +import type { ReviewCommentContext } from "./reviewCommentContext"; + +type AnswerContextRecord = + | ThreadContextRecord + | ReviewCommentContextRecord + | PreviewAnnotationContextRecord; + +// Diff comments and preview annotations land in the thread draft even when their chip is in an answer. +export function answerContextRecords( + questionDraft: { threadContexts: ReadonlyArray } | null | undefined, + threadDraft: + | { + reviewComments: ReadonlyArray; + previewAnnotations: ReadonlyArray; + } + | null + | undefined, +): AnswerContextRecord[] { + return [ + ...(questionDraft?.threadContexts ?? []), + ...(threadDraft?.reviewComments ?? []).map(reviewCommentContextRecord), + ...(threadDraft?.previewAnnotations ?? []).map((annotation) => + previewAnnotationContextRecord(annotation), + ), + ]; +} export function projectPendingUserInputAnswer( answer: unknown, - records: ReadonlyArray, + records: ReadonlyArray, ) { if (typeof answer !== "string" || records.length === 0) return answer; const recordsById = new Map(records.map((record) => [record.contextId, record])); diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 9ea7861777266..1252bbc391896 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -1404,6 +1404,29 @@ describe("HTML renders in the timeline", () => { ]); }); + it("shows a sent message in place through the turn fold, and only once sent", () => { + const sentMessage = "Draft reply:\n\n> Thanks, Thursday works."; + const send = ( + status: OrchestrationV2TurnItem["status"], + output?: unknown, + ): OrchestrationV2TurnItem => ({ + ...base("render", 2), + status, + type: "dynamic_tool", + toolName: "mcp__t3-code__send_to_user", + input: { message: sentMessage }, + ...(output === undefined ? {} : { output }), + }); + const entries = turn(send("completed", { structuredContent: { sentMessage }, content: [] })); + expect(entries.find((entry) => entry.kind === "sent-message")).toMatchObject({ + id: "render", + runId, + text: sentMessage, + }); + expect(rowsFor(entries, false)).toEqual(["message", "turn-fold", "sent-message", "message"]); + expect(turn(send("running")).some((entry) => entry.kind === "sent-message")).toBe(false); + }); + it("hosts a captured MCP app after its tool row, from any provider's tool", () => { const mcpApp = { attachmentId: "render-thread-app-html", diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index ba745a04e6df2..0590a2014c7ec 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -26,7 +26,11 @@ import { import type { HtmlRenderReference } from "@t3tools/shared/htmlRender"; import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail"; import type { McpAppReference } from "@t3tools/shared/mcpApp"; -import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput"; +import { + htmlRenderFromToolItem, + mcpAppFromToolItem, + sentMessageFromToolItem, +} from "@t3tools/shared/toolOutput"; import { contextCompactionLabel, workEntryIndicatesToolFailure, @@ -133,6 +137,13 @@ export type TimelineEntry = ( readonly runId: RunId | null; readonly htmlRender: HtmlRenderReference; } + | { + readonly id: string; + readonly kind: "sent-message"; + readonly createdAt: string; + readonly runId: RunId | null; + readonly text: string; + } | { readonly id: string; readonly kind: "mcp-app"; @@ -717,6 +728,22 @@ export function deriveTimelineEntriesFromVisibleTurnItems( continue; } + const sentMessage = + item.type === "dynamic_tool" && item.status === "completed" + ? sentMessageFromToolItem(item) + : undefined; + if (sentMessage !== undefined) { + entries.push({ + id: item.id, + kind: "sent-message", + createdAt, + runId: item.runId, + text: sentMessage, + ...attemptMetadata, + }); + continue; + } + if (STANDALONE_V2_ITEM_TYPES.has(item.type)) { entries.push({ id: item.id, diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 51760393f92d9..f0f7e33be50c6 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -328,6 +328,14 @@ export function waitForProjectRemoval(ref: ScopedProjectRef, timeoutMs = 5_000): }); } +/** The thread's loaded timeline, for a handler that reads it once instead of subscribing. */ +export function readThreadTurnItems(ref: ScopedThreadRef) { + return ( + appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(ref))?.projection + .visibleTurnItems ?? [] + ); +} + export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null { return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref)); } diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index 37adcb3f7adad..8471aa5bdd4d5 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -300,6 +300,27 @@ describe("resolvePathLinkTarget", () => { ); }); + it.each([ + ["src/main.ts", "/repo/src/main.ts"], + ["/repo/src/main.ts", "/repo/src/main.ts"], + [String.raw`C:\repo\src\main.ts`, String.raw`C:\repo\src\main.ts`], + ["app/(auth)/page.tsx", "/repo/app/(auth)/page.tsx"], + ])("preserves a TypeScript compiler location on %s", (path, target) => { + const text = `${path}(42,7)`; + const links = extractTerminalLinks(`${text}: error TS2322: Type mismatch`); + expect(links).toEqual([{ kind: "path", text: `${path}:42:7`, start: 0, end: text.length }]); + expect(resolveTerminalLinkTarget(links[0]?.text ?? "", "/repo")).toBe(`${target}:42:7`); + }); + + it.each([ + [String.raw`PS C:\dev\folder (42,7)> `, String.raw`C:\dev\folder (42,7)`], + ["/tmp/report(42,7)", "/tmp/report(42,7)"], + ["src/Program.cs(3,10): error CS1002: x", "/repo/src/Program.cs"], + ])("preserves existing path targets in %s", (line, target) => { + const [link] = extractTerminalLinks(line); + expect(resolveTerminalLinkTarget(link?.text ?? "", "/repo")).toBe(target); + }); + // regression: #36005 OSC 8 file URIs were joined onto the cwd as relative paths it("does not resolve an OSC 8 file URI target against the cwd", () => { expect(resolveTerminalLinkTarget("file:///var/tmp/report.txt", "/workspace/project")).toBe( diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index 920581963258a..844ba00219e81 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -41,9 +41,9 @@ const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]* // Bare paths start only at a segment boundary: hover detection runs this on // every frame, so separator-free output must not be rescanned at every suffix. // For the same reason `]` needs its `[`: trimming a long run of `]` is quadratic. -// Parentheses count only before a slash, so `src/foo.ts(3,10)` stays a compiler location. +// Parenthesized path segments need a following slash to distinguish compiler locations. const FILE_PATH_PATTERN = - /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?]+|(?(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\|[\p{L}\p{M}\p{N}._ -]+[\\/])[^\r\n]*?|[\p{L}\p{M}\p{N}._ -]+\.[\p{L}\p{M}\p{N}_-]+(?::\d+){0,2})\1(?(?::\d+){0,2})/gu; const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/; @@ -107,7 +107,10 @@ function collectMatches( const candidate: TerminalLinkMatch = { kind, - text: trimmed, + text: + kind === "path" && /^:\s+(?:error|warning) TS\d+:/u.test(line.slice(start + trimmed.length)) + ? trimmed.replace(/\((\d+),(\d+)\)$/, ":$1:$2") + : trimmed, start, // A position outside quotes spans the closing quote in the terminal buffer. end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0), diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts index c23924e65d159..9feeed716a616 100644 --- a/apps/web/src/terminal/ghostty/core.test.ts +++ b/apps/web/src/terminal/ghostty/core.test.ts @@ -369,7 +369,7 @@ describe("GhosttyTerminalCore snapshots", () => { expect(core.snapshot()).toEqual(reference.snapshot()); }); - it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => { + it("drops stale text in real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => { const [core, reference] = await Promise.all([createCore(), createCore()]); let state = createSession("hello"); const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR); @@ -398,7 +398,7 @@ describe("GhosttyTerminalCore snapshots", () => { core.write("\r\nstale local text"); state = applyTerminalAttachStreamEvent(state, event); const update = readTerminalOutputUpdate(state.output, cursor); - expect(update.type).toBe("reset"); + expect(update.type).toBe(event.type === "cleared" ? "append" : "reset"); writeTerminalOutputUpdate(core, update); cursor = update.cursor; reference.resetAndWrite(event.type === "cleared" ? "" : "hello"); @@ -413,6 +413,40 @@ describe("GhosttyTerminalCore snapshots", () => { reference.resetAndWrite("hello"); expect(core.snapshot()).toEqual(reference.snapshot()); }); + + it("keeps a running program's screen and input modes when its history is cleared", async () => { + const replies: string[] = []; + const core = await createCore((data) => replies.push(data)); + const modes = () => { + replies.length = 0; + core.write("\x1b[?u"); + return { + alternateScreen: core.isAlternateScreen(), + applicationCursorKeys: core.isApplicationCursorKeys(), + mouseTracking: core.isMouseTracking(), + kittyFlags: replies.join(""), + }; + }; + let state = createSession("\x1b[?1049h\x1b[>7u\x1b[?1;1000;1006h"); + const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR); + writeTerminalOutputUpdate(core, initial); + const live = modes(); + expect(live).toEqual({ + alternateScreen: true, + applicationCursorKeys: true, + mouseTracking: true, + kittyFlags: "\x1b[?7u", + }); + + state = applyTerminalAttachStreamEvent(state, { + type: "cleared", + threadId: "terminal-stream-test", + terminalId: "term-1", + }); + writeTerminalOutputUpdate(core, readTerminalOutputUpdate(state.output, initial.cursor)); + + expect(modes()).toEqual(live); + }); }); describe("GhosttyTerminalCore scrollback", () => { diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index c84650d346683..7e24054d096c1 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -1,7 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; import { + agentWorkingDirectories, claimWorkspaceBasenameLookup, + findAgentDirectoryMatch, pickProjectLinkMatch, pickWorkspaceBasenameMatch, pickWorkspaceLinkMatch, @@ -113,6 +115,75 @@ describe("chat file links into another project", () => { }); }); +// regression: #35337 a path the agent cited inside a checkout no project is rooted at +describe("agentWorkingDirectories", () => { + const directories = (...commands: ReadonlyArray) => + agentWorkingDirectories( + [...commands, "the reply", "cd /work/later"].map((input, index) => ({ + sourceThreadId: "thread", + sourceItemId: `item-${index}`, + item: { type: "command_execution", input }, + })), + { sourceThreadId: "thread", sourceItemId: `item-${commands.length}` }, + ); + + it("lists the folders commands above the reply changed into, the latest first", () => { + expect( + directories( + "cd /work/repo-c && cd /work/repo-b && git diff", + "git status", + `/bin/zsh -lc "cd '/work/my repo'; ls"`, + "cd -P /work/repo-a # not this; cd /work/commented", + "cd /work/repo-c\npwd", + ), + ).toEqual(["/work/repo-c", "/work/repo-a", "/work/my repo", "/work/repo-b"]); + }); + + it("skips operands only the shell can resolve and words that are not the command", () => { + expect( + directories( + "cd docs && cd ../other && cd ~/repo && cd $ROOT/x && cd /work/*/src", + "abcd /work/a; echo cd /work/b; git -C /work/c status; cd /work/d", + `echo "cd /work/g"; echo 'x; cd /work/h' && grep -c "cd /work/i" notes`, + "echo bash -c 'cd /work/j'; cd -", + "cat < notes\ncd /work/k\nEOF", + "cd /work/e\\ f && cd `pwd`/x", + ), + ).toEqual(["/work/d"]); + }); +}); + +// regression: #35337 a bare file name the agent cited from a subfolder of an unregistered checkout +describe("findAgentDirectoryMatch", () => { + const search = (found: Record>) => (root: string) => + Promise.resolve({ + root, + entries: (found[root] ?? []).map((path) => ({ path, kind: "file" as const })), + }); + + it("opens the one file of that name in the latest folder the agent worked in", async () => { + expect( + await findAgentDirectoryMatch( + "config.test.yaml", + ["/work/repo-b/server", "/work/repo-b", "/work/repo-c"], + search({ + "/work/repo-b/server": ["config.test.yaml"], + "/work/repo-b": ["server/config.test.yaml"], + "/work/repo-c": ["config.test.yaml"], + }), + ), + ).toBe("/work/repo-b/server/config.test.yaml"); + }); + + it("passes over a folder without the file, and opens nothing when none has it", async () => { + const found = search({ "/work/repo-c": ["etc/config.test.yaml"] }); + expect( + await findAgentDirectoryMatch("config.test.yaml", ["/work/repo-b", "/work/repo-c"], found), + ).toBe("/work/repo-c/etc/config.test.yaml"); + expect(await findAgentDirectoryMatch("config.test.yaml", ["/work/repo-b"], found)).toBeNull(); + }); +}); + describe("claimWorkspaceBasenameLookup", () => { it("keeps only the newest claim, whatever order the lookups settle in", () => { const first = claimWorkspaceBasenameLookup(); diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index c60a2173e971e..d3a97e328aff5 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -35,6 +35,7 @@ "scripts/verify-built-boot.ts", "scripts/warm-dep-cache.ts", "../../scripts/lib/public-config.ts", + "../../scripts/lib/tagged-source-version.ts", "../../scripts/lib/third-party-licenses.ts" ] } diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 3dd6b9edc4489..4dd23686add40 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -19,6 +19,7 @@ import { } from "@t3tools/shared/devProxy"; import { loadRepoEnv } from "../../scripts/lib/public-config"; +import { resolveTaggedSourceVersion } from "../../scripts/lib/tagged-source-version"; import { thirdPartyLicensesPlugin } from "../../scripts/lib/third-party-licenses"; import { tailwindPlugins } from "./vite/tailwind"; import { warmBundledDevPlugin } from "./vite/warmBundledDev"; @@ -45,7 +46,6 @@ const configuredRelayTracingToken = repoEnv.VITE_RELAY_OTLP_TRACES_TOKEN?.trim() const configuredHostedAppChannel = process.env.VITE_HOSTED_APP_CHANNEL?.trim() || ""; const configuredReleaseChannel = process.env.T3CODE_BUILT_DEV === "1" ? "dev" : process.env.VITE_RELEASE_CHANNEL?.trim() || ""; -const configuredAppVersion = process.env.APP_VERSION?.trim() || pkg.version; const configuredDesktopUpdateRepository = process.env.T3CODE_DESKTOP_UPDATE_REPOSITORY?.trim() || process.env.GITHUB_REPOSITORY?.trim() || @@ -320,7 +320,14 @@ const configuredAllowedHosts = (process.env.T3CODE_DEV_ALLOWED_HOSTS ?? "") .filter((entry) => entry.length > 0); const allowedHosts = [".ts.net", ...configuredAllowedHosts]; -export default defineConfig(() => { +export default defineConfig(({ command }) => { + // `vp dev` and `--built` dev pair this client with a server run from source, which reports the + // manifest version. Only a production build is paired with a packed server. + const configuredAppVersion = + process.env.APP_VERSION?.trim() || + (command === "build" && !builtDev + ? resolveTaggedSourceVersion(`${import.meta.dirname}/../..`, pkg.version) + : pkg.version); return { run: { tasks: { diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md index f852d8a81c777..537ffcc4a44ae 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -250,6 +250,15 @@ Choose **Delete now** to run the enabled rules immediately. The latest results s worktrees were removed or kept and why, plus any failures. Results also list folders in the worktree folder that no thread uses, with their sizes; cleanup never removes them, so remove them manually if you want. +The inactive and settled retention periods also apply to the folders of +[threads without a project](./thread-sidebar.md#start-without-a-project). Those folders are not +Git repositories, so their files are deleted with them and cannot be recovered; the thread stays, +and its next turn starts in a new, empty folder. A folder is kept when it has a Git repository +anywhere inside it or when its thread has an enabled scheduled task. Every file in such a folder +counts as untracked, so only **Edited tracked files** removes a folder that holds anything other +than `node_modules`; the other two rules remove only empty folders. Folders that no thread uses +are listed here too. + Browser captures and rotated logs have separate retention periods. Expired capture links stop working. Current logs, message attachments, and browser profiles are kept. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 4d1633bba43a1..332f4e2959606 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -13,10 +13,11 @@ Its branch and workspace mode come from your configured defaults. To continue in an existing worktree, use **New thread in this worktree** from the branch toolbar. On mobile, **New thread** starts in the current thread's project, or else in the -last project you opened or chose on that device. If neither is available, the -project picker opens. Turn off **Settings → General → Use last project** to -choose a project every time. When you pick a project that is on more than one -machine, the thread starts on a connected one if any is connected. +project the thread list is filtered to, or else in the last project you opened +or chose on that device. If none is available, the project picker opens. Turn +off **Settings → General → Use last project** to choose a project every time. +When you pick a project that is on more than one machine, the thread starts on +a connected one if any is connected. When you change a new thread's project, T3 Code stays in the current environment if that project exists there. Otherwise it selects an environment that has it. diff --git a/evals/mcp-tool-use/cases/mid-turn-messages.ndjson b/evals/mcp-tool-use/cases/mid-turn-messages.ndjson new file mode 100644 index 0000000000000..5a2d5b946bb27 --- /dev/null +++ b/evals/mcp-tool-use/cases/mid-turn-messages.ndjson @@ -0,0 +1,4 @@ +{"id": "draft-before-question-sent-in-full", "area": "mid-turn-messages", "kind": "bad", "pattern": "draft written before AskUserQuestion reaches the user only as a progress-update summary", "experience": "The agent drafted an email reply, then opened a question card about it. Claude returned the draft as a progress update before the tool call, so the user saw a one-line summary and answered a card about a draft they never read.", "rule": "Text the user must read in full before the turn ends goes through send_to_user.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"inbox/acme-renewal.txt": "From: Dana Ortiz \nSubject: Renewal for Acme Analytics\n\nHi,\n\nOur annual Acme Analytics contract renews on December 1. The price goes from $18,000 to $21,600. Before I sign, can you confirm whether the SSO add-on is still included and whether we can move the renewal date to January 15?\n\nThanks,\nDana\n"}}, "mocks": {"AskUserQuestion": "The user chose: Send it as written."}}, "prompt": "Draft a reply to the email in inbox/acme-renewal.txt. Sign it 'Morgan'. Show me the whole draft, then ask me with a question card whether to send it as written or make it shorter.", "expect": {"calls": [{"tool": "send_to_user", "args": {"message": "~Morgan"}}, {"tool": "AskUserQuestion"}], "order": ["send_to_user", "AskUserQuestion"]}, "notes": "The question card's own text would also arrive in full, but it is a short question, not a place for a whole draft."} +{"id": "control-draft-as-final-reply", "area": "mid-turn-messages", "kind": "control", "pattern": "a draft with no question after it belongs in the final reply", "experience": "Final messages always arrive in full, so a draft that ends the turn needs no send_to_user.", "rule": "Put everything else in your final reply.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"inbox/acme-renewal.txt": "From: Dana Ortiz \nSubject: Renewal for Acme Analytics\n\nHi,\n\nOur annual Acme Analytics contract renews on December 1. The price goes from $18,000 to $21,600. Before I sign, can you confirm whether the SSO add-on is still included and whether we can move the renewal date to January 15?\n\nThanks,\nDana\n"}}}, "prompt": "Draft a reply to the email in inbox/acme-renewal.txt. Sign it 'Morgan'.", "expect": {"notCalls": ["send_to_user"], "finalTextMust": ["Morgan"]}, "notes": ""} +{"id": "control-progress-updates-stay-text", "area": "mid-turn-messages", "kind": "control", "pattern": "ordinary multi-step work: progress notes are not send_to_user content", "experience": "Status notes between tool calls are what progress updates are for; sending each through send_to_user would flood the thread.", "rule": "send_to_user is for content the user must read in full mid-turn.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"src/price.ts": "export function renewalPrice(base: number, upliftPercent: number) {\n return base + base * upliftPercent;\n}\n", "src/price.test.ts": "import { expect, it } from \"vitest\";\nimport { renewalPrice } from \"./price\";\n\nit(\"applies a 20% uplift\", () => {\n expect(renewalPrice(18_000, 20)).toBe(21_600);\n});\n"}}}, "prompt": "src/price.test.ts fails. Find out why and fix it.", "expect": {"notCalls": ["send_to_user"]}, "notes": ""} +{"id": "answer-before-bookkeeping-call", "area": "mid-turn-messages", "kind": "bad", "pattern": "answer written before a closing bookkeeping tool call; the turn ends on a short note", "experience": "The agent answered the question, ran one more command its project rules ask for at the end of a turn, then wrote two short sentences. The answer came back as a progress update and reached the user as a summary folded under the turn.", "rule": "Text before a tool call may reach the user only as a summary; put the answer in the final reply or send_to_user.", "privacy": "commit-safe", "source": {"issue": "#32877"}, "setup": {"role": "top", "world": {"files": {"scripts/log-question.sh": "#!/bin/sh\necho \"$(date -u +%FT%TZ) $1\" >> .questions.log\n", "src/server/config.ts": "export const config = {\n port: Number(process.env.PORT ?? 4817),\n host: process.env.HOST ?? \"127.0.0.1\",\n};\n"}}, "shellMocks": [{"match": "log-question", "output": ""}], "context": "Contents of /home/user/acme/AGENTS.md (project instructions, checked into the codebase):\n\n# Acme app\n\nAfter you answer a question, run `./scripts/log-question.sh ` so we can track what people ask about."}, "prompt": "Which port and host does the dev server listen on by default, and how do I change them?", "expect": {"shellMust": ["log-question"], "finalTextMust": ["4817", "PORT"]}, "notes": "Passes when the full answer ends the turn. An answer sent with send_to_user and a final reply without it fails, since a plain answer belongs in the final reply."} diff --git a/evals/mcp-tool-use/cases/orchestration.ndjson b/evals/mcp-tool-use/cases/orchestration.ndjson index 28e89df5597e8..df13d9cd6313b 100644 --- a/evals/mcp-tool-use/cases/orchestration.ndjson +++ b/evals/mcp-tool-use/cases/orchestration.ndjson @@ -34,6 +34,8 @@ {"id": "two-children-same-model", "area": "orchestration", "kind": "bad", "pattern": "named-model rule read as a cap", "experience": "Asked for two Sol xhigh subagents, an Astra parent started one and refused the second, citing 'One child per named model' (#24967).", "rule": "Before delegate_task ... One child per named model. (intended: every named model gets a child; read as a cap of one child per model)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}}, "prompt": "Launch two Sol xhigh subagents. Give each a trivial task that only replies OK.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "gpt-6.1-sol", "target.options.reasoningEffort": "xhigh"}}], "minCalls": {"delegate_task": 2}, "callsMustNot": [{"tool": "delegate_task", "args": {"target.model": "~muse"}}, {"tool": "delegate_task", "args": {"target.model": "~claude"}}]}, "notes": "From #24967. One child plus the parent doing the work fails, and so does a second model in place of Sol."} {"id": "worker-counts-per-model", "area": "orchestration", "kind": "bad", "pattern": "named-model rule read as a cap", "experience": "Asked for 20 Sol workers and 20 Luna workers, the agent started one worker per model (#25359).", "rule": "Before delegate_task ... One child per named model. (intended: every named model gets a child; read as a cap of one child per model)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"files": {"tests/flaky/retry.test.ts": "it('retry is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/upload.test.ts": "it('upload is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/session.test.ts": "it('session is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/search.test.ts": "it('search is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/billing.test.ts": "it('billing is flaky', async () => { /* fails 1 in 5 runs */ });\n", "tests/flaky/webhook.test.ts": "it('webhook is flaky', async () => { /* fails 1 in 5 runs */ });\n"}}}, "prompt": "Six tests in tests/flaky/ fail now and then. Start 3 Muse Wonder Full workers and 3 Grok workers, one test file each, to find and fix the flake.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "muse-wonder-full"}}, {"tool": "delegate_task", "args": {"target.model": "grok-4.7"}}], "minCalls": {"delegate_task": 6}}, "notes": "Scaled down from the real 20 Sol + 20 Luna ask. Muse and Grok need delegate_task from every parent, so a native Sol helper cannot pass or fail it."} {"id": "linked-thread-chip-reads-there", "area": "orchestration", "kind": "guard", "pattern": "thread chip from a linked machine read on this one", "experience": "A thread chip from a linked machine names its environmentId; an agent that reads it without passing that id reads this machine, where the thread does not exist.", "rule": "The thread chip names its environmentId; t3_thread_read takes it.", "privacy": "commit-safe", "setup": {"role": "top", "linkedEnvironments": true, "mocks": {"t3_environment_links": {"environmentId": "environment-laptop", "links": [{"environmentId": "environment-vps", "label": "Hetzner VPS", "status": "reachable", "access": "auto-accept-edits", "expiresAt": "2026-12-01T00:00:00.000Z", "lastError": null}], "notListed": "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words."}, "t3_thread_read": {"thread": {"threadId": "thread-deploy-api", "title": "Deploy the API", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Deploy the API to the VPS and check the health endpoint."}, {"position": 2, "createdBy": "assistant", "text": "Deployed. /health returns 200, but /health/db times out after 5s: the API can't reach Postgres on 10.0.0.5:5432."}], "nextPosition": 3, "hasMore": false}}}, "prompt": "Pick up where [Deploy the API](t3-context://v1/thread/thread_deploy-api) left off. What is still failing?", "promptContext": {"records": [{"version": 1, "kind": "thread", "contextId": "thread_deploy-api", "label": "Deploy the API", "environmentId": "environment-vps", "threadId": "thread-deploy-api", "title": "Deploy the API"}]}, "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "thread-deploy-api", "environmentId": "environment-vps"}}], "notCalls": ["t3_environment_link"]}, "source": {"request": "akj on #17130: attach a linked machine's thread without dragging"}} +{"id": "vps-delegate-links-off-names-setting", "area": "orchestration", "kind": "bad", "pattern": "hidden link tools, setting never named", "experience": "With Linked environments off, the default, an agent asked to delegate to the user's VPS searched for t3_environment_link, then said the tool was not in this build and never named the setting that turns it on.", "rule": "The link tools are absent while Settings → Labs → Linked environments is off; the agent tells the user to turn it on there.", "privacy": "commit-safe", "setup": {"role": "top"}, "prompt": "Delegate this to my vps: run `uname -a` there and tell me the result. Do not edit any files here.", "expect": {"textMust": ["Labs", "Linked environments"], "notCalls": ["delegate_task", "t3_environment_links", "t3_environment_link"]}, "source": {"issue": "pingdotgg/t3code#30358"}} +{"id": "vps-delegate-links-on-calls-link", "area": "orchestration", "kind": "control", "pattern": "unlinked machine with Linked environments on", "experience": "With Linked environments on, a machine the user names that is not linked gets a t3_environment_link card, not advice to turn the setting on.", "rule": "A machine the user names that is not linked: call t3_environment_link with a hint from their words.", "privacy": "commit-safe", "setup": {"role": "top", "linkedEnvironments": true, "mocks": {"t3_environment_links": {"environmentId": "environment-laptop", "links": [], "notListed": "Not listed: not linked yet. Call t3_environment_link with a hint from the user's words."}, "t3_environment_link": {"status": "pending", "turnItemId": "turn-item-link-card-1"}}}, "prompt": "Delegate this to my vps: run `uname -a` there and tell me the result. Do not edit any files here.", "expect": {"calls": [{"tool": "t3_environment_link"}], "textMustNot": ["Labs", "([Tt]urn on|[Ee]nable)[^.\\n]*[Ll]inked environments"]}, "source": {"issue": "pingdotgg/t3code#30358"}} {"id": "background-wait-unmatched-id", "area": "orchestration", "kind": "guard", "pattern": "waits on a task ID that matches no background work, then ends the turn as if waiting", "experience": "One agent called t3_background_wait with the literal ID 'placeholder', another with a Claude subagent ID. The tool returned a normal result listing the ID under `unmatched`, so the agent said it would continue when the work came back and ended its turn. Nothing ever woke it.", "rule": "To wait for a background command or Monitor you started (tests, a build), call `t3_background_wait` with its task ID before you end your turn.", "privacy": "commit-safe", "setup": {"role": "top", "harness": "claude", "priorTurns": [{"role": "user", "text": "Run the full test suite in the background and fix whatever fails. It takes about 15 minutes."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "vp test run", "description": "Run the full test suite", "run_in_background": true}, "result": "Command running in background with ID: bq7m2x9k. Output is being written to: /tmp/claude/tasks/bq7m2x9k.output"}, {"tool": "t3_background_wait", "input": {"taskIds": ["placeholder"]}, "result": "default"}]}], "world": {"backgroundTasks": ["bq7m2x9k"], "tests": "The suite started a minute ago and runs for about 15 minutes. Until then /tmp/claude/tasks/bq7m2x9k.output lists 38 passing test files and no failures yet."}}, "prompt": "I'm heading out for a bit. Tell me what failed when it's done.", "expect": {"calls": [{"tool": "t3_background_wait", "args": {"taskIds": ["bq7m2x9k"]}}]}, "source": {"issue": "#29772"}, "notes": "The seeded wait gets T3's real result for an ID the session does not know. The tests are still running, so the only way to keep the thread waiting is a wait on bq7m2x9k. In replay, Sonnet 5.5 and Opus 5.5 also recover from main's success result, so this guards the recovery rather than reproducing the incident. Claude only: t3_background_wait is a Claude tool.", "maxSteps": 8} {"id": "background-wait-matched-id", "area": "orchestration", "kind": "control", "pattern": "waits on the right task ID, then ends the turn", "experience": "With the background command's own ID registered, ending the turn is correct: T3 keeps the thread working and wakes it when the tests finish.", "rule": "To wait for a background command or Monitor you started (tests, a build), call `t3_background_wait` with its task ID before you end your turn.", "privacy": "commit-safe", "setup": {"role": "top", "harness": "claude", "priorTurns": [{"role": "user", "text": "Run the full test suite in the background and fix whatever fails. It takes about 15 minutes."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "vp test run", "description": "Run the full test suite", "run_in_background": true}, "result": "Command running in background with ID: bq7m2x9k. Output is being written to: /tmp/claude/tasks/bq7m2x9k.output"}, {"tool": "t3_background_wait", "input": {"taskIds": ["bq7m2x9k"]}, "result": "default"}]}], "world": {"backgroundTasks": ["bq7m2x9k"], "tests": "The suite started a minute ago and runs for about 15 minutes. Until then /tmp/claude/tasks/bq7m2x9k.output lists 38 passing test files and no failures yet."}}, "prompt": "I'm heading out for a bit. Tell me what failed when it's done.", "expect": {"maxCalls": {"t3_background_wait": 1, "Bash": 3}, "notCalls": ["ScheduleWakeup"]}, "source": {"issue": "#29772"}, "notes": "Same thread as background-wait-unmatched-id, with a wait T3 matched. Guards against a fix that makes agents distrust a good wait and poll; a few looks at the output are ordinary. Claude only.", "maxSteps": 8} {"id": "settle-this-thread-after-cleanup", "area": "orchestration", "kind": "bad", "pattern": "settle read as plain English for finish", "experience": "Asked to clean up scratch files and settle this thread, the agent deleted the files and ended the turn without calling t3_thread_organize (#26749).", "rule": "A request to settle this thread calls t3_thread_organize with action settle.", "privacy": "commit-safe", "notes": "From #26749. Claude defers MCP tools, so only the tool's name is visible until ToolSearch loads it; 'settle' appears only in the t3_thread_organize description.", "setup": {"role": "top", "world": {"files": {"scratch/run-1.log": "ok\n", "scratch/run-2.log": "ok\n", "src/index.ts": "export const x = 1;\n"}}, "mocks": {"t3_thread_organize": {"settlesWhenTurnEnds": true}}}, "prompt": "Clean up the scratch files and settle this thread.", "expect": {"calls": [{"tool": "t3_thread_organize", "args": {"action": "settle"}}], "notCalls": ["t3_thread_update"]}} @@ -42,3 +44,4 @@ {"id": "settle-after-delayed-merge-waits", "area": "orchestration", "kind": "guard", "pattern": "settle before delayed work finishes", "experience": "Asked to merge a PR once its checks pass and then settle this thread, an agent following the #26749 settle bullet can settle in the first turn; a settled thread refuses watch_pull_request and drops PR-watch wakes, so the merge never happens.", "rule": "Asked to settle ... a thread, including this one: call t3_thread_organize. (the request is to settle after the merge, not now)", "privacy": "commit-safe", "notes": "From the CodeRabbit finding on #26765. Settling this thread applies at turn end, and Orchestrator.ts rejects watch wakes on a settled thread. Good: watch #123 and end the turn without settling. gh pr merge --auto plus a settle would still lose the wake that confirms the merge.", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Okay this looks good to me. Any risk merging it?"}, {"role": "assistant", "text": "Low risk. [#123](https://github.com/acme/app/pull/123) only adds an accessible title to the HTML preview frame, and the new test covers it. Two checks are still running: Check and Test Web.", "toolCalls": [{"tool": "Bash", "input": {"command": "gh pr view 123 --json title,files --jq '.title, .files[].path'"}, "result": "fix(web): HTML preview frame gets an accessible title\napps/web/src/HtmlPreview.tsx\napps/web/src/HtmlPreview.test.tsx"}, {"tool": "Bash", "input": {"command": "gh pr checks 123"}, "result": "Lint\tpass\t41s\nTypecheck\tpass\t1m2s\nCheck\tpending\t0\nTest Web\tpending\t0"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/123"}, "result": {"host": "github.com", "repository": "acme/app", "number": 123, "url": "https://github.com/acme/app/pull/123", "alreadyLinked": false}}]}], "mocks": {"watch_pull_request": "default", "link_pull_request": "default", "t3_thread_organize": {"settlesWhenTurnEnds": true}}, "world": {"branch": "fix/html-preview-title", "commits": [{"sha": "abc1234", "subject": "fix(web): HTML preview frame gets an accessible title"}], "diff": "diff --git a/apps/web/src/HtmlPreview.tsx b/apps/web/src/HtmlPreview.tsx\n--- a/apps/web/src/HtmlPreview.tsx\n+++ b/apps/web/src/HtmlPreview.tsx\n@@ -1,3 +1,3 @@\n export function HtmlPreview({ html }: { html: string }) {\n- return