diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index 45f5c9b9f7760..41e4ccecb024d 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -7,6 +7,13 @@ on: permissions: contents: read +# Run-level, not job-level: runs join the group when their event arrives, so a newer push +# always supersedes an older one. A job-level group is joined when the job starts, which +# let an older run's slower job cancel the newer head's job and label from a stale diff. +concurrency: + group: pr-size-${{ github.event.pull_request.number }} + cancel-in-progress: true + jobs: prepare-config: name: Prepare PR size config @@ -120,9 +127,6 @@ jobs: contents: read issues: read pull-requests: write - concurrency: - group: pr-size-${{ github.event.pull_request.number }} - cancel-in-progress: true steps: # This pull_request_target job may fetch untrusted PR commits only as passive # git data. Do not add dependency installs, build/test scripts, or cache diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml index a81f877e69ddd..c8b067e7637dd 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -15,6 +15,17 @@ on: permissions: contents: read +# Per-PR events supersede each other at the run level, in arrival order (a job-level group +# is joined when the job starts, so an older run's slower job could cancel the newer one). +# Other comments and pushes get a unique group so they never cancel a PR's run. +concurrency: + group: >- + ${{ (github.event_name == 'pull_request_target' || + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '/recheck-vouch'))) + && format('pr-vouch-run-{0}', github.event.pull_request.number || github.event.issue.number) + || format('pr-vouch-run-{0}', github.run_id) }} + cancel-in-progress: true + jobs: collect-targets: name: Collect PR targets @@ -74,9 +85,6 @@ jobs: permissions: contents: read pull-requests: write - concurrency: - group: pr-vouch-${{ matrix.target.number }} - cancel-in-progress: true strategy: fail-fast: false matrix: diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts index bd736f46b40fe..eb7838c924f0a 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.test.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.test.ts @@ -2201,3 +2201,15 @@ it.effect.each([false, true])( ); }, ); + +it.each([ + ["preview-config", "Alt+Super+C is already used by Hyprland. Choose another shortcut."], + ["apply-config", "Your config changed since this preview. Review changes again before saving."], +] as const)("tells the renderer why %s failed", (action, reason) => { + const error = new DesktopSnapShot.DesktopSnapShotSetupError({ + action, + reason: "setup-failed", + cause: new Error(reason), + }); + assert.include(error.message, reason); +}); diff --git a/apps/desktop/src/snapShot/DesktopSnapShot.ts b/apps/desktop/src/snapShot/DesktopSnapShot.ts index d995758619bfe..b3d75754b676f 100644 --- a/apps/desktop/src/snapShot/DesktopSnapShot.ts +++ b/apps/desktop/src/snapShot/DesktopSnapShot.ts @@ -262,9 +262,14 @@ export class DesktopSnapShotSetupError extends Schema.TaggedError { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("downloads again when the downloaded update file was deleted before install", () => { + const downloadedFile = "/cache/pending/T3-Code-1.2.4-arm64.zip"; + let installedFileExists: boolean | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + downloadUpdate: Effect.sync(() => { + harness.deletedFiles.delete(downloadedFile); + harness.emit("update-downloaded", { version: "1.2.4", downloadedFile }); + }), + quitAndInstall: Effect.sync(() => { + installedFileExists = !harness.deletedFiles.has(downloadedFile); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* updates.download; + yield* flushCallbacks; + assert.equal(harness.downloadCount(), 1); + + harness.deletedFiles.add(downloadedFile); + const result = yield* updates.installPrepared("1.2.4"); + assert.isTrue(result.accepted); + assert.equal(harness.downloadCount(), 2); + assert.equal(harness.quitAndInstalls(), 1); + assert.isTrue(installedFileExists); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("restores download state and permits retry after interruption", () => Effect.gen(function* () { const actionStarted = yield* Deferred.make(); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 7976503d9e761..32e64502d9333 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -51,6 +51,7 @@ import { reduceDesktopUpdateStateOnCheckStart, reduceDesktopUpdateStateOnDownloadComplete, reduceDesktopUpdateStateOnDownloadFailure, + reduceDesktopUpdateStateOnDownloadLost, reduceDesktopUpdateStateOnDownloadProgress, reduceDesktopUpdateStateOnDownloadStart, reduceDesktopUpdateStateOnInstallFailure, @@ -80,6 +81,7 @@ const UpdateInfo = Schema.Struct({ releaseNotes: Schema.optional(Schema.Unknown), releaseName: Schema.optional(Schema.NullOr(Schema.String)), releaseDate: Schema.optional(Schema.String), + downloadedFile: Schema.optional(Schema.String), }); const DownloadProgressInfo = Schema.Struct({ @@ -403,6 +405,7 @@ export const make = Effect.gen(function* () { const updaterConfiguredRef = yield* Ref.make(false); const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1); const notAppliedVersionRef = yield* Ref.make(Option.none()); + const downloadedFileRef = yield* Ref.make(Option.none()); // The release a track switch's database check cleared. A build crosses to another track only // through such a switch, and never below that release: version order alone cannot tell whether // a Stable knows a Nightly's migrations. @@ -995,6 +998,19 @@ export const make = Effect.gen(function* () { }), ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate")); + const downloadedFileMissing = Ref.get(downloadedFileRef).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(false), + onSome: (path) => + fileSystem.exists(path).pipe( + Effect.map((exists) => !exists), + Effect.orElseSucceed(() => false), + ), + }), + ), + ); + const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* ( expectedVersion?: string, ) { @@ -1007,11 +1023,32 @@ export const make = Effect.gen(function* () { }; } let installVersion = expectedVersion; - // A download can be hours old: a release published since replaces it before restarting. const retained = yield* Ref.get(updateStateRef); - if ( - retained.downloadedVersion !== null && - (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) && + const retainedVersion = retained.downloadedVersion; + const retainsExpectedDownload = + retainedVersion !== null && + (expectedVersion === undefined || retainedVersion === expectedVersion); + // A cache cleaner can delete the archive; Squirrel.Mac would then fail every install attempt. + if (retainsExpectedDownload && (yield* downloadedFileMissing)) { + yield* logUpdaterWarning("the downloaded update file is gone; downloading it again", { + version: retainedVersion, + }); + yield* updateState(reduceDesktopUpdateStateOnDownloadLost); + const download = yield* downloadAvailableUpdate(true); + if (!download.completed) { + return { + accepted: download.accepted, + completed: false, + failed: download.accepted, + state: yield* Ref.get(updateStateRef), + }; + } + if (expectedVersion !== undefined) { + installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion; + } + } else if ( + // A download can be hours old: a release published since replaces it before restarting. + retainsExpectedDownload && (yield* checkForUpdates( "install", "acquire", @@ -1023,7 +1060,7 @@ export const make = Effect.gen(function* () { // electron-updater compares a stale feed with the running build, not the retained download. if ( refreshed.availableVersion === null || - compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0 + compareSemverVersions(refreshed.availableVersion, retainedVersion) <= 0 ) { yield* setState(retained); } else { @@ -1244,6 +1281,7 @@ export const make = Effect.gen(function* () { } return; } + yield* Ref.set(downloadedFileRef, Option.fromNullishOr(info.downloadedFile)); yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version)); yield* logUpdaterInfo("update downloaded", { version: info.version }); }), diff --git a/apps/desktop/src/updates/updateMachine.ts b/apps/desktop/src/updates/updateMachine.ts index 80751315657c0..53785a6a57a34 100644 --- a/apps/desktop/src/updates/updateMachine.ts +++ b/apps/desktop/src/updates/updateMachine.ts @@ -209,6 +209,22 @@ export function reduceDesktopUpdateStateOnDownloadComplete( }; } +export function reduceDesktopUpdateStateOnDownloadLost( + state: DesktopUpdateState, +): DesktopUpdateState { + if (state.downloadedVersion === null) return state; + return { + ...withoutTrackMismatch(state), + status: "available", + availableVersion: state.downloadedVersion, + downloadedVersion: null, + downloadPercent: null, + message: null, + errorContext: null, + canRetry: false, + }; +} + export function reduceDesktopUpdateStateOnInstallFailure( state: DesktopUpdateState, message: string, diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced674..9b8f78e19000c 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -246,6 +246,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { const updateRestartMarkers = new Set(); const updateMarkerContents = new Map(); const installRecords = new Map(); + const deletedFiles = new Set(); let previousInstallRecord = options.installRecord; const isInstallRecord = (path: string) => path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE); @@ -266,6 +267,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { }), ); }, + exists: (path) => Effect.succeed(!deletedFiles.has(path)), makeDirectory: () => Effect.void, writeFileString: (path, data) => Effect.sync(() => { @@ -320,6 +322,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { updateInProgressMarker: () => [...updateMarkerContents].find(([path]) => path.endsWith("/desktop-update-in-progress"))?.[1], installRecords, + /** Paths removed behind the app's back, as by a cache cleaner. */ + deletedFiles, previousInstallRecord: () => previousInstallRecord, downloadCount: () => downloadCount, feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls, diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 50a987787b4e4..9942754660b8e 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -195,7 +195,7 @@ function PoolWindowCard({ const inlineLabels = wide && segmentWidth >= 96; const inlineReset = wide && segmentWidth >= 150; const inlineName = wide && segmentWidth >= 220; - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); const openAccount = (account: LimitAccount) => navigation.navigate("SettingsUsageAccount", { accountKey: account.key, diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 6dfd723e7084a..6c3469c1eb948 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -143,6 +143,12 @@ it.effect( const homeShared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-home-")); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "api", ".git"), { recursive: true }); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "notes")); + // Names are cut to 128 UTF-16 units, never between the halves of an emoji. + const named = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-names-")); + const straddling = NodePath.join(named, `${"a".repeat(127)}🚀`); + const fitting = NodePath.join(named, `${"b".repeat(126)}🚀`); + const padded = NodePath.join(named, `${" ".repeat(127)}🚀`); + for (const folder of [straddling, fitting, padded]) NodeFS.mkdirSync(folder); yield* runCli([ "project", "add", @@ -151,6 +157,12 @@ it.effect( `${shared}${NodePath.sep}`, "--track", `~/${NodePath.basename(homeShared)}`, + "--track", + straddling, + "--track", + fitting, + "--track", + padded, "--base-dir", baseDir, ]).pipe(Effect.provideService(HostProcess.HomeDirectory, NodeOS.tmpdir())); @@ -158,6 +170,9 @@ it.effect( { path: NodePath.join(workspaceRoot, "api"), name: "api", discovered: true }, { path: shared, name: NodePath.basename(shared) }, { path: homeShared, name: NodePath.basename(homeShared) }, + { path: straddling, name: "a".repeat(127) }, + { path: fitting, name: `${"b".repeat(126)}🚀` }, + { path: padded, name: "🚀" }, ]); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 1fa7cc0f3f264..fb11ade0c75dd 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -8,6 +8,7 @@ import { ProjectId, } from "@t3tools/contracts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -401,9 +402,10 @@ const projectAddCommand = Command.make("add", { const named = flags.track .map((folder) => { const resolved = path.resolve(expandHomePath(folder, home)); + const name = (path.basename(resolved) || resolved).trimStart(); return { path: resolved, - name: (path.basename(resolved) || resolved).slice(0, 128).trim(), + name: name.slice(0, splitsSurrogatePair(name, 128) ? 127 : 128).trim(), }; }) .filter( diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index eafda7f3e9b69..41632c169d03f 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -767,5 +767,10 @@ it.live("resolves a path inside a git worktree of the project's repository to th assert.strictEqual(ambiguous._tag, "ThreadUsageError"); assert.include(ambiguous.message, "sample (project-sample)"); assert.include(ambiguous.message, "feature (project-feature)"); + + // An inherited relative GIT_DIR resolves against Git's cwd, where no repository is. + vi.stubEnv("GIT_DIR", ".git"); + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); + assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index fc3476739d1b0..ce74ce4eb2815 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -34,6 +34,7 @@ import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts import { expandHomePath } from "../os-jank.ts"; import * as ProcessRunner from "../processRunner.ts"; import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; +import { unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -327,9 +328,15 @@ const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools /** The checkouts of the git repository at `directory`, or none outside a repository. */ const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) { const processRunner = yield* ProcessRunner.ProcessRunner; + const env = unsetInheritedRepositoryEnv(process.env, yield* HostProcess.Platform); const list = (args: ReadonlyArray) => processRunner - .run({ command: "git", args: ["worktree", "list", "--porcelain", ...args], cwd: directory }) + .run({ + command: "git", + args: ["worktree", "list", "--porcelain", ...args], + cwd: directory, + env, + }) .pipe( Effect.option, Effect.map((result) => diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 41f4241fade68..a0bf8597431dc 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -21,6 +21,7 @@ import { expect, vi } from "vite-plus/test"; import { cli } from "../binCli.ts"; import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts"; +import { matchAgentAnswer } from "./triage.ts"; const cliPath = NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)); @@ -108,6 +109,18 @@ it.live.each([ }), ); +it.each([ + { answer: "2", picked: "codex" }, + { answer: " 1 ", picked: "claude" }, + { answer: "CLAUDE", picked: "claude" }, + { answer: "1.5", picked: undefined }, + { answer: "1x", picked: undefined }, + { answer: "2codex", picked: undefined }, + { answer: "3", picked: undefined }, +])("the agent picker reads $answer as $picked", ({ answer, picked }) => { + expect(matchAgentAnswer([{ id: "claude" }, { id: "codex" }], answer)?.id).toBe(picked); +}); + it.live( "requires an explicit choice when Codex and Antigravity are installed without a terminal", () => diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index df73347cd9fe4..a4c7da2a91e49 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -86,6 +86,17 @@ export class TriageAgentSpawnError extends Schema.TaggedError( + agents: ReadonlyArray, + answer: string, +) => { + const trimmed = answer.trim(); + return ( + agents.find((_, index) => String(index + 1) === trimmed) ?? + agents.find((agent) => agent.id === trimmed.toLowerCase()) + ); +}; + const pickAgent = (agents: ReadonlyArray) => Effect.promise(async () => { const readline = NodeReadlinePromises.createInterface({ @@ -97,14 +108,10 @@ const pickAgent = (agents: ReadonlyArray) => .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`) .join("\n"); for (;;) { - const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim(); - const byNumber = agents[Number.parseInt(answer, 10) - 1]; - if (byNumber !== undefined) { - return byNumber; - } - const byId = agents.find((agent) => agent.id === answer.toLowerCase()); - if (byId !== undefined) { - return byId; + const answer = await readline.question(`Run triage with:\n${menu}\n> `); + const picked = matchAgentAnswer(agents, answer); + if (picked !== undefined) { + return picked; } } } finally { diff --git a/apps/server/src/cloud/serviceSelectionLock.test.ts b/apps/server/src/cloud/serviceSelectionLock.test.ts index d2567de4c0bc5..b061a5587c33a 100644 --- a/apps/server/src/cloud/serviceSelectionLock.test.ts +++ b/apps/server/src/cloud/serviceSelectionLock.test.ts @@ -27,4 +27,42 @@ it.layer(NodeServices.layer)("service selection lock", (it) => { assert.isFalse(yield* fs.exists(lock)); }), ); + + it.effect("waits on a contended live lease until the first holder releases it", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-selection-lock-" }); + const selectionPath = path.join(root, "service-state.json"); + const lock = `${selectionPath}.selection-lock`; + + const releaseFirst = yield* Effect.promise(() => acquireServiceSelectionLock(selectionPath)); + let signalRetryStarted!: () => void; + const retryStarted = new Promise((resolve) => { + signalRetryStarted = resolve; + }); + let releaseRetryGate!: () => void; + const retryGate = new Promise((resolve) => { + releaseRetryGate = resolve; + }); + let secondAcquired = false; + const second = acquireServiceSelectionLock(selectionPath, { + waitForRetry: () => { + signalRetryStarted(); + return retryGate; + }, + }).then((release) => { + secondAcquired = true; + return release; + }); + yield* Effect.promise(() => retryStarted); + assert.isFalse(secondAcquired); + releaseFirst(); + releaseRetryGate(); + const releaseSecond = yield* Effect.promise(() => second); + assert.isTrue(secondAcquired); + releaseSecond(); + assert.isFalse(yield* fs.exists(lock)); + }), + ); }); diff --git a/apps/server/src/cloud/serviceSelectionLock.ts b/apps/server/src/cloud/serviceSelectionLock.ts index 4cbd123c22f7e..7277ca4affea9 100644 --- a/apps/server/src/cloud/serviceSelectionLock.ts +++ b/apps/server/src/cloud/serviceSelectionLock.ts @@ -10,18 +10,29 @@ import * as NodePath from "node:path"; const bootEpochSeconds = () => Math.round(Date.now() / 1000 - NodeOS.uptime()); /** Serialize durable selection and unit writes, never manager stop/start commands. */ -export async function acquireServiceSelectionLock(selectionPath: string): Promise<() => void> { +export async function acquireServiceSelectionLock( + selectionPath: string, + options?: { readonly waitForRetry?: () => Promise }, +): Promise<() => void> { + const waitForRetry = + options?.waitForRetry ?? (() => new Promise((resolve) => setTimeout(resolve, 50))); const directory = NodePath.dirname(selectionPath); NodeFS.mkdirSync(directory, { recursive: true, mode: 0o700 }); const lock = selectionPath + ".selection-lock"; const owner = `${process.pid}.${bootEpochSeconds()}.${NodeCrypto.randomUUID()}`; const candidate = `${lock}.${owner}`; const deadline = Date.now() + 30_000; + // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. + const windows = NodeOS.platform() === "win32"; const removeEmptyLock = () => { try { NodeFS.rmdirSync(lock); } catch (error) { - if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) + const code = (error as NodeJS.ErrnoException).code ?? ""; + if ( + !["ENOENT", "ENOTEMPTY", "EEXIST"].includes(code) && + !(windows && ["EBUSY", "EPERM", "EACCES"].includes(code)) + ) throw error; } }; @@ -37,15 +48,20 @@ export async function acquireServiceSelectionLock(selectionPath: string): Promis removeEmptyLock(); }; } catch (error) { - if (!["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) - throw error; + const code = (error as NodeJS.ErrnoException).code ?? ""; + // Windows MoveFileExW fails with EPERM/EACCES when the target directory already exists. + const contended = + code === "EEXIST" || + code === "ENOTEMPTY" || + (windows && (code === "EPERM" || code === "EACCES")); + if (!contended) throw error; } - let owners: string[]; + let owners: string[] = []; try { owners = NodeFS.readdirSync(lock); } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; - throw error; + // A Windows rename can fail with EPERM while no lock exists; keep the deadline and delay. + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } if (owners.length === 1) { const previous = owners[0]!; @@ -80,7 +96,7 @@ export async function acquireServiceSelectionLock(selectionPath: string): Promis throw new Error( `Service selection is locked at ${lock}. Retry when the other operation finishes.`, ); - await new Promise((resolve) => setTimeout(resolve, 50)); + await waitForRetry(); } } finally { NodeFS.rmSync(candidate, { recursive: true, force: true }); diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 7fd2816e3c17c..0c9912aadd034 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -40,6 +40,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts"; import * as DeviceHost from "./DeviceHost.ts"; import { makeDeviceHubOperations } from "./DeviceHubOperations.ts"; +import { deviceHubNodeArgs } from "./deviceHubNodeArgs.ts"; import { agentDeviceStateDir, type DeviceToolPaths, @@ -455,7 +456,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ChildProcess.make( nodePath, [ - hubTool.entryPath, + ...deviceHubNodeArgs(hubTool.entryPath, hostPlatform), "--port", String(port), "--host", diff --git a/apps/server/src/device/deviceHubNodeArgs.test.ts b/apps/server/src/device/deviceHubNodeArgs.test.ts new file mode 100644 index 0000000000000..efe434862d46d --- /dev/null +++ b/apps/server/src/device/deviceHubNodeArgs.test.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics nodeBuiltinImport:off - exercises the standalone Node preload in a subprocess. +import { describe, expect, it } from "@effect/vitest"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeUtil from "node:util"; + +import { deviceHubNodeArgs } from "./deviceHubNodeArgs.ts"; + +const exec = NodeUtil.promisify(NodeChildProcess.execFile); + +describe("deviceHubNodeArgs", () => { + it("hides emulator consoles without changing other hub children or arguments", async () => { + const capture = ` +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +childProcess.spawn = (...args) => console.log(JSON.stringify(args)); +syncBuiltinESMExports(); +`; + const fixture = ` +import { spawn } from "node:child_process"; +import { join } from "node:path"; +spawn(join("sdk with spaces", "emulator", "Emulator.exe"), ["-avd", "Pixel"], { + detached: true, stdio: "ignore", env: { TEST: "preserved" } +}); +spawn("ffmpeg", ["-encoders"], { detached: true, stdio: "pipe" }); +spawn("emulator.exe", { detached: true, cwd: "sdk" }); +console.log(JSON.stringify(process.argv.slice(1))); +`; + const args = deviceHubNodeArgs("unused-entry.mjs", "win32"); + const { stdout } = await exec( + process.execPath, + [ + "--import", + `data:text/javascript,${encodeURIComponent(capture)}`, + ...args.slice(0, -1), + "--input-type=module", + "-e", + fixture, + "--", + "--port", + "12345", + ], + { encoding: "utf8", windowsHide: true }, + ); + const [emulator, ffmpeg, withoutArgs, argv] = stdout + .trim() + .split(/\r?\n/) + .map((line) => JSON.parse(line)); + expect(emulator.slice(1)).toEqual([ + ["-avd", "Pixel"], + { detached: false, stdio: "ignore", env: { TEST: "preserved" }, windowsHide: true }, + ]); + expect(ffmpeg).toEqual(["ffmpeg", ["-encoders"], { detached: true, stdio: "pipe" }]); + expect(withoutArgs).toEqual([ + "emulator.exe", + { detached: false, cwd: "sdk", windowsHide: true }, + ]); + expect(argv).toEqual(["--port", "12345"]); + }); +}); diff --git a/apps/server/src/device/deviceHubNodeArgs.ts b/apps/server/src/device/deviceHubNodeArgs.ts new file mode 100644 index 0000000000000..5cd3c3629c63b --- /dev/null +++ b/apps/server/src/device/deviceHubNodeArgs.ts @@ -0,0 +1,25 @@ +// expo-device-hub detaches emulators without hiding their Windows console. Closing that +// console terminates the emulator; keep the workaround scoped to the hub process. +const WINDOWS_EMULATOR_PRELOAD = ` +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +import { basename } from "node:path"; +const spawn = childProcess.spawn; +childProcess.spawn = function(command, ...args) { + if (typeof command === "string" && basename(command).toLowerCase() === "emulator.exe") { + const index = Array.isArray(args[0]) ? 1 : 0; + args[index] = { ...args[index], detached: false, windowsHide: true }; + } + return Reflect.apply(spawn, this, [command, ...args]); +}; +syncBuiltinESMExports(); +`; + +export const deviceHubNodeArgs = (entryPath: string, platform: NodeJS.Platform): string[] => + platform === "win32" + ? [ + "--import", + `data:text/javascript,${encodeURIComponent(WINDOWS_EMULATOR_PRELOAD)}`, + entryPath, + ] + : [entryPath]; diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts index 96c71fcd773f9..19769a840a8c8 100644 --- a/apps/server/src/mcp/McpInvocationContext.test.ts +++ b/apps/server/src/mcp/McpInvocationContext.test.ts @@ -94,4 +94,14 @@ it("acts at an administrator's ceiling for a client approved above it", () => { ).toEqual({ runtimeMode: "approval-required", interactionMode: "plan" }); expect(modes(scope("auto-accept-edits"), "auto").runtimeMode).toBe("auto-accept-edits"); expect(modes(scope("full-access")).runtimeMode).toBe("full-access"); + // The scope says what the ceiling is, for a thread caller too. + expect( + McpInvocationContext.withRuntimeModeCeiling(scope("full-access"), "auto").runtimeModeCeiling, + ).toBe("auto"); + expect( + McpInvocationContext.withRuntimeModeCeiling( + { ...scope("full-access"), client: undefined }, + "auto", + ).runtimeModeCeiling, + ).toBe("auto"); }); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 0ba10af2d8c45..9bd2f08f37445 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -126,10 +126,12 @@ export const withRuntimeModeCeiling = ( scope: McpInvocationScope, ceiling: RuntimeMode | undefined, ): McpInvocationScope => { - if (ceiling === undefined || scope.client === undefined) return scope; + if (ceiling === undefined) return scope; + if (scope.client === undefined) return { ...scope, runtimeModeCeiling: ceiling }; const asked = scope.client.narrowedTo; return { ...scope, + runtimeModeCeiling: ceiling, client: { ...scope.client, narrowedTo: { @@ -155,6 +157,8 @@ export interface McpInvocationScope { readonly linkedEnvironments?: boolean; /** The Agent feedback mode here; `/mcp` reads it per request. Unset is off. */ readonly agentFeedback?: AgentFeedbackMode; + /** The broadest runtime mode an administrator lets a thread run in here. Unset is full access. */ + readonly runtimeModeCeiling?: RuntimeMode | undefined; /** True while Labs → Workflows is on here; `/mcp` reads it per request. Unset is off. */ readonly workflows?: boolean; /** diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts index 6cfd86bd3d836..cd1d28d37d4cf 100644 --- a/apps/server/src/mcp/McpToolAccess.test.ts +++ b/apps/server/src/mcp/McpToolAccess.test.ts @@ -137,6 +137,7 @@ const ProbeToolkit = Toolkit.make( }), }), Tool.make("writes_environment", probe), + Tool.make("writes_owner_work", probe), ); const ran = Effect.succeed({ ran: "ran" }); const probeHandlers: McpToolAccess.Handlers = { @@ -155,6 +156,7 @@ const probeHandlers: McpToolAccess.Handlers = { "stamped", ), writes_environment: McpToolAccess.writesEnvironment(() => ran), + writes_owner_work: McpToolAccess.writesOwnerWork("drive owner work", () => ran), }; const layerProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, probeHandlers); @@ -194,6 +196,7 @@ export const refusedAtCompileTime = () => { writes_threads: unchecked, starts_threads: unchecked, writes_environment: unchecked, + writes_owner_work: unchecked, }), ); }; @@ -249,6 +252,15 @@ const fullAccessLinkedClient: McpInvocationContext.McpInvocationScope = { ...fullAccessClient, client: { ...fullAccessClient.client!, linked: true }, }; +// An administrator's ceiling narrows every client to it. +const atCeilingClient: McpInvocationContext.McpInvocationScope = { + ...fullAccessClient, + runtimeModeCeiling: "auto", + client: { + ...fullAccessClient.client!, + narrowedTo: { runtimeMode: "auto", interactionMode: "default" }, + }, +}; const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) }; it.effect.each([ @@ -321,6 +333,18 @@ it.effect.each([ ["writes_environment", plan, {}, "capability_denied"], ["writes_environment", fullAccessClient, {}, "ran"], ["writes_environment", supervisedClient, {}, "capability_denied"], + + ["writes_owner_work", fullAccess, {}, "ran"], + ["writes_owner_work", supervised, {}, "capability_denied"], + ["writes_owner_work", plan, {}, "capability_denied"], + ["writes_owner_work", ended, {}, "parent_not_active"], + ["writes_owner_work", fullAccessClient, {}, "ran"], + ["writes_owner_work", supervisedClient, {}, "capability_denied"], + ["writes_owner_work", readOnlyClient, {}, "capability_denied"], + ["writes_owner_work", linkedClient, {}, "capability_denied"], + ["writes_owner_work", fullAccessLinkedClient, {}, "ran"], + ["writes_owner_work", atCeilingClient, {}, "ran"], + ["writes_environment", atCeilingClient, {}, "capability_denied"], ] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) => call(tool, scope, args).pipe( Effect.map((outcome) => expect(outcome).toBe(expected)), diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index bbf090809c682..b179882661c3b 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -32,6 +32,7 @@ import { import * as McpInvocationContext from "./McpInvocationContext.ts"; import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts"; import { + assertBroadestAccess, assertFullAccess, assertLiveCaller, assertTargetWithinLimits, @@ -190,6 +191,24 @@ export const writes = ( () => orchestratingCaller, ); +/** + * Drives work that runs for this environment's owner in modes its definition picks, such as a + * workflow run. `what` names it in a refusal, after "can" or "cannot". + */ +export const writesOwnerWork = ( + what: string, + handle: (params: P) => Effect.Effect, +) => { + const check = orchestratingCaller.pipe( + Effect.tap((caller) => assertNotLinked(caller, what)), + Effect.tap((caller) => assertBroadestAccess(caller, what)), + ); + return declare( + (params: P) => check.pipe(Effect.flatMap(() => handle(params))), + () => check, + ); +}; + /** Requires handler capability checks, not thread control; linked work is refused the same way. */ export const writesWithCapability = (handle: (params: P) => Effect.Effect) => declare( diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 7c4a0f00eccfe..869d557b55e3c 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -16,6 +16,7 @@ import { TurnItemId, } from "@t3tools/contracts"; 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"; @@ -1331,7 +1332,11 @@ it("requestSecret saves a pasted value to a file without opening a card", async it("requestSecret returns the unsaved note for a declined, cancelled or timed-out card", async () => { const outcomes = ["declined", "cancelled", "pending"] as const; const results = await Effect.forEach(outcomes, (outcome) => { - const dispatched: Array<{ readonly type: string; readonly turnItemId?: string }> = []; + const dispatched: Array<{ + readonly type: string; + readonly turnItemId?: string; + readonly secretStatus?: string; + }> = []; const projection = () => { const card = dispatched.find((command) => command.type === "secret_request.record"); return { @@ -1390,14 +1395,24 @@ it("requestSecret returns the unsaved note for a declined, cancelled or timed-ou }) .pipe(Effect.forkChild({ startImmediately: true })); yield* TestClock.adjust("2 seconds"); - return yield* Fiber.join(request); + const result = yield* Fiber.join(request); + return { result, recorded: dispatched.map((command) => command.secretStatus) }; }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))); }).pipe(Effect.runPromise); expect(results).toEqual([ - { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined }, - { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }, - { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, + { + result: { status: "declined", note: SECRET_REQUEST_UNSAVED_NOTE.declined }, + recorded: ["pending"], + }, + { + result: { status: "cancelled", note: SECRET_REQUEST_UNSAVED_NOTE.cancelled }, + recorded: ["pending"], + }, + { + result: { status: "timed_out", note: SECRET_REQUEST_UNSAVED_NOTE.timed_out }, + recorded: ["pending", "cancelled"], + }, ]); }); @@ -1489,6 +1504,84 @@ it("requestSecret cancels its card when a steering restart supersedes the reques }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("requestSecret closes its card when the call is aborted while the card is being recorded", async () => { + const statuses: Array = []; + const projection = () => + ({ + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + { ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }, + ], + visibleTurnItems: [], + turnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + contextTransfers: [], + subagents: [], + updatedAt: now, + }) as unknown as OrchestrationV2ThreadProjection; + + await Effect.gen(function* () { + const recorded = yield* Deferred.make(); + const release = yield* Deferred.make(); + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.sync(projection), + getThreadShell: () => + Effect.sync(() => projection().thread as unknown as OrchestrationV2ThreadShell), + // The pending card is stored before the dispatch returns to the caller. + dispatch: (command) => + Effect.gen(function* () { + if (command.type !== "secret_request.record") return {} as never; + statuses.push(command.secretStatus); + if (command.secretStatus === "pending") { + yield* Deferred.succeed(recorded, undefined); + yield* Deferred.await(release); + } + return {} as never; + }), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({}), + NodeCrypto.layer, + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const request = yield* service + .requestSecret(makeScope(), { + label: "Staging password", + reason: "Signs in the QA account.", + }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(recorded); + const abort = yield* Fiber.interrupt(request).pipe( + Effect.forkChild({ startImmediately: true }), + ); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(abort); + }).pipe(Effect.provide(Layer.merge(layer, TestClock.layer()))); + }).pipe(Effect.runPromise); + + expect(statuses).toEqual(["pending", "cancelled"]); +}); + it("requestSecret delivers a fields card as one file per field", async () => { const dispatched: Array<{ readonly type: string; diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index b9568a43e1c77..bc0dc9ed074fc 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -483,7 +483,7 @@ function providerConstraints( return constraints; } -/** t3_thread_launch keeps a selection as given, so it can hold options its model does not have. */ +/** Older persisted selections or providers without descriptors can still hold options a model does not declare. */ function knownOptions( options: ReadonlyArray | undefined, descriptors: ReadonlyArray | undefined, @@ -527,6 +527,26 @@ function invalidOptionSelections( return problems; } +/** Validate and normalize requested options against the model's advertised option descriptors. */ +export const validateModelOptions = ( + provider: ServerProvider, + model: string, + options: ReadonlyArray | undefined, +): Effect.Effect | undefined, OrchestratorMcpFailure> => { + const descriptors = advertisedModel(provider, model)?.capabilities?.optionDescriptors; + const normalized = withLegacyUltracodeEffort(descriptors, options); + if (normalized === undefined) return Effect.undefined; + const invalid = invalidOptionSelections(normalized, descriptors); + return invalid.length > 0 + ? Effect.fail( + failure( + "invalid_request", + `Model ${model} on provider ${provider.instanceId} rejected options: ${invalid.join(" ")}`, + ), + ) + : Effect.succeed(normalized); +}; + function taskStatusForRun( run: Pick | undefined, ): OrchestratorMcpDelegateTaskResult["status"] { @@ -1784,16 +1804,7 @@ const make = Effect.gen(function* () { if (requestedModel !== undefined) yield* requireAdvertisedModel(provider, model); const advertised = advertisedModel(provider, model); const descriptors = advertised?.capabilities?.optionDescriptors; - const requestedOptions = withLegacyUltracodeEffort(descriptors, input.target?.options); - if (requestedOptions !== undefined) { - const invalid = invalidOptionSelections(requestedOptions, descriptors); - if (invalid.length > 0) { - return yield* failure( - "invalid_request", - `Model ${model} on provider ${instanceId} rejected options: ${invalid.join(" ")}`, - ); - } - } + const requestedOptions = yield* validateModelOptions(provider, model, input.target?.options); const inheritsOptions = instanceId === inheritedSelection.instanceId && @@ -2700,7 +2711,6 @@ const make = Effect.gen(function* () { ), ), ); - yield* record("pending"); // Only this call can hand the agent its ref, so the card must not // outlive it: a timeout, a failed wait or an aborted call closes it as // cancelled. @@ -2710,54 +2720,57 @@ const make = Effect.gen(function* () { ), ); - const answered = yield* Effect.gen(function* () { - while (true) { - const projection = yield* threadManagement - .getThreadRecords(threadId, ["runs", "turnItems"], { - turnItemTypes: ["secret_request"], - messageRoles: [], - }) - .pipe( - Effect.mapError((error) => - failure( - "orchestration_error", - `Unable to read the secret request: ${errorMessage(error)}`, + const answered = yield* Effect.acquireUseRelease( + record("pending"), + () => + Effect.gen(function* () { + while (true) { + const projection = yield* threadManagement + .getThreadRecords(threadId, ["runs", "turnItems"], { + turnItemTypes: ["secret_request"], + messageRoles: [], + }) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to read the secret request: ${errorMessage(error)}`, + ), + ), + ); + const item = projection.turnItems.find((candidate) => candidate.id === turnItemId); + if (item?.type === "secret_request" && item.secretStatus !== "pending") { + return item.secretStatus; + } + const current = projection.runs.find((candidate) => candidate.id === runId); + if ( + current === undefined || + ThreadManagementService.isTerminalRunStatus(current.status) + ) { + yield* record("cancelled"); + return "cancelled" as const; + } + // A steering restart replaced the run's root, so this request belonged to + // the superseded attempt: its card can never be answered into that attempt, + // and the call must stop blocking the agent's turn. + if (current.rootNodeId !== nodeId) { + yield* record("cancelled"); + return "cancelled" as const; + } + yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); + } + }).pipe( + Effect.timeoutOption( + Duration.millis( + Math.min( + input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS, + MAX_SECRET_REQUEST_TIMEOUT_MS, ), ), - ); - const item = projection.turnItems.find((candidate) => candidate.id === turnItemId); - if (item?.type === "secret_request" && item.secretStatus !== "pending") { - return item.secretStatus; - } - const current = projection.runs.find((candidate) => candidate.id === runId); - if ( - current === undefined || - ThreadManagementService.isTerminalRunStatus(current.status) - ) { - yield* record("cancelled"); - return "cancelled" as const; - } - // A steering restart replaced the run's root, so this request belonged to - // the superseded attempt: its card can never be answered into that attempt, - // and the call must stop blocking the agent's turn. - if (current.rootNodeId !== nodeId) { - yield* record("cancelled"); - return "cancelled" as const; - } - yield* Effect.sleep(Duration.millis(SECRET_REQUEST_POLL_INTERVAL_MS)); - } - }).pipe( - Effect.timeoutOption( - Duration.millis( - Math.min( - input.timeoutMs ?? DEFAULT_SECRET_REQUEST_TIMEOUT_MS, - MAX_SECRET_REQUEST_TIMEOUT_MS, ), ), - ), - Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : closeCard)), + (_, exit) => (Exit.isSuccess(exit) && Option.isSome(exit.value) ? Effect.void : closeCard), ); - if (Option.isNone(answered)) yield* closeCard; const status = Option.isSome(answered) ? answered.value : yield* threadManagement diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index d21495f0ff7c7..abcb7fcd29e05 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -5,6 +5,7 @@ import type { import { CommandId, type EnvironmentId, + isRuntimeModeAbove, OrchestratorMcpFailure, type ProjectId, type ProviderInstanceId, @@ -220,6 +221,23 @@ export const assertFullAccess = (context: Caller, message: string) => ? Effect.void : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message })); +/** + * For work whose definition picks its own modes: the caller must hold the broadest modes a + * thread may run in here, full access or an administrator's ceiling below it. + */ +export const assertBroadestAccess = (context: Caller, what: string) => { + const broadest = context.scope.runtimeModeCeiling ?? "full-access"; + return !isRuntimeModeAbove(broadest, context.limits.runtimeMode) && + context.limits.interactionMode === "default" + ? Effect.void + : Effect.fail( + new OrchestratorMcpFailure({ + code: "capability_denied", + message: `Only a caller with ${broadest}/default access can ${what}, because that work picks its own modes. This caller is limited to ${context.limits.runtimeMode}/${context.limits.interactionMode}.`, + }), + ); +}; + export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) => projectId !== undefined ? Effect.succeed(projectId) diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index a40d15252fbb8..17fa4dd496fad 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -471,6 +471,93 @@ it.effect("a launch with a model its provider does not advertise creates no thre }), ); +it.effect( + "a launch rejects options its model does not declare and normalizes legacy ultracode effort", + () => + Effect.gen(function* () { + const launched: Array = []; + const providers: ServerProvider[] = [ + { + instanceId: ProviderInstanceId.make("claudeAgent"), + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + status: "ready", + version: null, + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00Z", + models: [ + { + slug: "claude-opus-5-5", + name: "Claude Opus 5.5", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "effort", + role: "reasoning", + label: "Effort", + type: "select", + options: [ + { id: "high", label: "High" }, + { id: "xhigh", label: "Extra High" }, + ], + }, + { id: "ultracode", label: "Ultracode", type: "boolean" }, + ], + }, + }, + ], + slashCommands: [], + skills: [], + }, + ]; + const { projectId, dependencies } = clientLaunchHarness({ + runtimeModeCeiling: "auto", + launched, + providers, + }); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe( + Layer.provide(dependencies), + ), + ), + ); + const launchWith = (options: NonNullable) => + toolkit + .handle("t3_thread_launch", { + title: "Options check", + projectId, + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-5-5", + options, + }, + }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((result) => result.at(-1)?.result), + Effect.provide(dependencies), + ); + + expect(yield* launchWith([{ id: "thought_level", value: "high" }])).toMatchObject({ + code: "invalid_request", + message: expect.stringContaining("Unknown option thought_level"), + }); + expect(launched).toHaveLength(0); + + yield* launchWith([{ id: "effort", value: "ultracode" }]); + expect(launched.map((launch) => launch.modelSelection.options)).toEqual([ + [ + { id: "effort", value: "xhigh" }, + { id: "ultracode", value: true }, + ], + ]); + }), +); + it.effect("a launch retried with the same clientRequestId replays the first one", () => Effect.gen(function* () { const launched: Array = []; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index f92df228a422f..deec936b62b54 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -1,6 +1,7 @@ import { CommandId, MessageId, + type ModelSelection, ThreadId, OrchestratorMcpFailure, type OrchestrationV2ThreadLaunchWorkspaceStrategy, @@ -322,26 +323,35 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { ), } : input.workspaceStrategy; + let validatedModelSelection = input.modelSelection; if (!replaying && input.modelSelection !== undefined) { - const { instanceId, model } = input.modelSelection; + const requestedSelection = input.modelSelection; + const { instanceId, model } = requestedSelection; const registry = yield* ProviderRegistry.ProviderRegistry; // The thread runs in this folder, whose own provider config can add models. const cwd = workspaceStrategy?.type === "existing_worktree" ? workspaceStrategy.worktreePath : project?.workspaceRoot; - const requireModel = ( + const validateSelection = Effect.fn("mcp.validateLaunchModelSelection")(function* ( providers: ReadonlyArray, - ): Effect.Effect => { + ): Effect.fn.Return { const provider = OrchestrationMcp.withWorkspaceModels(providers, cwd).find( (candidate) => candidate.instanceId === instanceId, ); - return provider === undefined - ? Effect.void - : OrchestrationMcp.requireAdvertisedModel(provider, model); - }; - const checked = requireModel(yield* registry.getProviders); - yield* cwd === undefined + if (provider === undefined) return requestedSelection; + yield* OrchestrationMcp.requireAdvertisedModel(provider, model); + const options = yield* OrchestrationMcp.validateModelOptions( + provider, + model, + requestedSelection.options, + ); + return options === undefined || options === requestedSelection.options + ? requestedSelection + : { ...requestedSelection, options }; + }); + const checked = validateSelection(yield* registry.getProviders); + validatedModelSelection = yield* cwd === undefined ? checked : checked.pipe( Effect.catchIf( @@ -352,7 +362,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { Effect.flatMap((scanCwd) => registry.refreshWorkspaceSnapshot({ instanceId, cwd, scanCwd }), ), - Effect.flatMap(requireModel), + Effect.flatMap(validateSelection), ), ), ); @@ -408,7 +418,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { // within the ceiling it was approved with. const projectDefaults = caller === undefined ? projectSettings : undefined; const modelSelection = - input.modelSelection ?? + validatedModelSelection ?? launchedModel ?? caller?.modelSelection ?? (projectDefaults diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 95f816f151b9d..c031c5f947a10 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -1369,6 +1369,33 @@ describe("source control tools", () => { }), ); + it.effect("pins a review to the head the caller read, and approves only with one", () => + Effect.gen(function* () { + const reviews: Array = []; + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { + submitReview: (input) => Effect.sync(() => void reviews.push(input)), + }, + }); + yield* harness.call("pull_request_review", { + verdict: "approve", + expectedHeadSha: "abc1234def5678", + }); + expect(reviews).toMatchObject([{ verdict: "approve", expectedHeadSha: "abc1234def5678" }]); + + const error = yield* harness + .call("pull_request_review", { verdict: "approve" }) + .pipe(Effect.flip); + expect(error.message).toContain("expectedHeadSha"); + expect(reviews).toHaveLength(1); + + yield* harness.call("pull_request_review", { verdict: "comment", body: "A question." }); + expect(reviews).toHaveLength(2); + expect(reviews[1]).not.toHaveProperty("expectedHeadSha"); + }), + ); + it.effect("updates labels, requests reviewers by login, and closes the PR", () => Effect.gen(function* () { const calls: Array = []; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 646f94de8e541..db5fd3b5d5cce 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -1182,10 +1182,24 @@ const make = Effect.gen(function* () { ), pull_request_review: McpToolAccess.writesWithCapability((input) => Effect.gen(function* () { + if (input.verdict === "approve" && input.expectedHeadSha === undefined) { + return yield* new PullRequestForgeError({ + detail: + "Approving needs expectedHeadSha: the headSha pull_request_read reported for the commits you reviewed.", + }); + } const { target, ref } = yield* locate(input); const comments = yield* reviewComments(ref, input.comments ?? []); yield* pullRequests - .submitReview({ ...ref, verdict: input.verdict, body: input.body ?? "", comments }) + .submitReview({ + ...ref, + verdict: input.verdict, + body: input.body ?? "", + comments, + ...(input.expectedHeadSha === undefined + ? {} + : { expectedHeadSha: input.expectedHeadSha }), + }) .pipe(Effect.mapError(forgeFailure)); return identityOf(target); }), diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 446b300b9a40b..45edd39081881 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -767,10 +767,11 @@ export type ReviewLineComment = typeof ReviewLineComment.Type; const ReviewPullRequestTool = Tool.make("pull_request_review", { description: - "Submit a review: approve, request changes, or comment, with optional line comments.", + "Submit a review: approve, request changes, or comment, with optional line comments. Approving needs expectedHeadSha (headSha in pull_request_read). Refuses if the head moved from it.", parameters: Schema.Struct({ ...ThreadPullRequestInput.fields, verdict: PullRequestReviewVerdict, + expectedHeadSha: Schema.optional(TrimmedNonEmptyString), body: Schema.optional(Schema.String), comments: Schema.optional(Schema.Array(ReviewLineComment).check(Schema.isMaxLength(50))), }), diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index 77b7036681ad6..ea758e6f62c53 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -12,7 +12,13 @@ import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import * as WorkflowHandlers from "./handlers.ts"; import { WorkflowToolkit } from "./tools.ts"; -const handlersWith = (workflows: Partial) => +const fullAccess = { sessionId: "session-1", label: "t3 CLI", access: "full-access" } as const; +const supervised = { sessionId: "session-2", label: "Bot", access: "approval-required" } as const; + +const handlersWith = ( + workflows: Partial, + scope: Partial = {}, +) => McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( Layer.provideMerge( Layer.mergeAll( @@ -22,9 +28,10 @@ const handlersWith = (workflows: Partial) => environmentId: EnvironmentId.make("environment:workflow"), requestNamespace: "client:workflow", thread: undefined, - client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + client: fullAccess, capabilities: new Set(["orchestration" as const]), issuedAt: 0, + ...scope, }), Layer.mock(Workflows.Workflows)(workflows), ), @@ -100,3 +107,96 @@ it.effect("signal refuses a run destination mixed with a channel destination", ( expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); }), ); + +const emptyRun = { run: undefined, steps: [], references: [] } as never; +const call = (input: Record) => + Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* toolkit.handle("t3_workflow", input as never).pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ); + }); + +const changes = [ + { action: "start", workflow: "release", idempotencyKey: "trial" }, + { action: "signal", runId: "run-1", wait: "review", value: { choice: "yes" } }, + { action: "resume", runId: "run-1" }, + { action: "cancel", runId: "run-1" }, + { action: "store_set", key: "switch", value: true }, + { action: "store_delete", key: "switch" }, +]; + +it.effect("a caller below the broadest mode reads runs but does not start or change them", () => + Effect.gen(function* () { + const reached: Array = []; + const reach = (name: string) => () => Effect.sync(() => void reached.push(name)); + const results = yield* Effect.forEach( + [...changes, { action: "list" }, { action: "questions" }], + call, + ).pipe( + Effect.provide( + handlersWith( + { + start: () => Effect.sync(() => (reached.push("start"), { runId: "run-1" })), + signal: () => Effect.sync(() => (reached.push("signal"), "delivered" as const)), + resume: reach("resume"), + cancel: reach("cancel"), + storeSet: reach("storeSet"), + storeDelete: reach("storeDelete"), + stored: () => Effect.succeed([]), + get: () => Effect.succeed(emptyRun), + list: () => Effect.succeed([]), + questions: Effect.succeed([]), + }, + { client: supervised }, + ), + ), + ); + for (const result of results.slice(0, changes.length)) { + expect(result).toMatchObject({ code: "capability_denied" }); + } + expect(reached).toEqual([]); + expect(results.slice(changes.length)).toEqual([{ runs: [] }, { questions: [] }]); + }), +); + +it.effect("hook paths go only to a caller at the broadest mode", () => + Effect.gen(function* () { + const hooks = [{ workflow: "release", name: "push", path: "/api/hooks/wf-release.push/token" }]; + const read = (client: McpInvocationContext.McpClientCaller) => + call({ action: "hooks" }).pipe( + Effect.provide(handlersWith({ hooks: Effect.succeed(hooks as never) }, { client })), + ); + expect(yield* read(fullAccess)).toEqual({ hooks }); + const refused = yield* read(supervised); + expect(refused).toMatchObject({ code: "capability_denied" }); + expect(JSON.stringify(refused)).not.toContain("token"); + }), +); + +it.effect("under an administrator's ceiling, a caller at the ceiling starts runs", () => + Effect.gen(function* () { + const start = { action: "start", workflow: "release", idempotencyKey: "trial" }; + const started: Array = []; + const workflows = { + start: (name: string) => Effect.sync(() => (started.push(name), { runId: "run-1" })), + get: () => Effect.succeed(emptyRun), + }; + const narrowedTo = (runtimeMode: "auto" | "approval-required") => ({ + runtimeModeCeiling: "auto" as const, + client: { ...fullAccess, narrowedTo: { runtimeMode, interactionMode: "default" as const } }, + }); + expect( + yield* call(start).pipe(Effect.provide(handlersWith(workflows, narrowedTo("auto")))), + ).toEqual({ steps: [], references: [] }); + expect(started).toEqual(["release"]); + expect( + yield* call(start).pipe( + Effect.provide(handlersWith(workflows, narrowedTo("approval-required"))), + ), + ).toMatchObject({ code: "capability_denied" }); + expect(started).toEqual(["release"]); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index 7ebc6ac0cf7a4..0bc0c97d8e9fa 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -41,7 +41,7 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { return yield* workflows.get(runId).pipe(Effect.mapError(refused)); }), ), - McpToolAccess.writes((input) => + McpToolAccess.writesOwnerWork("start or change workflow runs, or read hook paths", (input) => Effect.gen(function* () { const workflows = yield* Workflows.Workflows; // A hook's path holds its secret, and posting to it starts a run. diff --git a/apps/server/src/mcpApps/McpAppModelContext.test.ts b/apps/server/src/mcpApps/McpAppModelContext.test.ts index bcd01e03dfa82..f8097823febe1 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.test.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.test.ts @@ -62,4 +62,53 @@ layer("McpAppModelContext", (it) => { assert.deepEqual(yield* texts(threadId), []); }), ); + + it.effect("drops pre-/clear MCP app notes, but not for a restarted scheduled fresh run", () => + Effect.gen(function* () { + yield* runMigrations(); + const sql = yield* SqlClient.SqlClient; + const store = yield* McpAppModelContext.McpAppModelContext; + const clearedThread = ThreadId.make("thread-cleared-context"); + + yield* sql` + INSERT INTO orchestration_v2_projection_runs + (run_id, thread_id, ordinal, provider, status, requested_at, payload_json) + VALUES + ('run-before-clear', ${clearedThread}, 1, 'codex', 'completed', '2026-01-01', '{"startedAt":"2026-01-01"}'), + ('run-clear', ${clearedThread}, 2, 'codex', 'completed', '2026-01-02', '{"freshContext":true,"startedAt":"2026-01-02","userMessageId":"msg-clear"}'), + ('run-after-clear', ${clearedThread}, 3, 'codex', 'completed', '2026-01-03', '{"startedAt":"2026-01-03"}'), + ('run-scheduled-fresh', ${clearedThread}, 4, 'codex', 'completed', '2026-01-04', '{"freshContext":true,"startedAt":"2026-01-04","userMessageId":"msg-restart"}') + `; + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items + (turn_item_id, thread_id, run_id, ordinal, type, status, updated_at, payload_json) + VALUES + ('item-before-clear', ${clearedThread}, 'run-before-clear', 1, 'dynamic_tool', 'completed', '2026-01-01', '{}'), + ('item-after-clear', ${clearedThread}, 'run-after-clear', 2, 'dynamic_tool', 'completed', '2026-01-03', '{}'), + ('item-scheduled-prompt', ${clearedThread}, 'run-scheduled-fresh', 3, 'user_message', 'completed', '2026-01-04', '{"messageId":"msg-scheduled","scheduledTaskId":"sched-1"}'), + ('item-restart-prompt', ${clearedThread}, 'run-scheduled-fresh', 4, 'user_message', 'completed', '2026-01-04', '{"messageId":"msg-restart"}') + `; + + yield* store.set({ + threadId: clearedThread, + itemId: TurnItemId.make("item-before-clear"), + server: "todos", + tool: "list_todos", + text: "stale pre-clear note", + }); + yield* store.set({ + threadId: clearedThread, + itemId: TurnItemId.make("item-after-clear"), + server: "todos", + tool: "list_todos", + text: "fresh post-clear note", + }); + + const entries = yield* store.forThread(clearedThread); + assert.deepEqual( + entries.map((entry) => entry.text), + ["fresh post-clear note"], + ); + }), + ); }); diff --git a/apps/server/src/mcpApps/McpAppModelContext.ts b/apps/server/src/mcpApps/McpAppModelContext.ts index 017e10ae3bf5b..7d65bfc4286c3 100644 --- a/apps/server/src/mcpApps/McpAppModelContext.ts +++ b/apps/server/src/mcpApps/McpAppModelContext.ts @@ -90,10 +90,37 @@ export const layer = Layer.effect( }); const forThread = Effect.fn("McpAppModelContext.forThread")(function* (threadId: ThreadId) { - // Match by id across fork lineage; later source rollbacks leave the fork's copy intact. + // Match by id across fork lineage; later source rollbacks leave the fork's copy intact, + // while a started non-scheduled /clear (freshContext) run on this thread clears older notes. return yield* sql` + WITH boundary AS ( + SELECT COALESCE(MAX(b.ordinal), 0) AS min_ordinal + FROM orchestration_v2_projection_runs AS b + WHERE b.thread_id = ${threadId} + AND json_extract(b.payload_json, '$.freshContext') = 1 + AND b.status <> 'queued' + AND NOT ( + b.status = 'cancelled' + AND json_extract(b.payload_json, '$.startedAt') IS NULL + AND json_extract(b.payload_json, '$.restartContinuationOfRunId') IS NULL + ) + -- Mirrors isScheduledFreshRun: the run's first prompt, else its userMessageId's row. + AND ( + SELECT json_extract(ti.payload_json, '$.scheduledTaskId') + FROM orchestration_v2_projection_turn_items AS ti + WHERE ti.thread_id = b.thread_id + AND ti.type = 'user_message' + AND ( + ti.run_id = b.run_id + OR json_extract(ti.payload_json, '$.messageId') = json_extract(b.payload_json, '$.userMessageId') + ) + ORDER BY ti.run_id = b.run_id DESC, ti.ordinal + LIMIT 1 + ) IS NULL + ) SELECT context.item_id AS "itemId", context.server, context.tool, context.text FROM mcp_app_model_context AS context + CROSS JOIN boundary JOIN orchestration_v2_projection_turn_items AS item ON item.turn_item_id = context.item_id LEFT JOIN orchestration_v2_projection_runs AS run @@ -104,6 +131,10 @@ export const layer = Layer.effect( OR run.status <> 'rolled_back' OR run.thread_id <> context.thread_id ) + AND ( + boundary.min_ordinal = 0 + OR (run.thread_id = context.thread_id AND run.ordinal >= boundary.min_ordinal) + ) ORDER BY context.updated_at, context.item_id `.pipe(NodeSqliteClient.readOnly, Effect.mapError(fail)); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index f4ff952bf888d..90852f89dfa82 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -69,6 +69,7 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { writeFakeCli } from "@t3tools/provider-testing/fakeCli"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { ACP_EMPTY_OPTION_VALUE, @@ -13069,6 +13070,96 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.live("sends an image to an agent without image prompts as a file path", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const host = yield* ProviderHost.ProviderHost; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const sent: Array = []; + const instanceId = ProviderInstanceId.make("acp-test-image-without-image-prompts"); + const threadId = ThreadId.make("thread-acp-image-without-image-prompts"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.sync(() => void sent.push(payload.prompt)).pipe( + Effect.andThen(runtime.prompt(payload, promptOptions)), + ), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-image-without-prompts"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const screenshot = { + type: "image", + id: "screenshot-1", + name: "screenshot.png", + mimeType: "image/png", + sizeBytes: 8, + } as const; + const screenshotPath = host.resolveAttachmentPath(screenshot); + if (screenshotPath === null) return assert.fail("expected a screenshot path"); + yield* fileSystem.writeFile( + screenshotPath, + Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a), + ); + const base = makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + messageText: "What is in this screenshot?", + }); + + yield* runtime.startTurn({ + ...base, + message: { ...base.message, attachments: [screenshot] }, + }); + const terminal = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + + assert.equal(Option.getOrThrow(terminal).status, "completed"); + const blocks = sent[0] ?? []; + assert.deepEqual( + blocks.filter((block) => block.type !== "text"), + [], + ); + assert.include( + blocks.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"), + `[Attached image "screenshot.png" is saved at: ${screenshotPath}]`, + ); + }).pipe(Effect.provide(layerTest)), + ); + it.live( "delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer", () => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index faa96e3720645..f5bb3d4bd9c39 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -13856,6 +13856,57 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); + // A sleep is a timer the agent ends its turn on, so a restart must wake it. + const sleeps = [ + ["timer", "sleep 1740; date", true], + ["computed_timer", "sleep $((29 * 60)); date", true], + ["quoted_timer", 'sleep "60" && date', true], + ["single_quoted_timer", "sleep '60'; date", true], + ["quoted_computed_timer", 'sleep "$((29 * 60))"; date', true], + ["expanded_timer", 'sleep "${DELAY:-60}"; date', true], + ["unit_timer", 'sleep 5m && echo "Time to check the build"', true], + ["quoted_note_timer", 'sleep 60 && echo "Timer finished; check build"', true], + ["endless_sleep", "sleep infinity", false], + ["delayed_server", "sleep 5 && npm run dev", false], + ["substituted_server", 'sleep 60; echo "$(npm run dev)"', false], + ] as const; + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_background_timer", + type: "message", + role: "assistant", + content: sleeps.map(([taskId, command]) => ({ + type: "tool_use", + id: `toolu_${taskId}`, + name: "Bash", + input: { command, run_in_background: true }, + })), + }, + parent_tool_use_id: null, + uuid: "background-timer-launch", + session_id: WAKE_NATIVE_SESSION, + }), + ); + for (const [index, [taskId]] of sleeps.entries()) { + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: taskId, + tool_use_id: `toolu_${taskId}`, + description: "Wait before the next check", + is_backgrounded: true, + task_type: "local_bash", + uuid: `00000000-0000-4000-8000-00000000021${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + } yield* Queue.offer(harness.sdkMessages, turnOneResult); yield* harness.awaitTerminal(1); @@ -13866,6 +13917,17 @@ describe("ClaudeAdapterV2 background wake turns", () => { const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0]; assert.equal(started?.taskId, WAKE_TASK_ID); assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID); + assert.deepEqual( + (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? []).map((task) => [ + task.taskId, + task.awaited === true, + ]), + [ + [WAKE_TASK_ID, false], + ["moved-build", false], + ...sleeps.map(([taskId, , awaited]) => [taskId, awaited]), + ], + ); const command = harness.events.find( (event) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a4cb16c51d948..88a4d995b2b1b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2433,6 +2433,67 @@ function parseClaudeInteger(text: string): number { return Number.parseInt(value, 10); } +const CLAUDE_SLEEP_DURATION = String.raw`(?:\d[\w.]*|\$\(\([\d\s+*/%-]+\)\)|\$\{\w+(?::?[-=]\d[\w.]*)?\}|\$\w+)`; +const CLAUDE_SLEEP_TIMER_START = new RegExp( + String.raw`^[ \t\n]*sleep[ \t]+(?:${CLAUDE_SLEEP_DURATION}|"${CLAUDE_SLEEP_DURATION}"|'\d[\w.]*')[ \t]*(?:$|;|&&|\n)`, +); +// Bash separates words only with spaces and tabs, so `\s` would read `true\rnpm` as `true`. +const CLAUDE_SLEEP_TIMER_REPORT = /^[ \t]*(?:$|(?:date|echo|printf|true|:)(?:[ \t]|$))/; + +// A background command that only sleeps for a finite time, then at most prints the time or a +// note, is a timer the agent set to check back, which Claude wakes it for when it ends. Any other +// step (`sleep 5 && npm run dev`) may never end, so that command is not a timer. +function isClaudeSleepTimer(command: string | undefined): boolean { + const start = command === undefined ? null : CLAUDE_SLEEP_TIMER_START.exec(command); + if (command === undefined || start === null) return false; + const steps = splitClaudeSleepTimerSteps(command.slice(start[0].length)); + return steps !== undefined && steps.every((step) => CLAUDE_SLEEP_TIMER_REPORT.test(step)); +} + +// Splits at unquoted `;`, `&&` and newlines. Gives up on anything a report never needs that could +// run or hide another command: pipes, `||`, a lone `&`, subshells, heredocs, substitutions, `${…}`, +// `$'…'`, comments, and unbalanced quotes or escapes. +function splitClaudeSleepTimerSteps(tail: string): string[] | undefined { + const steps: string[] = []; + let step = ""; + let quote: string | undefined; + for (let index = 0; index < tail.length; index++) { + const char = tail[index] ?? ""; + const next = tail[index + 1] ?? ""; + if (quote === "'") { + if (char === "'") quote = undefined; + step += char; + continue; + } + if (char === "\\") { + if (next === "") return undefined; + step += char + next; + index++; + continue; + } + if (char === "`" || (char === "$" && "({'\"".includes(next) && next !== "")) return undefined; + if (quote === '"') { + if (char === '"') quote = undefined; + step += char; + continue; + } + if (char === "'" || char === '"') { + quote = char; + } else if (char === ";" || char === "\n" || (char === "&" && next === "&")) { + steps.push(step); + step = ""; + if (char === "&") index++; + continue; + } else if (char === "&" ? next !== ">" && tail[index - 1] !== ">" : "|()<#".includes(char)) { + return undefined; + } + step += char; + } + if (quote !== undefined) return undefined; + steps.push(step); + return steps; +} + // Claude Code defers MCP tools behind ToolSearch, so the agent only finds // t3_background_wait when the system prompt says when to reach for it. const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = ` @@ -7205,17 +7266,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, task: OrchestrationV2PendingBackgroundTask, ) { - const startedMonitor = yield* Ref.modify( + const startedWait = yield* Ref.modify( pendingBackgroundTasksByNativeThread, (current) => { const roster = new Map(rosterForNativeThread(current, nativeThreadId)); - const startedMonitor = - task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor"; + const previous = roster.get(task.taskId); + const startedWait = + task.kind === "monitor" + ? previous?.kind !== "monitor" + : task.kind === "command" && + previous?.command === undefined && + isClaudeSleepTimer(task.command); roster.set(task.taskId, task); - return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const; + return [startedWait, new Map(current).set(nativeThreadId, roster)] as const; }, ); - if (startedMonitor) { + if (startedWait) { yield* addTaskIdsToNativeThreadSet( awaitedBackgroundTasksByNativeThread, nativeThreadId, diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index a6a1056d1a95b..16193d12e242e 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -4137,6 +4137,56 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("sends a $skill named in a message that steers the running turn", () => + Effect.gen(function* () { + const prompts: Array = []; + const steerId = "msg_recorded_steer_skill"; + const greet = { + id: "greet", + name: "greet", + path: `${WORK}/.opencode/skills/greet/SKILL.md`, + content: "Say hello.", + }; + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.started", { sessionID: SESSION }), + out("skill.list", { "location[directory]": WORK }), + reply("skill.list", { location: { directory: WORK }, data: [greet] }), + out("session.prompt", { sessionID: SESSION, id: steerId, delivery: "steer" }), + replyData("session.prompt", { + id: steerId, + sessionID: SESSION, + time: { created: 1790656601500 }, + type: "user", + payload: { text: "$greet first" }, + delivery: "steer", + }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: steerId }), + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { onPrompt: (input) => prompts.push(input) }, + ); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + const input = turnInput(thread); + yield* runtime.startTurn(input); + yield* runtime.steerTurn({ + threadId, + runId: input.runId, + providerThread: thread, + providerTurnId: yield* providerTurnId, + message: { + ...input.message, + messageId: MessageId.make("message:opencode2-adapter:steer"), + text: "$greet first", + }, + }); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + assert.deepInclude(prompts[1], { delivery: "steer", skills: [{ id: "greet" }] }); + }), + ); + it.effect.each([ { server: "an external server keeps rejecting requests", diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts index 78958c2e317d5..74a21397ab466 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts @@ -301,3 +301,159 @@ it.effect("inherited history stops at a missing fork ancestor", () => assert.deepEqual(items, []); }), ); + +const clearNow = DateTime.makeUnsafe("2026-01-01T00:00:00.000Z"); +const clearAncestorId = ThreadId.make("thread:ancestor-before-clear"); +const clearSourceId = ThreadId.make("thread:source-with-clear"); +const clearAncestorRunId = RunId.make("run:ancestor-1"); + +function clearRun(id: RunId, threadId: ThreadId, ordinal: number, freshContext?: boolean) { + return { + id, + threadId, + ordinal, + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + providerThreadId: ProviderThreadId.make(`pt:${id}`), + userMessageId: MessageId.make(`msg:${id}`), + rootNodeId: null as never, + activeAttemptId: null, + status: "completed" as const, + queuePosition: null, + requestedAt: clearNow, + startedAt: clearNow, + completedAt: clearNow, + checkpointId: null, + contextHandoffId: null, + ...(freshContext ? { freshContext: true } : {}), + }; +} + +function clearUserItem( + id: string, + threadId: ThreadId, + runId: RunId, + text: string, + ordinal: number, + scheduledTaskId?: string, +) { + return { + ...importedItem({ role: "user", id, text, ordinal }), + threadId, + runId, + ...(scheduledTaskId === undefined ? {} : { scheduledTaskId }), + } as OrchestrationV2TurnItem; +} + +function clearThread( + id: ThreadId, + forkedFrom: OrchestrationV2AppThread["forkedFrom"], +): OrchestrationV2AppThread { + return { + createdBy: "user", + creationSource: "web", + id, + projectId: ProjectId.make("project:clear-fork"), + title: id, + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: clearAncestorId }, + forkedFrom, + createdAt: clearNow, + updatedAt: clearNow, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + snoozedUntil: null, + snoozedAt: null, + deletedAt: null, + }; +} + +/** Portable fork history of a source forked from an ancestor, through its last run. */ +const readClearFork = Effect.fn(function* ( + sourceRuns: ReadonlyArray>, + sourceItems: ReadonlyArray, +) { + const sourceThread = clearThread(clearSourceId, { + type: "run", + threadId: clearAncestorId, + runId: clearAncestorRunId, + }); + const store = { + getThreadRecords: (threadId: ThreadId) => + Effect.succeed( + (threadId === clearAncestorId + ? { + thread: clearThread(clearAncestorId, null), + runs: [clearRun(clearAncestorRunId, clearAncestorId, 1)], + attempts: [], + turnItems: [ + clearUserItem("anc", clearAncestorId, clearAncestorRunId, "ancestor history", 1), + ], + } + : { + thread: sourceThread, + runs: sourceRuns, + attempts: [], + turnItems: sourceItems, + }) as never, + ), + }; + const items = yield* ContextHandoffService.readForkHistoryItems( + store as never, + { thread: sourceThread, runs: sourceRuns, attempts: [] } as never, + sourceRuns.at(-1)!, + ); + return items.map((item) => (item.type === "user_message" ? item.text : "")); +}); + +it.effect("portable fork history stops at /clear (freshContext) and drops ancestor history", () => + Effect.gen(function* () { + const before = RunId.make("run:source-1"); + const clear = RunId.make("run:source-2-clear"); + const texts = yield* readClearFork( + [clearRun(before, clearSourceId, 1), clearRun(clear, clearSourceId, 2, true)], + [ + clearUserItem("old", clearSourceId, before, "before clear", 1), + clearUserItem("new", clearSourceId, clear, "after clear", 2), + ], + ); + assert.deepEqual(texts, ["after clear"]); + }), +); + +it.effect("portable fork history keeps history past a restarted scheduled fresh run", () => + Effect.gen(function* () { + const before = RunId.make("run:source-1"); + const scheduled = RunId.make("run:source-2-scheduled"); + const after = RunId.make("run:source-3"); + // A steering restart points userMessageId at the steer, which carries no scheduledTaskId. + const scheduledRun = { + ...clearRun(scheduled, clearSourceId, 2, true), + userMessageId: MessageId.make("message:steer"), + }; + const texts = yield* readClearFork( + [clearRun(before, clearSourceId, 1), scheduledRun, clearRun(after, clearSourceId, 3)], + [ + clearUserItem("old", clearSourceId, before, "before schedule", 1), + clearUserItem("sched", clearSourceId, scheduled, "scheduled prompt", 2, "task-1"), + clearUserItem("steer", clearSourceId, scheduled, "steer", 3), + clearUserItem("new", clearSourceId, after, "after schedule", 4), + ], + ); + assert.deepEqual(texts, [ + "ancestor history", + "before schedule", + "scheduled prompt", + "steer", + "after schedule", + ]); + }), +); diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.ts index ca6b5ff0fcdf1..ab001147c4519 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts @@ -25,6 +25,7 @@ import { } from "@t3tools/provider-core/server/handoffBudget"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline"; +import { turnItemsSinceContextBoundary } from "./contextBoundary.ts"; import type { ProjectionStoreV2Shape } from "./ProjectionStore.ts"; export class ContextHandoffPrepareError extends Schema.TaggedError()( @@ -147,20 +148,25 @@ export function visibleConversationItems( type ForkHistorySource = Pick; -/** Visible rows of `source`'s own runs through `throughRun`, plus its v1 imported rows. */ +/** Visible rows of `source`'s own runs through `throughRun` since its latest `/clear` boundary. */ const readOwnHistoryItems = Effect.fn("orchestrationV2.contextHandoff.readOwnHistoryItems")( function* ( projectionStore: Pick, source: ForkHistorySource, throughRun: Pick, ) { + const throughRuns = source.runs.filter((run) => run.ordinal <= throughRun.ordinal); const { turnItems } = yield* projectionStore.getThreadRecords(source.thread.id, ["turnItems"], { turnItemRunIds: [ - ...source.runs.filter((run) => run.ordinal <= throughRun.ordinal).map((run) => run.id), + ...throughRuns.map((run) => run.id), ...(source.thread.historyOrigin === "v1_import" ? [null] : []), ], }); - return visibleConversationItems(source, turnItems); + const bounded = turnItemsSinceContextBoundary({ runs: throughRuns, turnItems }); + return { + items: visibleConversationItems(source, bounded.turnItems), + cleared: bounded.boundary > 0, + }; }, ); @@ -186,7 +192,9 @@ export const readInheritedHandoffItems = Effect.fn( .pipe(Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) })); const forkRun = source?.runs.find((run) => run.id === runId); if (source === null || forkRun === undefined) break; - segments.unshift(yield* readOwnHistoryItems(projectionStore, source, forkRun)); + const own = yield* readOwnHistoryItems(projectionStore, source, forkRun); + segments.unshift(own.items); + if (own.cleared) break; current = source.thread; } return segments.flat(); @@ -200,10 +208,9 @@ export const readForkHistoryItems = Effect.fn( source: ForkHistorySource, throughRun: Pick, ) { - return [ - ...(yield* readInheritedHandoffItems(projectionStore, source.thread)), - ...(yield* readOwnHistoryItems(projectionStore, source, throughRun)), - ]; + const own = yield* readOwnHistoryItems(projectionStore, source, throughRun); + if (own.cleared) return own.items; + return [...(yield* readInheritedHandoffItems(projectionStore, source.thread)), ...own.items]; }); function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 10a986269e9bb..7a106478044b1 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -88,7 +88,11 @@ import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; import { modelSwitchSince } from "./modelSwitch.ts"; -import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts"; +import { + contextBoundaryOrdinal, + isScheduledFreshRun, + turnItemsSinceContextBoundary, +} from "./contextBoundary.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { outputRequestProblem } from "./runOutput.ts"; @@ -9454,15 +9458,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const mergeBackDeltaItems = mergeBackSourceProjection === null || mergeBackSourceRun === null ? [] - : visibleConversationItems( - mergeBackSourceProjection, - yield* readHandoffItems( + : yield* Effect.gen(function* () { + const sourceRuns = mergeBackSourceProjection.runs.filter( + (run) => run.ordinal <= mergeBackSourceRun.ordinal, + ); + const rawItems = yield* readHandoffItems( mergeBackSourceProjection.thread.id, - mergeBackSourceProjection.runs - .filter((run) => run.ordinal <= mergeBackSourceRun.ordinal) - .map((run) => run.id), - ), - ); + sourceRuns.map((run) => run.id), + ); + const { turnItems } = turnItemsSinceContextBoundary({ + runs: sourceRuns, + turnItems: rawItems, + }); + return visibleConversationItems(mergeBackSourceProjection, turnItems); + }); const mergeBackHandoff = pendingMergeBackTransfer === undefined || mergeBackSourceProjection === null || @@ -11714,15 +11723,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio continue; } const answered = isMessageQuestionAnswer(answer); - // Clients send "" for a skipped optional question, such as an attachment-only answer. - if (!answered && question.required === false) continue; - if (!answered) { + // Clients send "" for a skipped optional question or an attachment-only answer. + if (!answered && !command.attachmentsByQuestionId?.[question.id]?.length) { + if (question.required === false) continue; return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, cause: "Answer each question before sending.", }); } + if (!answered) { + replies.push(question.question); + continue; + } const text = typeof answer === "string" ? answer : answer.join(", "); replies.push(`${question.question}\n${text.trim()}`); } @@ -11920,7 +11933,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, messageId: MessageId.make(`async-answer:${command.requestId}`), text: replies.join("\n\n"), - attachments: [], + attachments: Object.values(command.attachmentsByQuestionId ?? {}).flat(), createdBy: "user" as const, creationSource: "server" as const, dispatchMode, @@ -14650,7 +14663,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const stopDelegatedTasks = command.stopDelegatedTasks === false || !projection.subagents.some( - (task) => task.origin === "app_owned" && task.childThreadId !== null, + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), ) ? Effect.void : Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 77af7d2680e05..e86cc9dfd4982 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -1479,3 +1479,39 @@ it.effect("skips restart discovery when no project enables continuation", () => yield* recovery.prepareForShutdown; }), ); + +it("does not continue a settled run whose only open subagent is a remote delegated task", () => { + const base = makeProjection(); + for (const status of ["completed", "waiting"] as const) { + const projection = { + ...base, + runs: [{ ...base.runs[0]!, status }], + providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }], + turnItems: [ + { + id: "item:remote-delegated", + threadId, + runId, + nodeId: NodeId.make("task:remote"), + providerThreadId, + type: "subagent", + subagentId: NodeId.make("task:remote"), + origin: "app_owned", + driver, + providerInstanceId: instanceId, + childThreadId: null, + remoteChild: { + environmentId: "env:box", + threadId: ThreadId.make("thread:remote-child"), + label: "Box", + }, + status: "running", + title: "Remote task", + prompt: "Check remote tests", + result: null, + }, + ], + } as unknown as OrchestrationV2ThreadProjection; + assert.isUndefined(restartContinuationRun(projection, now), status); + } +}); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 21d70c62f920e..806f17c20c197 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -144,7 +144,11 @@ function hasOpenAwaitedWork( const openItem = projection.turnItems.some((item) => { if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting") return false; - if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null) + if ( + item.type === "subagent" && + item.origin === "app_owned" && + (item.childThreadId !== null || item.remoteChild !== undefined) + ) return false; const work = cancelledTurnItemWork(item); return ( diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 42a8d7eae9cff..631f9089049c0 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -907,6 +907,7 @@ it.effect.each([ ({ thread: { id: threadId, projectId, deletedAt: null }, runs: raced ? [...runs, nextRun] : runs, + turnItems: [], messages: [ { id: MessageId.make("original"), runId, role: "user" as const }, { @@ -1000,6 +1001,60 @@ it.effect.each([ }), ); +// The agent reads a message steered in after it asked to settle and ends on a question. +it.effect.each(["steer", "promoted_queued_to_steer"] as const)( + "settleAfterRun keeps the thread open after a %s read once the settle was requested", + (inputIntent) => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:settle-after-steer"); + const threadId = ThreadId.make("thread:thread-management:settle-after-steer"); + const runId = RunId.make("run:thread-management:settle-after-steer"); + yield* TestClock.adjust(Duration.millis(60_000)); + const dispatched: Array = []; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadEventSequence: () => Effect.succeed(0), + restartContinuationPending: () => Effect.succeed(false), + streamStoredEventsFrom: () => Stream.empty, + getThreadRecords: () => + Effect.succeed({ + thread: { id: threadId, projectId, deletedAt: null }, + runs: [{ id: runId, ordinal: 1, status: "completed", userMessageId: "original" }], + messages: [ + { id: "original", runId, role: "user" }, + { id: "steered", runId, role: "user" }, + ], + turnItems: [ + { + runId, + type: "user_message", + inputIntent, + status: "completed", + createdAt: "1970-01-01T00:01:30.000Z", + completedAt: "1970-01-01T00:01:30.000Z", + }, + ], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command.type); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const service = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + yield* service.settleAfterRun({ projectId, threadId, runId }); + expect(dispatched).toEqual([]); + }), +); + it.effect.each([ { name: "kills the thread's own agent and ends its turn", diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 0c8879cfe18a5..e3bc51179ed10 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1251,6 +1251,21 @@ const make = Effect.gen(function* () { const requestedAt = yield* DateTime.now; const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS }); if (run?.status !== "completed") return; + // A message steered into this run and read after the request supersedes it. + const { turnItems } = yield* getProjectThreadRecords(input, ["turnItems"], { + turnItemRunIds: [run.id], + turnItemTypes: ["user_message"], + }); + if ( + turnItems.some( + (item) => + item.type === "user_message" && + (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer") && + item.completedAt !== null && + !DateTime.isLessThan(DateTime.makeUnsafe(item.completedAt), requestedAt), + ) + ) + return; const afterSequence = yield* orchestrator.getThreadEventSequence(input.threadId); const trySettle = Effect.gen(function* () { const sequence = yield* orchestrator.getThreadEventSequence(input.threadId); diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts index 81fc56150d7fd..163d6a0d60b54 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts @@ -58,9 +58,16 @@ const layerFailingDispatchHandler = ); }; +const noPendingRuntimeRequests: ThreadManagementService.ThreadManagementServiceShape["getThreadRecords"] = + () => + Effect.succeed({ runtimeRequests: [] } as unknown as Effect.Success< + ReturnType + >); + const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) => Layer.mock(ThreadManagementService.ThreadManagementService)({ dispatch: layerFailingDispatchHandler(captured), + getThreadRecords: noPendingRuntimeRequests, }); const NOW = DateTime.makeUnsafe("2026-09-13T00:00:00.000Z"); @@ -144,6 +151,60 @@ it.effect("claims question uploads and passes readable paths through the V2 requ }).pipe(Effect.provide(layerIntakeTest)), ); +it.effect("leaves an async answer's text alone so its files travel as message attachments", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const id = ChatAttachmentId.make(createPendingAttachmentId()!); + NodeFS.writeFileSync( + NodePath.join(config.attachmentsDir, `${id}.png`), + new Uint8Array([1, 2, 3]), + ); + const threadId = ThreadId.make("thread-async-answer"); + const requestId = RuntimeRequestId.make("request-async"); + const captured: OrchestrationV2ServerCommand[] = []; + yield* dispatchCommand({ + type: "runtime-request.respond", + commandId: CommandId.make("answer-async"), + threadId, + requestId, + answers: { q: "" }, + attachmentsByQuestionId: { + q: [{ type: "image", id, name: "screen.png", mimeType: "image/png", sizeBytes: 3 }], + }, + }).pipe( + Effect.provide( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + dispatch: layerFailingDispatchHandler(captured), + getThreadRecords: () => + Effect.succeed({ + runtimeRequests: [ + { + id: requestId, + nodeId: null, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { type: "message" }, + createdAt: NOW, + resolvedAt: null, + }, + ], + } as unknown as Effect.Success< + ReturnType + >), + }), + ), + Effect.result, + ); + expect(captured).toHaveLength(1); + const command = captured[0]!; + if (command.type !== "runtime-request.respond") throw new Error("expected a response"); + expect(command.answers).toEqual({ q: "" }); + expect(command.attachmentsByQuestionId?.q).toHaveLength(1); + }).pipe(Effect.provide(layerIntakeTest)), +); + it.effect("retains claimed copies when dispatch failure may have been accepted", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -209,6 +270,7 @@ it.effect("releases claimed copies when the command was already rejected", () => }).pipe( Effect.provide( Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: noPendingRuntimeRequests, dispatch: (command) => Effect.fail( new OrchestratorCommandPreviouslyRejectedError({ @@ -276,6 +338,7 @@ it.effect("releases claimed copies when dispatch replays an earlier accepted res }).pipe( Effect.provide( Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: noPendingRuntimeRequests, dispatch: () => Effect.succeed({ sequence: 1, storedEvents }), }), ), @@ -346,6 +409,7 @@ it.effect("a retried response re-claims the preserved pending uploads", () => const retry = yield* dispatchCommand(command).pipe( Effect.provide( Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: noPendingRuntimeRequests, dispatch: (dispatched) => { captured.push(dispatched); return Effect.succeed({ sequence: 1, storedEvents: [] }); diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index 5d9ec263b0b0d..165a92ab4e3b4 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -156,15 +156,34 @@ export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")( enumerable: true, }); } - const answers = yield* appendUserInputAttachmentPaths({ - answers: command.answers ?? {}, - attachmentsByQuestionId, - attachmentsDir: config.attachmentsDir, - }).pipe( - Effect.mapError( - (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }), - ), - ); + // An answer by message carries its files as message attachments, not paths in its text. + const { runtimeRequests } = yield* threads + .getThreadRecords(command.threadId, ["runtimeRequests"], { + runtimeRequestStatuses: ["pending"], + }) + .pipe( + Effect.mapError( + (cause) => + new AttachmentClaims.AttachmentClaimError({ + message: "Failed to read the question.", + cause, + }), + ), + ); + const answersByMessage = + runtimeRequests.find((request) => request.id === command.requestId)?.responseCapability + .type === "message"; + const answers = answersByMessage + ? (command.answers ?? {}) + : yield* appendUserInputAttachmentPaths({ + answers: command.answers ?? {}, + attachmentsByQuestionId, + attachmentsDir: config.attachmentsDir, + }).pipe( + Effect.mapError( + (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }), + ), + ); return { answers, attachmentsByQuestionId }; }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths))); return yield* threads diff --git a/apps/server/src/orchestration-v2/ThreadSearch.test.ts b/apps/server/src/orchestration-v2/ThreadSearch.test.ts index 1ea5b9daa4af9..7078f80c22301 100644 --- a/apps/server/src/orchestration-v2/ThreadSearch.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSearch.test.ts @@ -1474,6 +1474,7 @@ it.effect("starts snippets a few words before the match so one line shows it", ( snippet(`x${"🚀".repeat(200)}needle`, "needle"), /[\ud800-\udbff](?![\udc00-\udfff])|(?, + run: Pick, turnItems: OrchestrationV2ThreadProjection["turnItems"], ): boolean { + if (run.freshContext !== true) return false; + // A steering restart replaces userMessageId; the run's first prompt still records its origin. // A compacted thread's command read loads these prompts for every fresh-context run. - return ( - run.freshContext === true && - turnItems.some( - (item) => - item.type === "user_message" && - item.messageId === run.userMessageId && - item.scheduledTaskId !== undefined, - ) - ); + let prompt: OrchestrationV2ThreadProjection["turnItems"][number] | undefined; + for (const item of turnItems) { + if (item.type !== "user_message") continue; + if (item.runId === run.id) { + if (prompt?.runId !== run.id || item.ordinal < prompt.ordinal) prompt = item; + } else if (prompt === undefined && item.messageId === run.userMessageId) { + prompt = item; + } + } + return prompt?.type === "user_message" && prompt.scheduledTaskId !== undefined; } /** Ordinal of the latest started fresh-context run. Runs before it never reach a provider again. */ @@ -37,3 +40,18 @@ export function contextBoundaryOrdinal( } return boundary; } + +/** Rows of runs from the latest context boundary on; all rows when nothing was cleared. */ +export function turnItemsSinceContextBoundary( + projection: Pick, +): { readonly boundary: number; readonly turnItems: OrchestrationV2ThreadProjection["turnItems"] } { + const boundary = contextBoundaryOrdinal(projection); + if (boundary === 0) return { boundary, turnItems: projection.turnItems }; + const kept = new Set( + projection.runs.filter((run) => run.ordinal >= boundary).map((run) => run.id), + ); + return { + boundary, + turnItems: projection.turnItems.filter((item) => item.runId !== null && kept.has(item.runId)), + }; +} diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 7eb1868cbb1f5..506c3d203b453 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -170,6 +170,42 @@ describe("evaluatePullRequestWatch", () => { ); }); + it.each([false, true])( + "reports CI that passes during registration once (required: %s)", + (required) => { + const green = detail({ checks: [{ ...check("test", "success"), required }] }); + for (const awaitingBaseline of ["all", "checks"] as const) { + const first = evaluatePullRequestWatch( + watch({ awaitingBaseline, checksPending: true }), + green, + noRemarks, + ); + assert.deepEqual(first.changes, [{ kind: "checks-passed", count: 1, required }]); + assert.isFalse(first.next.checksPending); + assert.deepEqual(evaluatePullRequestWatch(first.next, green, noRemarks).changes, []); + } + }, + ); + + it("does not announce an unchanged required gate while optional CI still runs", () => { + const pending = detail({ + checks: [{ ...check("test", "success"), required: true }, check("advisory", "pending")], + }); + const first = evaluatePullRequestWatch( + watch({ awaitingBaseline: "all", checksPending: true }), + pending, + noRemarks, + ); + assert.deepEqual(first.changes, []); + const green = { + ...pending, + checks: pending.checks.map((check) => ({ ...check, status: "success" as const })), + }; + const finished = evaluatePullRequestWatch(first.next, green, noRemarks); + assert.deepEqual(finished.changes, [{ kind: "checks-passed", count: 2, required: false }]); + assert.deepEqual(evaluatePullRequestWatch(finished.next, green, noRemarks).changes, []); + }); + it("baselines existing failures and conflicts, then reports new ones", () => { const broken = detail({ checks: [check("lint", "failure"), check("test", "pending")], diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index e6e0be0f20310..284949f96c510 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -163,7 +163,9 @@ export function evaluatePullRequestWatch( checks.every((check) => check.status !== "pending"); owedChecks = owed; if (passedNow && (!passed || gateGrew)) { - if (!checksBaseline) { + // CI running at the start that has since settled green is news. The start rollup can be + // pending only on optional checks, so a passed gate alone is not. + if (!checksBaseline || (watch.checksPending === true && settled)) { changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 }); } owedChecks = diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 27091a5027bcd..370fd7deb9ade 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -2771,6 +2771,47 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { }), ); + it.effect("sends an async answer's files as attachments on the answer message", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-async-question-files"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("runtime-async-question-files-create"), + createdBy: "user", + creationSource: "web", + threadId, + projectId: ProjectId.make("runtime-async-question-files-project"), + title: "Async question with files", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const { requestId } = yield* seedPendingQuestion(threadId, null, { type: "message" }); + const screenshot = { + type: "image" as const, + id: createAttachmentId(threadId)!, + name: "screen.png", + mimeType: "image/png", + sizeBytes: 3, + }; + yield* orchestrator.dispatch({ + type: "runtime-request.respond", + commandId: CommandId.make("runtime-async-question-files-answer"), + threadId, + requestId, + answers: { color: "", sizes: ["Small"], note: "" }, + attachmentsByQuestionId: { color: [screenshot] }, + }); + const answered = yield* orchestrator.getThreadProjection(threadId); + assert.equal(answered.messages.length, 1); + assert.equal(answered.messages[0]?.text, "Which color?\n\nWhich sizes?\nSmall"); + assert.deepEqual(answered.messages[0]?.attachments, [screenshot]); + }), + ); + it.effect("reports an answer that never reaches its provider without reopening it", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 3c14fb427fc2e..d075c44ef9ff2 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -37,7 +37,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Tracer from "effect/Tracer"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as TestClock from "effect/testing/TestClock"; -import type * as SqlClient from "effect/sql/SqlClient"; +import * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; import * as ServerConfig from "../config.ts"; @@ -2079,6 +2079,37 @@ it.effect("stopping the parent stops its task there", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("the parent's Stop queues stopping a task that runs only there", () => + 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 a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + + yield* delegateToBox(a); + yield* a.orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("command:thread-stop:remote-only"), + threadId: parentThreadId, + reason: "User stopped", + }); + const sql = Context.get(database, SqlClient.SqlClient); + const outbox = yield* sql<{ readonly effect_type: string }>` + SELECT effect_type + FROM orchestration_v2_effect_outbox + WHERE thread_id = ${parentThreadId} + `; + expect(outbox.some((row) => row.effect_type === "delegated-tasks.stop")).toBe(true); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + /** A follower retry schedule the test steps: each failed attempt is offered, then waits for `retry`. */ const steppedRetries = Effect.gen(function* () { const failed = yield* Queue.unbounded(); diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 278bba1c96b9c..2f9ea973261f9 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -23,6 +23,7 @@ import { expect, vi } from "vite-plus/test"; import { FetchHttpClient } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "./PortScanner.ts"; @@ -1023,12 +1024,17 @@ effectIt.effect.each(["linux", "darwin"] as const)( effectIt.effect("stops only a job's own process group", () => Effect.sync(() => { const serverPid = 100; + const launcherPid = 150; const rows = [ { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job { pid: serverPid, ppid: 10, pgid: 10 }, - { pid: 200, ppid: serverPid, pgid: 200 }, // agent CLI + { pid: launcherPid, ppid: serverPid, pgid: 10 }, // Linux ProcessLauncher worker + { pid: 200, ppid: serverPid, pgid: 200 }, // direct agent CLI { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own + { pid: 250, ppid: launcherPid, pgid: 250 }, // launcher-spawned agent CLI (e.g. agy acp) + { pid: 260, ppid: 250, pgid: 250 }, // a server in the launcher-spawned agent CLI's group + { pid: 270, ppid: 250, pgid: 270 }, // a job started by the launcher-spawned agent CLI { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &` { pid: 401, ppid: 400, pgid: 400 }, @@ -1036,10 +1042,11 @@ effectIt.effect("stops only a job's own process group", () => { pid: 600, ppid: 500, pgid: 600 }, // terminal job ]; const table = new Map(rows.map((row) => [row.pid, row])); - expect(PortScanner.stoppableProcessGroup(table, 401, serverPid)).toBe(400); - expect(PortScanner.stoppableProcessGroup(table, 600, serverPid)).toBe(600); - for (const pid of [20, 210, 500, 999]) { - expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull(); + expect(PortScanner.stoppableProcessGroup(table, 401, serverPid, launcherPid)).toBe(400); + expect(PortScanner.stoppableProcessGroup(table, 600, serverPid, launcherPid)).toBe(600); + expect(PortScanner.stoppableProcessGroup(table, 270, serverPid, launcherPid)).toBe(270); + for (const pid of [20, 150, 210, 250, 260, 500, 999]) { + expect(PortScanner.stoppableProcessGroup(table, pid, serverPid, launcherPid)).toBeNull(); } // The tool shell is the command; its `npm run dev &` job only inherited the name. const variables = new Map([ @@ -1055,6 +1062,152 @@ effectIt.effect("stops only a job's own process group", () => }), ); +effectIt.effect( + "excludes Linux agent CLIs spawned through ProcessLauncher (including after restarts) while keeping their dev servers", + () => { + let launcherPid = 9_000; + const firstDevPort = 43_201; + const secondDevPort = 43_202; + let lsofStdout = + `p4300\ncagy\nn127.0.0.1:43200\n` + + `p4301\ncclaude\nn127.0.0.1:43199\n` + + `p4242\ncnode\nn127.0.0.1:${firstDevPort}\n`; + const procFiles: Record = { + "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`, + "/proc/4300/stat": `4300 (agy) S ${launcherPid} 4300 4300 0`, + "/proc/4301/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-claude\0`, + "/proc/4301/stat": `4301 (claude) S ${process.pid} 4301 4301 0`, + "/proc/4242/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`, + "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0", + }; + const missing = FileSystem.makeNoop({}); + const layer = layerScanner.pipe( + Layer.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + readFileString: (path) => { + const content = procFiles[path]; + return content === undefined ? missing.readFileString(path) : Effect.succeed(content); + }, + }), + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => + input.command === "lsof" + ? Effect.succeed(processOutput(lsofStdout)) + : Effect.succeed( + processOutput( + `${launcherPid} ${process.pid} ${process.pid}\n` + + `4300 ${launcherPid} 4300\n` + + "4242 4300 4300\n", + ), + ), + }), + Layer.succeed(ProcessLauncher.ProcessLauncher, { + currentPid: Effect.sync(() => launcherPid), + }), + Layer.succeed(HostProcess.Platform, "linux"), + FetchHttpClient.layer.pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, () => Promise.reject(new Error()))), + ), + ), + ), + ); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + expect(yield* scanner.scan()).toMatchObject([ + { port: firstDevPort, pid: 4242, agent: { threadId: "thread-agy" } }, + ]); + + // Refuses to stop a server sharing the ProcessLauncher-spawned agent CLI's process group. + const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: firstDevPort })); + expect(stop.reason).toBe("shared-group"); + + // After ProcessLauncher restarts with a new helper PID, new agent CLIs are still excluded. + launcherPid = 9_001; + procFiles["/proc/4400/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`; + procFiles["/proc/4400/stat"] = `4400 (agy) S ${launcherPid} 4400 4400 0`; + procFiles["/proc/4401/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`; + procFiles["/proc/4401/stat"] = "4401 (node) S 4400 4401 4401 0"; + lsofStdout = `p4400\ncagy\nn127.0.0.1:43210\np4401\ncnode\nn127.0.0.1:${secondDevPort}\n`; + + expect(yield* scanner.scan()).toMatchObject([ + { port: secondDevPort, pid: 4401, agent: { threadId: "thread-agy-2" } }, + ]); + }).pipe(Effect.provide(layer)); + }, +); + +effectIt.effect.each([ + { + case: "its parent's arguments", + leader: { command: "node server.js", env: "COMMAND=cmd-a" }, + parent: { command: "/bin/bash -c set -m; COMMAND=cmd-a node server.js & wait", env: "" }, + stops: ["cmd-a"], + }, + { + case: "its own arguments", + leader: { command: "node server.js COMMAND=cmd-a", env: "" }, + parent: { command: "/bin/bash -c node server.js & wait", env: "" }, + stops: [], + }, +])("on macOS, a stop names the command in the leader's environment, not $case", (scenario) => { + const port = 43_127; + // macOS `ps -E` prints the environment after the arguments; plain `ps` prints only the arguments. + const command = (row: { command: string; env: string }, withEnvironment: boolean) => + withEnvironment + ? `${row.command} PATH=/usr/bin ${PortScanner.AGENT_THREAD_ENV}=thread-a ${row.env}`.trim() + : row.command; + const layer = layerScanner.pipe( + Layer.provide( + Layer.mergeAll( + layerNoProc, + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => { + if (input.command === "lsof") { + return Effect.succeed(processOutput(`p4242\ncnode\nn127.0.0.1:${port}\n`)); + } + if (input.args[0] === "-A") { + return Effect.succeed( + processOutput(`4242 4300 4242\n4300 4200 4300\n4200 ${process.pid} 4200\n`), + ); + } + const withEnvironment = input.args.includes("-E"); + const withParent = input.args.includes("pid=,ppid=,command="); + return Effect.succeed( + processOutput( + ` 4242${withParent ? " 4300" : ""} ${command(scenario.leader, withEnvironment)}\n` + + ` 4300${withParent ? " 4200" : ""} ${command(scenario.parent, withEnvironment)}\n`, + ), + ); + }, + }), + Layer.succeed(HostProcess.Platform, "darwin"), + FetchHttpClient.layer, + ), + ), + ); + + return Effect.gen(function* () { + const signal = vi.spyOn(ProcessGroup, "signalProcessGroup").mockImplementation(() => { + throw Object.assign(new Error("No such process"), { code: "ESRCH" }); + }); + yield* Effect.addFinalizer(() => Effect.sync(() => signal.mockRestore())); + const scanner = yield* PortScanner.PortDiscovery; + scanner.trackAgent(); + const stops: string[] = []; + yield* scanner.watchAgentCommandStops({ + variable: "COMMAND", + onStop: (stopped) => Effect.sync(() => stops.push(stopped)), + onStopAbandoned: () => Effect.void, + }); + expect(yield* scanner.scan()).toMatchObject([{ pid: 4242, agent: { threadId: "thread-a" } }]); + yield* scanner.stopServer({ pid: 4242, port }); + expect(signal).toHaveBeenCalledExactlyOnceWith(4242, "SIGTERM"); + expect(stops).toEqual(scenario.stops); + }).pipe(Effect.scoped, Effect.provide(layer)); +}); + const AGENT_SERVER_SCRIPT = ` const server = require("node:http").createServer((_, response) => { response.writeHead(200, { "content-type": "text/html" }); diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index bbbd6bf53db92..c48d6a3ad6abe 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -26,6 +26,7 @@ import * as Semaphore from "effect/Semaphore"; import { FetchHttpClient, HttpClient } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as WindowsTcpListeners from "../process/windowsTcpListeners.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -388,14 +389,23 @@ const parseProcEnvironThread = (raw: string): ThreadId | null => { }; /** - * A listener with an agent thread in its environment. An agent CLI is a direct child of this - * server and has that environment too, but its own ports are not servers it started. + * A listener with an agent thread in its environment. An agent CLI is spawned directly by this + * server or its Linux process launcher and has that environment too, but its own ports are not + * servers it started. */ interface AgentListener { readonly threadId: ThreadId; readonly isAgentCli: boolean; } +const isServerSpawnedChild = ( + parentPid: number | null, + serverPid: number, + launcherPid?: number, +): boolean => + parentPid !== null && + (parentPid === serverPid || (launcherPid !== undefined && parentPid === launcherPid)); + /** Reads the parent pid from `/proc//stat`, whose command field can hold spaces. */ const parseProcStatParent = (raw: string): number | null => { const parent = Number( @@ -414,6 +424,7 @@ const parseProcStatParent = (raw: string): number | null => { const parsePsEnvironmentThreads = ( raw: string, serverPid: number, + launcherPid?: number, ): ReadonlyMap => { const threads = new Map(); for (const line of raw.split("\n")) { @@ -423,13 +434,25 @@ const parsePsEnvironmentThreads = ( threads.set( Number(match[1]), value && !DEVTOOLS_PORT_ARGUMENT.test(match[3]!) - ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } + ? { + threadId: ThreadId.make(value), + isAgentCli: isServerSpawnedChild(Number(match[2]), serverPid, launcherPid), + } : null, ); } return threads; }; +const parsePsCommandLines = (raw: string): ReadonlyMap => { + const lines = new Map(); + for (const line of raw.split("\n")) { + const match = /^\s*(\d+)\s(.*)$/.exec(line); + if (match) lines.set(Number(match[1]), match[2]!); + } + return lines; +}; + /** Splits `/proc//environ` on NUL, or the environment macOS `ps -E` appends on spaces. */ const parseEnvironmentVariables = ( raw: string, @@ -480,16 +503,19 @@ const parseProcessTable = (raw: string): ReadonlyMap => /** * The process group stopping `pid` signals. Shells with job control and agent tool shells give * every job its own group, so the group is the job. Null when the group also holds this server, - * a direct child of it (agent CLIs and terminal shells), or one of its ancestors. + * a direct child of it or its process launcher (agent CLIs and terminal shells), or one of its + * ancestors. */ export const stoppableProcessGroup = ( table: ReadonlyMap, pid: number, serverPid: number, + launcherPid?: number, ): number | null => { const group = table.get(pid)?.pgid; if (group === undefined || group <= 1) return null; const guarded = new Set([serverPid]); + if (launcherPid !== undefined) guarded.add(launcherPid); for ( let parent = table.get(serverPid)?.ppid; parent !== undefined && parent > 1 && !guarded.has(parent); @@ -498,7 +524,12 @@ export const stoppableProcessGroup = ( guarded.add(parent); } for (const row of table.values()) { - if (row.pgid === group && (guarded.has(row.pid) || row.ppid === serverPid)) return null; + if ( + row.pgid === group && + (guarded.has(row.pid) || isServerSpawnedChild(row.ppid, serverPid, launcherPid)) + ) { + return null; + } } return group; }; @@ -542,6 +573,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const listenerDiscovery = (yield* HostProcess.Environment)[PORT_DISCOVERY_ENV] !== "0"; const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope); const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const processLauncher = yield* ProcessLauncher.ProcessLauncher; const stateRef = yield* Ref.make({ listeners: new Map(), terminalProcesses: new Map(), @@ -572,6 +604,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ) { const cached = yield* Ref.get(agentThreadsRef); const unread = pids.filter((pid) => !cached.has(pid)); + const launcherPid = unread.length === 0 ? undefined : yield* processLauncher.currentPid; const readProcListener = Effect.fnUntraced(function* (pid: number) { const threadId = yield* fileSystem.readFileString(`/proc/${pid}/environ`).pipe( Effect.map(parseProcEnvironThread), @@ -587,7 +620,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() { Effect.map(parseProcStatParent), Effect.orElseSucceed(() => null), ); - return [pid, { threadId, isAgentCli: parent === process.pid }] as const; + return [ + pid, + { threadId, isAgentCli: isServerSpawnedChild(parent, process.pid, launcherPid) }, + ] as const; }); const read: ReadonlyMap = unread.length === 0 @@ -602,7 +638,9 @@ export const make = Effect.gen(function* PortDiscoveryMake() { maxOutputBytes: PS_MAX_OUTPUT_BYTES, }) .pipe( - Effect.map((result) => parsePsEnvironmentThreads(result.stdout, process.pid)), + Effect.map((result) => + parsePsEnvironmentThreads(result.stdout, process.pid, launcherPid), + ), Effect.orElseSucceed(() => { agentScanPending = true; return new Map(); @@ -1136,19 +1174,36 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ); return new Map(read.flatMap(Option.toArray)); } - const result = yield* processRunner - .run({ - command: "ps", - args: ["-E", "-ww", "-o", "pid=,command=", "-p", pids.join(",")], - timeout: Duration.millis(PS_TIMEOUT_MS), - maxOutputBytes: PS_MAX_OUTPUT_BYTES, - }) - .pipe(Effect.option); + const readCommandLines = (withEnvironment: boolean) => + processRunner + .run({ + command: "ps", + args: [ + ...(withEnvironment ? ["-E"] : []), + "-ww", + "-o", + "pid=,command=", + "-p", + pids.join(","), + ], + timeout: Duration.millis(PS_TIMEOUT_MS), + maxOutputBytes: PS_MAX_OUTPUT_BYTES, + }) + .pipe( + Effect.map((result) => parsePsCommandLines(result.stdout)), + Effect.orElseSucceed(() => new Map()), + ); + // `ps -E` prints the environment after the arguments, so the arguments alone are read + // separately and only what follows them counts as environment. + const [withEnvironment, argumentsOnly] = yield* Effect.all( + [readCommandLines(true), readCommandLines(false)], + { concurrency: 2 }, + ); const variables = new Map>(); - for (const line of Option.isSome(result) ? result.value.stdout.split("\n") : []) { - const match = /^\s*(\d+)\s(.*)$/.exec(line); - if (match) { - variables.set(Number(match[1]), parseEnvironmentVariables(match[2]!, /\s+/, names)); + for (const [pid, line] of withEnvironment) { + const commandLine = argumentsOnly.get(pid); + if (commandLine !== undefined && line.startsWith(commandLine)) { + variables.set(pid, parseEnvironmentVariables(line.slice(commandLine.length), /\s+/, names)); } } return variables; @@ -1216,7 +1271,12 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const table = yield* readProcessTable; // It exited after the scan, so there is nothing left to stop. if (!table.has(input.pid)) return; - const group = stoppableProcessGroup(table, input.pid, process.pid); + const group = stoppableProcessGroup( + table, + input.pid, + process.pid, + yield* processLauncher.currentPid, + ); if (group === null) return yield* new PreviewStopLocalServerError({ reason: "shared-group" }); // False when the whole group already exited. const signalGroup = (signal: "SIGTERM" | "SIGKILL") => diff --git a/apps/server/src/preview/PreviewBrowser.ts b/apps/server/src/preview/PreviewBrowser.ts index 3f0de9b0af346..306a0bf1f1e8c 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). -export const VERSION = "158.0.8127.36"; +export const VERSION = "158.0.8127.88"; const ARCHIVES = { linux64: { - bytes: 132_087_165, - sha256: "2d3a23017323c54fd457a678e4351f895c4076d8050e39d5aa6247f93448b73a", + bytes: 132_091_593, + sha256: "63401333cc587645bfaeea7f0c90958b327d249251e23954a47f30112ca23d5b", }, "linux-arm64": { - bytes: 129_938_239, - sha256: "176ee5c55486c22de43128871189061365ea28e881fc96016fd18e7cb59437c8", + bytes: 129_942_265, + sha256: "9f89b7ef6574e4bbf6ddda9f17f1fab5626e93d6f7d852653232d0d3554df975", }, "mac-arm64": { - bytes: 105_057_133, - sha256: "c24d40a3786322ff3a5e3ac6eed162226cbaf07ebe468715407827226b0f8897", + bytes: 105_060_087, + sha256: "69320f6869c4defbbdac8b8fa83aef65dc63975e83bbd06899b75dbea5c464b3", }, "mac-x64": { - bytes: 112_306_247, - sha256: "e0c5d07d8f5bcc5bdd5ef370e7daf3770856b585fcc9eecf441c7e3bb2e3d1cf", + bytes: 112_314_759, + sha256: "dc1ac31965cb2ec7794aed8c66127aceea304ae15353cd56fc4b8bde44091548", }, win32: { - bytes: 122_509_290, - sha256: "c1fc009622363bccbc1e5f60be654b90fa7b70ad83e642875da1fcb147ae430d", + bytes: 122_509_314, + sha256: "936ad5e7f530bdd66b7261d0a2ceed76b057d429cf31b770a95fd903a7969856", }, win64: { - bytes: 127_876_264, - sha256: "9655950dfeddf565561cd64cfe8ee716ccd6482fa3798503b632219efc65a71e", + bytes: 127_879_225, + sha256: "e935ea2d4633495b5e9ab7bc66bcd982806329c0ee9ecbafc1ac9596a3b34cdb", }, } as const; diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts index f62a3c8445da2..397be7c42885d 100644 --- a/apps/server/src/process/ProcessLauncher.ts +++ b/apps/server/src/process/ProcessLauncher.ts @@ -22,6 +22,16 @@ import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorke const READY_TIMEOUT = "10 seconds"; const SPAWN_REPLY_TIMEOUT = "10 seconds"; +/** + * Exposes the active Linux process-launcher helper PID so callers such as port discovery can + * recognize direct children spawned through the helper instead of directly from the server. + */ +export class ProcessLauncher extends Context.Reference<{ + readonly currentPid: Effect.Effect; +}>("t3/process/ProcessLauncher", { + defaultValue: () => ({ currentPid: Effect.undefined }), +}) {} + /** A child of the launcher, presented to the native spawner as a Node ChildProcess. */ class HostedChild extends NodeEvents.EventEmitter @@ -152,7 +162,11 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT, ) { const fallback = yield* ChildProcessSpawner.ChildProcessSpawner; - if ((yield* HostProcess.Platform) !== "linux") return fallback; + if ((yield* HostProcess.Platform) !== "linux") { + return Context.make(ChildProcessSpawner.ChildProcessSpawner, fallback).pipe( + Context.add(ProcessLauncher, { currentPid: Effect.undefined }), + ); + } const executablePath = yield* HostProcess.ExecutablePath; const args = yield* launcherArguments(); @@ -368,13 +382,16 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( ); // Start while the server is still small; the launcher's own fork is the last full-size one. launch(); - return ChildProcessSpawner.make((command) => + const spawner = ChildProcessSpawner.make((command) => Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)), ); + return Context.make(ChildProcessSpawner.ChildProcessSpawner, spawner).pipe( + Context.add(ProcessLauncher, { currentPid: Effect.sync(() => current?.worker.pid) }), + ); }); /** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ -export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); +export const layer = Layer.effectContext(make()); /** The server's one spawner: memoized, so every build site shares a single launcher. */ export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer)); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index bd4ad037defa6..f31d7411c8625 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -592,10 +592,12 @@ describe("ProcessRunner.layer", () => { () => Effect.gen(function* () { const runner = yield* ProcessRunner.ProcessRunner; + const launcher = yield* ProcessLauncher.ProcessLauncher; const parentPid = runner .run({ command: "sh", args: ["-c", "echo $PPID"] }) .pipe(Effect.map((result) => expectHelperPid(result.stdout))); const helper = yield* parentPid; + expect(yield* launcher.currentPid).toBe(helper); process.kill(helper, "SIGSTOP"); const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); const replacement = yield* parentPid; @@ -603,15 +605,11 @@ describe("ProcessRunner.layer", () => { expect(error._tag).toBe("ProcessSpawnError"); expect(replacement).not.toBe(helper); expect(replacement).not.toBe(process.pid); + expect(yield* launcher.currentPid).toBe(replacement); }).pipe( Effect.provide( ProcessRunner.layer.pipe( - Layer.provide( - Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - ProcessLauncher.make("1 second"), - ), - ), + Layer.provideMerge(Layer.effectContext(ProcessLauncher.make("1 second"))), Layer.provide(NodeServices.layer), ), ), @@ -651,12 +649,7 @@ describe("ProcessRunner.layer", () => { const runner = Context.get( yield* Layer.build( ProcessRunner.layer.pipe( - Layer.provide( - Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - ProcessLauncher.make("1 second"), - ), - ), + Layer.provide(Layer.effectContext(ProcessLauncher.make("1 second"))), ), ), ProcessRunner.ProcessRunner, diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 09a7a396a294f..0fcab0d7ad4c3 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1345,6 +1345,60 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("excludes sandboxes recorded by their real path when the base dir is a symlink", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const realBaseDir = yield* fileSystem.realPath(yield* makeTempDir("t3code-scanner-base-")); + const linkParent = yield* makeTempDir("t3code-scanner-links-"); + const configBaseDir = path.join(linkParent, "t3-home"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + + const worktreeCwd = path.join(realBaseDir, "worktrees", "t3code", "wt-4"); + yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(worktreeCwd), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates).toEqual([]); + }), + ); + + it.effect("offers an outside project reached through a link inside a symlinked base dir", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const projectDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-project-"), + ); + const realBaseDir = yield* fileSystem.realPath(yield* makeTempDir("t3code-scanner-base-")); + const linkParent = yield* makeTempDir("t3code-scanner-links-"); + const configBaseDir = path.join(linkParent, "t3-home"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + const projectLink = path.join(realBaseDir, "project-link"); + yield* fileSystem.symlink(projectDir, projectLink); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(projectLink), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: projectLink, threadCount: 1 }, + ]); + }), + ); + it.effect("finds the cwd on a later line when the first records carry none", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1937,6 +1991,129 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect.each([{ layout: "plain" }, { layout: "symlinked into Downloads" }] as const)( + "does not file T3 sandbox chats under the Codex project they were moved into ($layout base dir)", + ({ layout }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nowMs = Date.parse("2026-11-08T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const homeDir = yield* makeTempDir("t3code-home-"); + let configBaseDir = yield* makeTempDir("t3code-scanner-base-"); + let realBaseDir = configBaseDir; + if (layout === "symlinked into Downloads") { + // A Downloads folder is scratch, so only the base's real spelling tells the sandbox apart. + realBaseDir = path.join(homeDir, "Downloads", "t3-data"); + yield* fileSystem.makeDirectory(realBaseDir, { recursive: true }); + configBaseDir = path.join(homeDir, "t3-link"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + } + const projectDir = path.join(homeDir, "code", "my-project"); + const sandboxDir = path.join(realBaseDir, "worktrees", "my-project", "wt-1"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.makeDirectory(sandboxDir, { recursive: true }); + + const projectId = "019a5f00-0000-7000-8000-000000000101"; + const chats = [ + { + id: "019a5f00-0000-7000-8000-00000000010a", + cwd: projectDir, + message: "Started in the project", + }, + { + id: "019a5f00-0000-7000-8000-00000000010b", + cwd: sandboxDir, + message: "Started in a T3 worktree", + }, + ]; + const rolloutPaths: Array = []; + for (const [index, chat] of chats.entries()) { + const filePath = path.join( + codexHomePath, + "sessions", + "2026", + "11", + "08", + `rollout-2026-11-08T08-0${index}-00-${chat.id}.jsonl`, + ); + rolloutPaths.push(filePath); + yield* writeTranscript({ + filePath, + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: chat.id, cwd: chat.cwd }, + }), + encodeTranscriptRecord({ type: "turn_context", payload: { cwd: chat.cwd } }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: chat.message }, + }), + ].join("\n"), + mtimeMs: nowMs - 60_000 + index, + }); + } + yield* Effect.sync(() => { + const db = new NodeSqlite.DatabaseSync(path.join(codexHomePath, "state_5.sqlite")); + try { + db.exec(` + CREATE TABLE projects ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}', + position INTEGER NOT NULL, + created_at_ms INTEGER NOT NULL, + updated_at_ms INTEGER NOT NULL + ); + CREATE TABLE project_roots ( + project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + position INTEGER NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (project_id, position) + ); + CREATE TABLE threads ( + id TEXT PRIMARY KEY, + rollout_path TEXT NOT NULL, + cwd TEXT NOT NULL, + project_id TEXT REFERENCES projects(id) ON DELETE SET NULL + ); + `); + db.prepare("INSERT INTO projects VALUES (?, ?, '{}', 0, ?, ?)").run( + projectId, + "my-project", + nowMs, + nowMs, + ); + db.prepare("INSERT INTO project_roots VALUES (?, 0, ?)").run(projectId, projectDir); + const insertThread = db.prepare("INSERT INTO threads VALUES (?, ?, ?, ?)"); + for (const [index, chat] of chats.entries()) { + insertThread.run(chat.id, rolloutPaths[index]!, chat.cwd, projectId); + } + } finally { + db.close(); + } + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + configBaseDir, + workspaceRoot: projectDir, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); + expect(threads.map((thread) => thread.title)).toEqual(["Started in the project"]); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }).pipe( + Effect.provideService(HostProcess.HomeDirectory, homeDir), + ); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual( + [{ path: projectDir, threadCount: 1 }], + ); + }), + ); + it.effect("imports a rewound Codex thread with the history its new rollout inherits", () => 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 b9029b8746b46..745d60e6f2c26 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -921,8 +921,17 @@ export const make = Effect.gen(function* () { const serverSettings = yield* ServerSettings.ServerSettingsService; const projectStore = yield* ProjectStore.ProjectStoreV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - const baseDir = path.resolve(serverConfig.baseDir); - const worktreesDir = path.resolve(serverConfig.worktreesDir); + const configuredT3Dirs = { + baseDir: path.resolve(serverConfig.baseDir), + worktreesDir: path.resolve(serverConfig.worktreesDir), + }; + // Resolved candidates are compared with T3's folders as resolved too, so a symlinked base still matches. + const realPathOf = (directory: string) => + fileSystem.realPath(directory).pipe(Effect.orElseSucceed(() => directory)); + const realT3Dirs = { + baseDir: yield* realPathOf(configuredT3Dirs.baseDir), + worktreesDir: yield* realPathOf(configuredT3Dirs.worktreesDir), + }; const platform = yield* HostProcess.Platform; const isWindows = platform === "win32"; const foldWorktreeCase = isWindows; @@ -939,17 +948,19 @@ export const make = Effect.gen(function* () { path.join(homeDir, "Documents", "Codex"), ]; - const isExcludedProjectPath = (candidatePath: string) => + const isScratchPath = (candidatePath: string) => excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) || excludedProjectAncestors.some((ancestor) => normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( normalizeForWorktreeMatch(ancestor, foldWorktreeCase), ), - ) || + ); + const isT3OwnedPath = (candidatePath: string, t3Dirs = configuredT3Dirs) => normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( - normalizeForWorktreeMatch(baseDir, foldWorktreeCase), - ) || - isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase); + normalizeForWorktreeMatch(t3Dirs.baseDir, foldWorktreeCase), + ) || isT3ManagedWorktree(candidatePath, t3Dirs.worktreesDir, foldWorktreeCase); + const isExcludedProjectPath = (candidatePath: string, t3Dirs = configuredT3Dirs) => + isScratchPath(candidatePath) || isT3OwnedPath(candidatePath, t3Dirs); const listDirectory = (directory: string) => fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); @@ -1010,7 +1021,7 @@ export const make = Effect.gen(function* () { .realPath(directory) .pipe(Effect.orElseSucceed(() => directory)); // Symlinks can disguise excluded worktree paths; re-check their targets. - return isExcludedProjectPath(realPath) ? Option.none() : stats; + return isExcludedProjectPath(realPath, realT3Dirs) ? Option.none() : stats; }); // Paths whose own read outlived the deadline, mapped to when they may be read @@ -1614,12 +1625,17 @@ export const make = Effect.gen(function* () { }).pipe(Effect.orElseSucceed((): ReadonlyMap> => new Map())); }); - // Only chats left in an excluded folder, such as Codex's scratch folder, take their project's root. - const projectCwd = (cwd: string, projectRoots: ReadonlyArray | undefined) => - projectRoots !== undefined && - isExcludedProjectPath(path.resolve(expandHomePath(cwd.trim(), homeDir))) - ? projectRoots[0]! - : cwd; + // Only chats left in a scratch folder, such as Codex's, take their project's root; T3's own stay excluded. + const projectCwd = Effect.fnUntraced(function* ( + cwd: string, + projectRoots: ReadonlyArray | undefined, + ) { + if (projectRoots === undefined) return cwd; + const resolved = path.resolve(expandHomePath(cwd.trim(), homeDir)); + if (!isScratchPath(resolved) || isT3OwnedPath(resolved)) return cwd; + const realCwd = yield* realPathOf(resolved); + return isT3OwnedPath(realCwd, realT3Dirs) ? cwd : projectRoots[0]!; + }); const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")( function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) { @@ -1788,7 +1804,7 @@ export const make = Effect.gen(function* () { sameTranscriptIdentity(imported.source, transcript.identity), )?.cwd ?? (yield* readCwd(source, transcript, budget)); if (rolloutCwd === null || rolloutCwd === false) continue; - const cwd = projectCwd(rolloutCwd, transcript.projectRoots); + const cwd = yield* projectCwd(rolloutCwd, transcript.projectRoots); const key = `${transcript.providerInstanceId}\0${cwd}`; const existing = byOwnerAndCwd.get(key); if (existing) { @@ -2097,7 +2113,9 @@ export const make = Effect.gen(function* () { ) { const root = path.resolve(expandHomePath(workspaceRoot, homeDir)); const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); - if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty; + if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot, realT3Dirs)) { + return Stream.empty; + } const rootIdentity = yield* directoryIdentity(root); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS; @@ -2283,7 +2301,7 @@ export const make = Effect.gen(function* () { return Option.some({ _tag: "Skipped" }); } const expandedCwd = expandHomePath( - projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), + (yield* projectCwd(snapshot.cwd.value, transcript.projectRoots)).trim(), homeDir, ); if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) { diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 7c0207eed557d..5de818cbeea9d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -194,8 +194,20 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "index.html", ''); + yield* writeTextFile( + cwd, + "index.html", + ` + + + + + +`, + ); yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + yield* writeTextFile(cwd, "public/brand/late.svg", "late"); + yield* writeTextFile(cwd, "public/cdn.example.com/icon.svg", "cdn"); yield* writeTextFile(cwd, "web/favicon.png", "flutter"); const resolved = yield* resolver.resolvePath(cwd); @@ -203,6 +215,15 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(resolved).not.toBeNull(); expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); + // A cached icon whose `public` folder became a file falls back instead of failing. + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "public"), { + recursive: true, + }); + yield* writeTextFile(cwd, "public", "not a folder"); + expect(yield* resolver.resolvePath(cwd)).toBe( + (yield* Path.Path).join(cwd, "web", "favicon.png"), + ); + const flutterCwd = yield* makeTempDir; yield* writeTextFile(flutterCwd, "web/favicon.png", "flutter"); expect(yield* resolver.resolvePath(flutterCwd)).toBe( @@ -284,7 +305,8 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { head: () => ({ links: [ { rel: "stylesheet", href: "/app.css" }, - { rel: "icon shortcut", href: "/brand/logo.svg" }, + { rel: "icon", href: "https://cdn.example.com/icon.svg" }, + { rel: "icon shortcut", href: "/brand/logo.svg#mark" }, ], }), });`, diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 12c8e2fc63ea2..85930064d033d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -83,7 +83,7 @@ const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])| const HTML_ATTRIBUTE_RE = /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g; const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); -const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; +const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?#]+)/i; export class ProjectFaviconResolutionError extends Schema.TaggedError()( "ProjectFaviconResolutionError", @@ -122,7 +122,7 @@ export class ProjectFaviconResolver extends Context.Service< } >()("t3/project/ProjectFaviconResolver") {} -function extractIconHref(source: string): string | null { +function* extractIconHrefs(source: string): Generator { for (const [tag] of source.matchAll(HTML_LINK_RE)) { const attributes = new Map(); for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag @@ -144,15 +144,14 @@ function extractIconHref(source: string): string | null { const href = attributes.get("href"); // An unquoted `{...}` is a JSX expression, not a path. if (!href || (!href.quoted && href.value.startsWith("{"))) continue; - const path = href.value.split("?")[0]; - if (path) return path; + const path = href.value.split(/[?#]/, 1)[0]; + if (path) yield path; } for (const run of source.split("}")) { if (!ICON_REL_RE.test(run)) continue; const hrefMatch = run.match(ICON_HREF_RE); - if (hrefMatch?.[1]) return hrefMatch[1]; + if (hrefMatch?.[1]) yield hrefMatch[1]; } - return null; } export const optionOnNotFound = ( @@ -166,6 +165,17 @@ export const optionOnNotFound = ( }), ); +// A path through a file (ENOTDIR) or a symlink loop names no file either. +const optionOnMissing = ( + effect: Effect.Effect, +): Effect.Effect, PlatformError.PlatformError, R> => + optionOnNotFound(effect).pipe( + Effect.catchIf( + (error) => error.reason._tag === "BadResource", + () => Effect.succeedNone, + ), + ); + export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -173,6 +183,8 @@ export const make = Effect.gen(function* () { const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader; const resolveIconHref = (href: string): ReadonlyArray => { + // `data:`, `https:` and `//host` icons name no project file, and a long data URL fails `stat`. + if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href.trim())) return []; // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs. const clean = href.trim().replace(/^\//, ""); return [path.join("public", clean), clean]; @@ -203,7 +215,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(candidate)) { continue; } - const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(candidate.value.absolutePath)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -242,7 +254,7 @@ export const make = Effect.gen(function* () { }), ), ); - const stats = yield* optionOnNotFound(fileSystem.stat(sourcePath.absolutePath)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(sourcePath.absolutePath)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -257,7 +269,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(stats) || stats.value.type !== "File") { return null; } - const source = yield* optionOnNotFound( + const source = yield* optionOnMissing( fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe( Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)), Effect.scoped, @@ -277,11 +289,8 @@ export const make = Effect.gen(function* () { if (Option.isNone(source) || Option.isNone(source.value)) { return null; } - const href = extractIconHref(new TextDecoder().decode(source.value.value)); - if (!href) { - return null; - } - return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace"); + const hrefs = Array.from(extractIconHrefs(new TextDecoder().decode(source.value.value))); + return yield* findExistingFile(projectCwd, hrefs.flatMap(resolveIconHref), "workspace"); }); // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit. @@ -377,7 +386,7 @@ export const make = Effect.gen(function* () { return null; } - const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(cached)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ diff --git a/apps/server/src/project/ProjectService.test.ts b/apps/server/src/project/ProjectService.test.ts index dc93ee64dbfcd..1e741ad8b051f 100644 --- a/apps/server/src/project/ProjectService.test.ts +++ b/apps/server/src/project/ProjectService.test.ts @@ -581,6 +581,59 @@ it.layer(layerTest)("ProjectService", (it) => { }), ); + it.effect("saves a project's actions where Settings reads them", () => + Effect.gen(function* () { + const service = yield* ProjectService.ProjectService; + const settings = yield* ServerSettings.ServerSettingsService; + const projectId = ProjectId.make("project:actions"); + const script = { + id: "likec4-start", + name: "LikeC4 podgląd", + command: "npx -y likec4@latest start", + icon: "play" as const, + runOnWorktreeCreate: false, + }; + yield* service.create({ + commandId: CommandId.make("command:actions:create"), + projectId, + title: "Actions", + workspaceRoot: "/work/actions", + scripts: [script], + }); + assert.deepEqual( + (yield* settings.getSettings).projectSettingsOverrides[projectId]?.defaultProjectScripts, + [script], + ); + yield* settings.updateSettings({ + projectSettingsOverrides: { + [projectId]: { defaultProjectScripts: [script], defaultThreadEnvMode: "worktree" }, + }, + }); + yield* service.update({ + commandId: CommandId.make("command:actions:update"), + projectId, + scripts: [], + }); + assert.deepEqual((yield* settings.getSettings).projectSettingsOverrides[projectId], { + defaultProjectScripts: [], + defaultThreadEnvMode: "worktree", + }); + // A retried command must not put its old actions back over a later edit. + yield* settings.updateSettings({ + projectSettingsOverrides: { [projectId]: { defaultProjectScripts: [script] } }, + }); + yield* service.update({ + commandId: CommandId.make("command:actions:update"), + projectId, + scripts: [], + }); + assert.deepEqual( + (yield* settings.getSettings).projectSettingsOverrides[projectId]?.defaultProjectScripts, + [script], + ); + }), + ); + it.effect("rejects a workspace another active project holds", () => Effect.gen(function* () { const service = yield* ProjectService.ProjectService; diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.ts index 80fabe6101c05..c1fec5fde3e9f 100644 --- a/apps/server/src/project/ProjectService.ts +++ b/apps/server/src/project/ProjectService.ts @@ -391,6 +391,9 @@ export const make = Effect.gen(function* () { refine?: ( current: ProjectStore.ProjectRow | undefined, ) => Effect.Effect, + // Runs under the same lock only when this call commits, so retries skip it and writes keep + // the commit order. + onCommitted?: Effect.Effect, ) { const { projectId } = initial; const dispatchError = (cause: unknown) => @@ -424,13 +427,14 @@ export const make = Effect.gen(function* () { now, }); if (Result.isSuccess(planned)) { - const { receipt } = yield* eventSink.commitProjectCommand({ + const { receipt, committed } = yield* eventSink.commitProjectCommand({ commandId: command.commandId, projectId, commandType: command.type, acceptedAt: now, event: planned.success, }); + if (committed && onCommitted !== undefined) yield* onCommitted; return { receipt }; } const receipt = yield* eventSink.commitRejectedProjectCommand({ @@ -534,6 +538,33 @@ export const make = Effect.gen(function* () { return Option.isNone(row) ? Option.none() : Option.some(yield* hydrate(row.value)); }); + // Once project settings are folded, actions resolve from Settings only, where the app's editor saves them. + const saveScripts = (projectId: ProjectId, scripts: ProjectCreateInput["scripts"]) => + scripts === undefined + ? Effect.void + : serverSettings.getSettings.pipe( + // A patch replaces the project's whole entry, so its other overrides are carried over. + Effect.flatMap(({ projectSettingsOverrides }) => + serverSettings.updateSettings({ + projectSettingsOverrides: { + [projectId]: { + ...projectSettingsOverrides[projectId], + defaultProjectScripts: scripts, + }, + }, + }), + ), + Effect.asVoid, + Effect.mapError( + (cause) => + new ProjectOperationError({ + operation: "dispatch-project-command", + projectId, + cause, + }), + ), + ); + const create: ProjectService["Service"]["create"] = Effect.fn("ProjectService.create")( function* (input) { yield* rejectWslSharePath(input.projectId, input.workspaceRoot); @@ -548,15 +579,19 @@ export const make = Effect.gen(function* () { workspaceRoot, input.trackedFolders ?? [], ); - yield* commit({ - type: "project.create", - commandId: input.commandId, - projectId: input.projectId, - title: input.title, - workspaceRoot, - ...(input.scripts === undefined ? {} : { scripts: input.scripts }), - trackedFolders, - }); + yield* commit( + { + type: "project.create", + commandId: input.commandId, + projectId: input.projectId, + title: input.title, + workspaceRoot, + ...(input.scripts === undefined ? {} : { scripts: input.scripts }), + trackedFolders, + }, + undefined, + saveScripts(input.projectId, input.scripts), + ); yield* projectEnrichment.invalidate([workspaceRoot]); return yield* readCommitted(input.projectId); }, @@ -639,6 +674,7 @@ export const make = Effect.gen(function* () { ); return { ...command, trackedFolders }; }), + saveScripts(input.projectId, input.scripts), ); if (workspaceRoot !== previousRoot || input.faviconPath !== undefined) { yield* projectEnrichment.invalidate([previousRoot, workspaceRoot]); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index aa717131c201c..5b015e574643d 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -230,6 +230,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { ); yield* fileSystem.makeDirectory(path.join(root, ".not-a-skill")); yield* fileSystem.writeFileString(path.join(root, "README.md"), "Not a skill."); + yield* fileSystem.writeFileString(path.join(root, "SKILL.MD"), "---\nname: uppercase\n---\n"); const skillPath = yield* writeSkill( path.join(root, ".native-hidden-skill"), "---\nname: native-name\ndescription: >\n Review the code\n and run tests.\n---\n", @@ -405,6 +406,9 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { "---\nname: release\n---\n", ); yield* writeSkill(path.join(projectSkills, "excluded"), "---\nname: excluded-root\n---\n"); + const explicitRoot = path.join(projectSkills, "explicit"); + yield* writeSkill(path.join(explicitRoot, "child"), "---\nname: not-discovered\n---\n"); + yield* fileSystem.writeFileString(path.join(explicitRoot, "SKILL.MD"), "---\n---\n"); // agy does not expand ~, so a ~/ entry loads nothing. yield* writeSkill( @@ -450,6 +454,7 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { { path: "tools/skills/public", include_only: ["public"] }, { path: "tools/skills/excluded", exclude: ["excluded"] }, { path: "tools/skills/excluded", include_only: ["public"] }, + { path: "tools/skills/explicit" }, ], }), ); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 28c5d4f34d09c..d7c551c7e9198 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -243,8 +243,8 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( { directory: configSkills, scope: "user" }, { directory: path.resolve(input.cwd, ".gemini", "skills"), scope: "project" }, { directory: cliSkills, scope: "user" }, - { directory: path.resolve(input.cwd, ".agents", "skills"), scope: "project" }, - { directory: path.resolve(input.cwd, ".agent", "skills"), scope: "project" }, + { directory: path.resolve(input.cwd, ".agents", "skills"), scope: "project", agentRoot: true }, + { directory: path.resolve(input.cwd, ".agent", "skills"), scope: "project", agentRoot: true }, ]; const budget: ScanBudget = { remainingBytes: MAX_SCAN_BYTES, @@ -273,12 +273,11 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( const scanDirectory = Effect.fn("scanAntigravitySkillDirectory")(function* ( directory: string, scope: string, - scanChildren: boolean, + mode: "directory" | "agent-root" | "child" | "manifest", filter: SkillEntryFilter = EMPTY_SKILL_FILTER, - acceptSkillFile = false, ): Effect.fn.Return { const info = yield* readIfPresent(fileSystem.stat(directory), directory); - if (info?.type === "File" && acceptSkillFile) { + if (info?.type === "File" && mode === "manifest") { if (budget.remainingEntries === 0) { return yield* new AntigravitySkillsProbeError({ reason: "scan-budget-exhausted", @@ -304,13 +303,13 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( const sortedEntries = entries.toSorted(); const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md"); - if (skillFileName !== undefined) { + if (skillFileName !== undefined && (mode !== "agent-root" || skillFileName.endsWith(".md"))) { if (matchesSkillFilter(path.basename(directory), filter)) { yield* addSkillFile(path.join(directory, skillFileName), scope); } return; } - if (scanChildren) { + if (mode !== "child") { const children = sortedEntries .filter((entry) => matchesSkillFilter(entry, filter)) .map((entry) => ({ entry, sortKey: skillPathSortKey(entry) })) @@ -318,7 +317,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( left.sortKey < right.sortKey ? -1 : left.sortKey > right.sortKey ? 1 : 0, ); for (const { entry } of children) { - yield* scanDirectory(path.join(directory, entry), scope, false); + yield* scanDirectory(path.join(directory, entry), scope, "child"); } } }); @@ -370,12 +369,12 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( } for (const entry of parsed.value.entries ?? []) { const entryDirectory = resolveSkillsConfigPath(path, entry.path, baseDir); - yield* scanDirectory(entryDirectory, scope, true, narrowSkillFilter(filter, entry), true); + yield* scanDirectory(entryDirectory, scope, "manifest", narrowSkillFilter(filter, entry)); } }); for (const root of roots) { - yield* scanDirectory(root.directory, root.scope, true); + yield* scanDirectory(root.directory, root.scope, root.agentRoot ? "agent-root" : "directory"); } for (const config of [ @@ -434,7 +433,7 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")( const pluginDirectory = path.join(pluginsDirectory, plugin); const info = yield* readIfPresent(fileSystem.stat(pluginDirectory), pluginDirectory); if (info?.type !== "Directory") continue; - yield* scanDirectory(path.join(pluginDirectory, "skills"), "user", true); + yield* scanDirectory(path.join(pluginDirectory, "skills"), "user", "directory"); } } return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name)); diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 26f4f6719e9c4..4089b32f80569 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 61709 + "mcpToolListJsonBytes": 61844 } diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index fa608d634a384..bdf74046def6d 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -876,7 +876,7 @@ describe("providerMaintenanceRunner", () => { // binary behind that later updates mistake for an install. it.effect.each([ { runFor: "6 minutes", status: "succeeded", message: "Provider updated." }, - { runFor: "31 minutes", status: "failed", message: "Update timed out after 30 minutes." }, + { runFor: "2 hours", status: "succeeded", message: "Provider updated." }, ] as const)("lets a slow installer run for $runFor", ({ runFor, status, message }) => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { @@ -1273,6 +1273,69 @@ describe("providerMaintenanceRunner", () => { }), ); + // npm moves the working package and its bin shims aside before it downloads + // the new version; a forced kill then (taskkill /F on Windows) leaves no CLI. + it.effect("does not force-kill an npm global update still running at the timeout", () => + Effect.gen(function* () { + const kills: Array = []; + let spawns = 0; + const spawned = yield* Deferred.make(); + const respawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed((spawns += 1) === 1 ? spawned : respawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); + + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner(registry); + yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(spawned); + yield* TestClock.adjust("31 minutes"); + + assert.deepStrictEqual( + kills, + [], + "the update timeout force-killed npm while it was replacing the installed CLI", + ); + // npm is still replacing the install, so a retry must not start a second installer. + yield* Effect.yieldNow.pipe(Effect.repeat({ times: 20 })); + const retry = yield* Effect.raceFirst( + updater.updateProvider(OPENCODE_DRIVER).pipe( + Effect.flip, + Effect.map((error) => error.reason), + ), + Deferred.await(respawned).pipe(Effect.as("a second installer started")), + ); + assert.include(retry, "already running"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("9.9.9"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ), + ); + }), + ); + it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { const captured: Array<{ readonly command: string; diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index a09bf1ee7dbba..4fb57bb08d3d0 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -15,7 +15,6 @@ import * as Duration from "effect/Duration"; 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 Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; @@ -41,11 +40,6 @@ import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/ser import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); -// Native updaters (`claude update`) download a ~300 MB binary without printing -// progress, and killing one mid-download leaves a truncated binary that the -// next run treats as installed. Allow a slow connection to finish. -const UPDATE_TIMEOUT_MINUTES = 30; -const UPDATE_TIMEOUT_MS = UPDATE_TIMEOUT_MINUTES * 60_000; const UPDATE_OUTPUT_MAX_BYTES = 10_000; // Sample installer output because every progress update resends the provider list to all clients. const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1); @@ -57,7 +51,6 @@ export interface ProviderMaintenanceCommandResult { readonly stdout: string; readonly stderr: string; readonly exitCode: number | null; - readonly timedOut: boolean; readonly stdoutTruncated: boolean; readonly stderrTruncated: boolean; } @@ -194,31 +187,16 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR stdout: stdout.text, stderr: stderr.text, exitCode: Number(exitCode), - timedOut: false, stdoutTruncated: stdout.truncated, stderrTruncated: stderr.truncated, } satisfies ProviderMaintenanceCommandResult; }, ); - return yield* collectCommandResult().pipe( - Effect.scoped, - Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)), - Effect.map((result) => - Option.match(result, { - onSome: (value) => value, - onNone: () => - ({ - stdout: "", - stderr: "", - exitCode: null, - timedOut: true, - stdoutTruncated: false, - stderrTruncated: false, - }) satisfies ProviderMaintenanceCommandResult, - }), - ), - ); + // No timeout: killing an installer mid-install leaves the provider half-replaced (npm has moved + // the old package and its shims aside; `claude update` leaves a truncated binary), and an + // installer still running must keep the update's locks until it exits. + return yield* collectCommandResult().pipe(Effect.scoped); }, ); @@ -282,9 +260,6 @@ function failureReason(result: ProviderMaintenanceCommandResult): string | null } function failureMessage(result: ProviderMaintenanceCommandResult): string { - if (result.timedOut) { - return `Update timed out after ${UPDATE_TIMEOUT_MINUTES} minutes.`; - } const summary = result.exitCode !== null && result.exitCode !== 0 ? `Update command exited with code ${result.exitCode}` @@ -594,12 +569,11 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ), ); const finishedAt = yield* nowIso; - if (result.timedOut || result.exitCode !== 0) { + if (result.exitCode !== 0) { yield* Effect.logWarning("Provider update command failed", { provider, command: describeCommand(command), exitCode: result.exitCode, - timedOut: result.timedOut, output: commandOutput(result), }); return yield* finish( diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index c62d74f186553..61565f3a5e0a1 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3411,6 +3411,38 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.effect("removes an eligible worktree whose ignored files take over 30 seconds to walk", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fs = yield* FileSystem.FileSystem; + const walking = yield* Deferred.make(); + let slowPath: string | undefined; + // Stands in for a flat Bun or npm node_modules with hundreds of thousands of files. + const fixture = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + lstat: (target) => + Effect.gen(function* () { + if (target === slowPath) { + yield* Deferred.succeed(walking, undefined); + yield* Effect.sleep("31 seconds"); + } + return yield* fs.lstat(target); + }), + }), + ); + yield* fs.makeDirectory(`${fixture.worktree}/node_modules/pkg`, { recursive: true }); + yield* fs.writeFileString(`${fixture.worktree}/node_modules/pkg/index.js`, "export {};\n"); + slowPath = `${yield* fs.realPath(fixture.worktree)}/node_modules`; + const run = yield* fixture.service.runNow.pipe(Effect.forkChild); + yield* Deferred.await(walking); + yield* TestClock.adjust("31 seconds"); + expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ outcome: "removed" }); + expect(yield* fs.exists(fixture.worktree)).toBe(false); + }), + ), + ); it.effect("removes a worktree owned by a repository other than the project root", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 451df614f8184..d091c9d11228d 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -515,9 +515,19 @@ const make = Effect.gen(function* () { } return { bytes, reason: null }; }, - Effect.timeout("30 seconds"), + // No time limit: the entry cap bounds the walk, and a removal that timed out would + // repeat the whole walk on every sweep without ever deleting the worktree. Effect.orElseSucceed(() => ({ bytes: null, reason: "worktree could not be fully inspected" })), ); + // For walks under a workspace lease, which provider startup waits on, or repeated under one. + const measureWorktreeBounded = (...args: Parameters) => + measureWorktree(...args).pipe( + Effect.timeoutOrElse({ + duration: "30 seconds", + orElse: () => + Effect.succeed({ bytes: null, reason: "worktree could not be fully inspected" }), + }), + ); // Large snapshots take seconds; use the reader worker instead of blocking the event loop. const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () { @@ -682,9 +692,9 @@ const make = Effect.gen(function* () { if (orphanSizes.has(key)) continue; const remaining = measurementDeadline - (yield* Clock.currentTimeMillis); if (!firstMeasurement && remaining <= 0) break; - const measured = yield* measureWorktree(path).pipe( - firstMeasurement ? Effect.asSome : Effect.timeoutOption(remaining), - ); + const measured = yield* firstMeasurement + ? measureWorktreeBounded(path).pipe(Effect.asSome) + : measureWorktree(path).pipe(Effect.timeoutOption(remaining)); firstMeasurement = false; if (Option.isSome(measured)) orphanSizes.set(key, measured.value.bytes); } @@ -1282,7 +1292,7 @@ const make = Effect.gen(function* () { ((yield* branchChanged(checkoutPath, branch)) ? "repository or branch changed" : null) ?? (yield* localChangesReason(checkoutPath, rules)); if (reason !== null) return { keep: reason, force: false, bytes: null }; - const { bytes, reason: measureReason } = yield* measureWorktree(checkoutPath, true); + const { bytes, reason: measureReason } = yield* measureWorktreeBounded(checkoutPath, true); if (measureReason !== null) return { keep: measureReason, force: false, bytes }; // Measuring takes time, and what follows deletes ignored files under these rules. if (yield* settingsChanged) @@ -1616,13 +1626,13 @@ const make = Effect.gen(function* () { (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? (yield* blockedSinceCheck()); if (blocked !== null) return keep(blocked); - const inspection = yield* measureWorktree(worktreePath, "plain-folder"); + const inspection = yield* measureWorktreeBounded(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"); + const finalInspection = yield* measureWorktreeBounded(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 = diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index f6284cc52c914..19c2fdd749f5e 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -1205,6 +1205,45 @@ it.layer( }).pipe(Effect.provide(TestClock.layer())), ); + it.effect("backs off polling a steady command and still sees it exit within five seconds", () => + Effect.gen(function* () { + const shell = { pid: 9000, ppid: 1, name: "zsh" }; + let table = [shell, { pid: 200, ppid: 9000, name: "node" }]; + let queries = 0; + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + subprocessPollIntervalMs: 1_000, + processKillGraceMs: 0, + processTable: Effect.sync(() => { + queries += 1; + return table; + }), + }).pipe(Effect.provide(layerWithHostPlatform("linux"))); + const activity = Effect.map(getEvents, (events) => + events.flatMap((event) => + event.type === "activity" ? [event.hasRunningSubprocess ? event.label : null] : [], + ), + ); + yield* manager.open(openInput()); + + yield* TestClock.adjust("10 minutes"); + expect(yield* activity).toEqual(["node"]); + expect(queries).toBeGreaterThanOrEqual(115); + expect(queries).toBeLessThanOrEqual(125); + + table = [...table, { pid: 201, ppid: 200, name: "esbuild" }]; + ptyAdapter.processes[0]!.emitData("rebuilt\r\n"); + queries = 0; + yield* TestClock.adjust("1 second"); + expect(queries).toBe(1); + + yield* TestClock.adjust("1 minute"); + table = [shell]; + yield* TestClock.adjust("5 seconds"); + expect(yield* activity).toEqual(["node", null]); + yield* manager.close({ threadId: "thread-1" }); + }).pipe(Effect.provide(TestClock.layer())), + ); + // Answers process-table queries after `queryDuration`, honoring the caller's // timeout the way ProcessRunner's `timedOutResult` mode does. const slowProcessTable = ( diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 968cbf4b3f78a..8f25dbcc4d727 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -113,6 +113,8 @@ const PROCESS_TABLE_QUERY_TIMEOUT = "15 seconds"; const CLOSE_IDLE_QUERY_TIMEOUT = { posix: "1 second", win32: "1500 millis" } as const; // Discover children started without terminal input or output. const QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 30; +// Bounds how late a steady command's silent exit or new child is seen. +const STEADY_SUBPROCESS_SNAPSHOT_EVERY_TICKS = 5; const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000; const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128; const DEFAULT_OPEN_COLS = 120; @@ -506,6 +508,7 @@ function terminalActivityMark(session: TerminalSessionState): number { interface QuietTerminalSession { readonly process: PtyAdapter.PtyProcess | null; readonly mark: number; + readonly processKey: string | null; readonly idleSnapshots: number; } @@ -3084,15 +3087,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func // Process identity prevents a restarted shell from inheriting quiet state. let quietSessions = new WeakMap(); let skippedQuietTicks = 0; - const isQuiet = (session: TerminalSessionState & { pid: number }) => { + const quietSnapshotEveryTicks = (session: TerminalSessionState & { pid: number }) => { const quiet = quietSessions.get(session); - return ( - quiet !== undefined && - quiet.idleSnapshots === 2 && - quiet.process === session.process && - quiet.mark === terminalActivityMark(session) && - !session.hasRunningSubprocess - ); + if ( + quiet === undefined || + quiet.idleSnapshots < 2 || + quiet.process !== session.process || + quiet.mark !== terminalActivityMark(session) + ) { + return 1; + } + return quiet.processKey === null + ? QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS + : STEADY_SUBPROCESS_SNAPSHOT_EVERY_TICKS; }; const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { @@ -3112,10 +3119,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func if (runningSessions.length === 0) { return { snapshotSucceeded: true, queryElapsedMs: 0 }; } - if ( - runningSessions.every(({ session }) => isQuiet(session)) && - skippedQuietTicks < QUIET_SUBPROCESS_SNAPSHOT_EVERY_TICKS - 1 - ) { + const snapshotEveryTicks = Math.min( + ...runningSessions.map(({ session }) => quietSnapshotEveryTicks(session)), + ); + if (skippedQuietTicks < snapshotEveryTicks - 1) { skippedQuietTicks += 1; return { snapshotSucceeded: true, queryElapsedMs: 0 }; } @@ -3207,9 +3214,11 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func yield* publishEvent(event.value); } + const processKey = next.hasRunningSubprocess + ? `${nextChildLabel}:${next.processIds.toSorted((a, b) => a - b).join(",")}` + : null; if ( snapshotSucceeded && - !next.hasRunningSubprocess && session.status === "running" && session.pid === terminalPid && session.process === process && @@ -3218,7 +3227,13 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func quietSessions.set(session, { process, mark, - idleSnapshots: previous?.process === process && previous.mark === mark ? 2 : 1, + processKey, + idleSnapshots: + previous?.process === process && + previous.mark === mark && + previous.processKey === processKey + ? 2 + : 1, }); } }); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 1ae6c7dfb0883..29484e835fed7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -609,6 +609,43 @@ it.effect.each([ ).pipe(Effect.provide(layerTest)), ); +it.effect("marks the default branch of a primary remote that is not named origin", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["branch", "-M", "trunk"]); + yield* git(cwd, ["remote", "add", "upstream", remote]); + yield* git(cwd, ["push", "upstream", "trunk"]); + yield* git(cwd, [ + "symbolic-ref", + "refs/remotes/upstream/HEAD", + "refs/remotes/upstream/trunk", + ]); + yield* git(cwd, ["checkout", "-b", "other"]); + // "other" sorts ahead of "trunk" by name when their commit times tie. + yield* git(cwd, ["commit", "--allow-empty", "-m", "newer"]); + yield* git(cwd, ["checkout", "-b", "feature", "trunk"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const status = yield* driver.statusDetailsLocal(cwd); + yield* git(cwd, ["checkout", "trunk"]); + assert.isTrue((yield* driver.statusDetailsLocal(cwd)).isDefaultBranch); + yield* git(cwd, ["checkout", "feature"]); + assert.isFalse(status.isDefaultBranch); + + const refs = (yield* driver.listRefs({ cwd, refresh: true, includeMatchingRemoteRefs: true })) + .refs; + assert.isTrue(refs.find((ref) => ref.name === "trunk")?.isDefault); + assert.isTrue(refs.find((ref) => ref.name === "upstream/trunk")?.isDefault); + const names = refs.map((ref) => ref.name); + assert.isBelow(names.indexOf("trunk"), names.indexOf("other")); + }), + ).pipe(Effect.provide(layerTest)), +); + it.effect.each(["branch", "detached", "nested", "aliased-root", "aliased-nested"] as const)( "discovers only the common directory during worktree creation from %s", (location) => @@ -6939,6 +6976,50 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "tracks the real branch name and refuses local collisions for remotes containing slashes", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const slashedRemote = yield* makeTmpDir("git-remote-slashed-"); + yield* git(slashedRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "team/origin", slashedRemote]); + yield* git(cwd, ["push", "team/origin", "HEAD:refs/heads/feature/demo"]); + yield* git(cwd, ["push", "team/origin", "HEAD:refs/heads/conflict"]); + yield* git(cwd, ["fetch", "team/origin"]); + + const driver = yield* GitVcsDriver.GitVcsDriver; + const switched = yield* driver.switchRef({ cwd, refName: "team/origin/feature/demo" }); + + assert.equal(switched.refName, "feature/demo"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/demo"); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(upstream)", "refs/heads/feature/demo"]), + "refs/remotes/team/origin/feature/demo", + ); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(refname)", "refs/heads/origin"]), + "", + ); + + yield* git(cwd, ["checkout", "--no-track", "-b", "conflict"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "Local conflict work"]); + yield* git(cwd, ["checkout", initialBranch]); + + const conflicted = yield* driver + .switchRef({ cwd, refName: "team/origin/conflict" }) + .pipe(Effect.flip); + + assert.equal(conflicted.reason, "branch_already_exists"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(refname)", "refs/heads/origin"]), + "", + ); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 82263ad70383f..5fcddc70e144a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -5443,6 +5443,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { concurrency: 2 }, ); + const remoteNamesInGitOrder = + remoteNamesResult.exitCode === 0 ? parseRemoteNamesInGitOrder(remoteNamesResult.stdout) : []; const remoteNames = remoteNamesResult.exitCode === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; if (remoteNamesResult.exitCode !== 0 && remoteNamesResult.stderr.trim().length > 0) { @@ -5450,10 +5452,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* `GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.exitCode} for ${gitCommonDir}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, ); } - const defaultBranch = + const originDefaultBranch = defaultRefResult.exitCode === 0 ? parseDefaultBranchFromRemoteHeadRef(defaultRefResult.stdout, "origin") : null; + // Same fallback as resolvePrimaryDefaultBranchName: without an origin, the first remote is primary. + const [firstRemoteName] = remoteNamesInGitOrder; + const fallbackRemoteName = + originDefaultBranch === null && + firstRemoteName !== undefined && + !remoteNamesInGitOrder.includes("origin") + ? firstRemoteName + : null; + const defaultBranch = + fallbackRemoteName === null + ? originDefaultBranch + : yield* resolveDefaultBranchName(fetchCwd, fallbackRemoteName, gitDirArgs); + const defaultRemoteName = fallbackRemoteName ?? "origin"; const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = []; @@ -5489,7 +5504,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* isRemote: true, isDefault: defaultBranch !== null && - parsedRemoteRef?.remoteName === "origin" && + parsedRemoteRef?.remoteName === defaultRemoteName && parsedRemoteRef.branchName === defaultBranch, worktreePath: null, ...(parsedRemoteRef ? { remoteName: parsedRemoteRef.remoteName } : {}), @@ -6887,9 +6902,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) : null; - const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.refName); + const localTrackedBranchCandidate = + remoteExists && !localInputExists && !localTrackingBranch + ? yield* executeGit("GitVcsDriver.switchRef.remoteNames", input.cwd, ["remote"], { + timeoutMs: 5_000, + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => { + const remoteNames = result.exitCode === 0 ? parseRemoteNames(result.stdout) : []; + return ( + parseRemoteRefWithRemoteNames(input.refName, remoteNames)?.branchName ?? + deriveLocalBranchNameFromRemoteRef(input.refName) + ); + }), + ) + : null; const localTrackedBranchTargetExists = - remoteExists && !localInputExists && !localTrackingBranch && localTrackedBranchCandidate + localTrackedBranchCandidate !== null ? yield* executeGit( "GitVcsDriver.switchRef.localTrackedBranchTargetExists", input.cwd, @@ -6902,7 +6931,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : false; const newTrackingBranch = - !localInputExists && remoteExists && !localTrackingBranch && !localTrackedBranchTargetExists + localTrackedBranchCandidate !== null && !localTrackedBranchTargetExists ? localTrackedBranchCandidate : null; @@ -6911,7 +6940,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : newTrackingBranch ? ["checkout", newTrackingBranch] : remoteExists && !localTrackingBranch - ? ["checkout", "--track", input.refName] + ? localTrackedBranchCandidate + ? [ + "checkout", + "--track", + "-b", + localTrackedBranchCandidate, + `refs/remotes/${input.refName}`, + ] + : ["checkout", "--track", input.refName] : remoteExists && localTrackingBranch ? ["checkout", localTrackingBranch] : ["checkout", input.refName]; diff --git a/apps/server/src/workspace/WorkspaceFolders.test.ts b/apps/server/src/workspace/WorkspaceFolders.test.ts index 3a02d202be891..6cd9e7c4ee0d1 100644 --- a/apps/server/src/workspace/WorkspaceFolders.test.ts +++ b/apps/server/src/workspace/WorkspaceFolders.test.ts @@ -61,8 +61,15 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { const tmp = yield* makeTempDir; const root = path.join(tmp, "wrapper"); const outside = path.join(tmp, "outside"); + // Labels are cut at 128 UTF-16 units; an emoji across the cut is left out whole. + const cut = `${"a".repeat(127)}🚀`; + const fits = `${"b".repeat(126)}🚀`; + const padded = `${" ".repeat(127)}🚀`; for (const folder of [ ".git", + `${cut}/.git`, + `${fits}/.git`, + `${padded}/.git`, "api/.git", "web/.git", "sub/.git", @@ -121,6 +128,14 @@ it.layer(NodeServices.layer)("WorkspaceFolders", (it) => { source: "code-workspace", }, { path: outside, name: "outside", isGitRepository: true, source: "code-workspace" }, + { path: path.join(root, padded), name: "🚀", isGitRepository: true, source: "child" }, + { + path: path.join(root, cut), + name: "a".repeat(127), + isGitRepository: true, + source: "child", + }, + { path: path.join(root, fits), name: fits, isGitRepository: true, source: "child" }, // One level below a plain folder is looked into. { path: path.join(root, "src", "svc"), diff --git a/apps/server/src/workspace/WorkspaceFolders.ts b/apps/server/src/workspace/WorkspaceFolders.ts index 0824c647ce360..ca4764b83c7fa 100644 --- a/apps/server/src/workspace/WorkspaceFolders.ts +++ b/apps/server/src/workspace/WorkspaceFolders.ts @@ -11,6 +11,7 @@ import { type WorkspaceScanFoldersResult, } from "@t3tools/contracts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { fromLenientJson } from "@t3tools/shared/schemaJson"; import { T3_PROJECT_FILE_NAME } from "@t3tools/contracts"; @@ -79,7 +80,11 @@ export class WorkspaceFolders extends Context.Service< const DETECTION_CONCURRENCY = 8; // What `ProjectTrackedFolder.name` allows. const FOLDER_NAME_MAX = 128; -const boundedName = (name: string) => name.slice(0, FOLDER_NAME_MAX).trim(); +const boundedName = (name: string) => { + const trimmed = name.trimStart(); + const end = splitsSurrogatePair(trimmed, FOLDER_NAME_MAX) ? FOLDER_NAME_MAX - 1 : FOLDER_NAME_MAX; + return trimmed.slice(0, end).trimEnd(); +}; const CODE_WORKSPACE_EXTENSION = ".code-workspace"; const decodeCodeWorkspace = Schema.decodeUnknownEffect( diff --git a/apps/web/src/components/AppRouteModal.browser.test.tsx b/apps/web/src/components/AppRouteModal.browser.test.tsx index 814cb87f946b0..429e76b3bab69 100644 --- a/apps/web/src/components/AppRouteModal.browser.test.tsx +++ b/apps/web/src/components/AppRouteModal.browser.test.tsx @@ -1,3 +1,4 @@ +import { redirect, useLocation } from "@tanstack/react-router"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -27,6 +28,33 @@ describe("AppRouteModal", () => { expect(onCommit).toHaveBeenCalledWith("Keep titles short"); }); + // regression: #42075. Navigation: Back (mod+[) leaves the Settings route without closing the dialog. + it("commits a focused field when the route goes back", async () => { + const onCommit = vi.fn(); + function SettingsRoute() { + const pathname = useLocation({ select: (location) => location.pathname }); + return pathname.startsWith("/settings") ? ( + + + + ) : null; + } + await using screen = await render(, { router: "/" }); + // The app redirects /settings, and the router skips onBeforeNavigate after a redirect. + screen.router!.routeTree.update({ + beforeLoad: ({ location }: { location: { pathname: string } }) => { + if (location.pathname === "/settings") throw redirect({ to: "/settings/general" }); + }, + }); + await screen.router!.navigate({ to: "/settings" }); + + await page.getByRole("textbox", { name: "Instructions" }).fill("Keep titles short"); + screen.router!.history.back(); + + await expect.element(page.getByRole("dialog", { name: "Settings" })).not.toBeInTheDocument(); + expect(onCommit).toHaveBeenCalledWith("Keep titles short"); + }); + it("returns focus to the opener when Esc closes it", async () => { const opener = ; await using screen = await render(opener, { router: "/" }); diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 1414b198afdc4..95effddf3698c 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -1,7 +1,8 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; -import { useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { useRouter } from "@tanstack/react-router"; +import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { getCommandPaletteOpener } from "../commandPaletteStore"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; @@ -35,6 +36,22 @@ export function AppRouteModal({ label, children }: { label: string; children: Re // buttons). Below sm the modal fills the window and leaves that strip empty; up to lg its // 1.5rem inset is shorter than the strip. const nativeTitlebarHeight = useNativeTitlebarHeight(); + const router = useRouter(); + // Leaving the page without closing (Navigation: Back) unmounts a focused field during a + // commit, when React no longer delivers its blur, so commit-on-blur rows would drop what was + // typed. Blur text fields before the navigation renders; other controls keep their focus. + // Not onBeforeNavigate: the router skips it while a past redirect is still recorded. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- router listener that blurs a field before navigation unmounts it + useEffect( + () => + router.subscribe("onBeforeLoad", ({ pathChanged }) => { + const focused = document.activeElement; + if (pathChanged && focused?.matches("input, textarea, [contenteditable]")) { + blurFocusedWithin(popupRef.current); + } + }), + [router], + ); return ( { @@ -116,6 +132,11 @@ export function AppRouteModal({ label, children }: { label: string; children: Re ); } +function blurFocusedWithin(container: HTMLElement | null) { + const focused = document.activeElement; + if (focused instanceof HTMLElement && container?.contains(focused)) focused.blur(); +} + export function AppRouteModalClose() { const gt = useGT(); return ( diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 48b86b8ddfe56..f9a1aca77daa6 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -4,11 +4,14 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitie import { visibilityParentKey } from "@t3tools/client-runtime/state/threads"; import type { ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; -import { Navigate, useNavigate } from "@tanstack/react-router"; +import { Link, Navigate, useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; +import { Button } from "./ui/button"; +import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -17,6 +20,7 @@ import { useAnyEnvironmentHiding, useQuietThreadShell, } from "../state/entities"; +import { environmentUnreachableAtom } from "../state/presentation"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { useEnvironmentShellStatus } from "../state/shell"; import { environmentThreadShells, threadFamilies, useEnvironmentThread } from "../state/threads"; @@ -70,6 +74,9 @@ export function ThreadRouteView({ const serverThreadShell = useQuietThreadShell(serverThreadRef); const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null); const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null); + const environmentUnreachable = useAtomValue( + environmentUnreachableAtom(serverThreadRef?.environmentId ?? null), + ); const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus); const draftThread = useComposerDraftStore((store) => serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null, @@ -137,6 +144,7 @@ export function ThreadRouteView({ serverThreadDeleted: serverThreadShell?.deletedAt != null, unlistedThreadDetail, draftThreadExists: draftThread !== null, + environmentUnreachable, }); const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads; @@ -208,6 +216,8 @@ export function ThreadRouteView({ } else { redirect = ; } + } else if (renderState === "unreachable") { + view = ; } else if (hiddenByTagFilter) { redirect = ; } else if (offShellBlocked) { @@ -236,3 +246,23 @@ export function ThreadRouteView({ ); } + +function UnreachableEnvironmentState() { + return ( + + + + Thread unavailable + + + This thread is on an environment this app is not connected to. + + + + + + + ); +} diff --git a/apps/web/src/components/chat/BackgroundWorkDetails.tsx b/apps/web/src/components/chat/BackgroundWorkDetails.tsx index 72ca70c2b16e1..4b1d0911d51da 100644 --- a/apps/web/src/components/chat/BackgroundWorkDetails.tsx +++ b/apps/web/src/components/chat/BackgroundWorkDetails.tsx @@ -8,7 +8,7 @@ import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2Pe import { T, useGT } from "gt-react"; import { useState } from "react"; -import { InlineButton } from "../ui/button"; +import { Button, InlineButton } from "../ui/button"; import { Dialog, DialogHeader, @@ -100,14 +100,16 @@ export function BackgroundWorkDetails(props: { ) : null} {childThreadId ? ( - { setOpen(false); props.onOpenThread(childThreadId); }} > Open subagent - + ) : null} ); diff --git a/apps/web/src/components/chat/EffortGlyph.test.ts b/apps/web/src/components/chat/EffortGlyph.test.ts index 1c893050e0d41..934d9111feb36 100644 --- a/apps/web/src/components/chat/EffortGlyph.test.ts +++ b/apps/web/src/components/chat/EffortGlyph.test.ts @@ -16,20 +16,25 @@ describe("resolveEffortGlyph", () => { ["ultrathink"], ); + const codex = descriptor(["low", "medium", "high", "xhigh", "max", "ultra"]); + it("fills bars up to the current level and leaves max and workflow levels off the scale", () => { - expect(resolveEffortGlyph(claude, "xhigh")).toEqual({ - count: 4, - filled: 4, - special: null, - label: "Xhigh", - }); + for (const model of [claude, codex]) { + expect(resolveEffortGlyph(model, "xhigh")).toEqual({ + count: 4, + filled: 4, + special: null, + label: "Xhigh", + }); + } }); - it("names Max and Default instead of drawing them", () => { + it("names Max, Default, and Ultra instead of drawing them", () => { expect(resolveEffortGlyph(claude, "max")?.special).toBe("Max"); const reported = descriptor(["default", "low", "medium", "high", "xhigh", "max"]); expect(resolveEffortGlyph(reported, "default")?.special).toBe("Default"); expect(resolveEffortGlyph(reported, "low")).toMatchObject({ count: 4, filled: 1 }); + expect(resolveEffortGlyph(codex, "ultra")?.special).toBe("Ultra"); }); it("names Ultracode and Ultrathink instead of drawing a level", () => { diff --git a/apps/web/src/components/chat/EffortGlyph.tsx b/apps/web/src/components/chat/EffortGlyph.tsx index 8220a2b27272c..2158174405acd 100644 --- a/apps/web/src/components/chat/EffortGlyph.tsx +++ b/apps/web/src/components/chat/EffortGlyph.tsx @@ -11,15 +11,15 @@ const BASELINE_INSET = 2; type SelectDescriptor = Extract; // Older servers offer Ultracode as a level. It changes the workflow, so it keeps its name. -// Max is named too, so the full scale stops short of it. Default leaves the level to the agent. -const NAMED_LEVELS = new Set(["ultracode", "max", "default"]); +// Max and Ultra sit above the bar scale. Default leaves the level to the agent. +const NAMED_LEVELS = new Set(["ultracode", "max", "default", "ultra"]); const OFF_LEVELS = new Set(["off", "none"]); // More bars than this no longer fit the glyph's height in whole pixels. const MAX_BARS = 7; /** * Maps a reasoning select to bars: one per ordinary level, filled up to the current one, with an - * off level as none filled. Max, Default, prompt-injected and workflow levels are named instead. + * off level as none filled. Max, Default, Ultra, prompt-injected and workflow levels keep their names. */ export function resolveEffortGlyph(descriptor: SelectDescriptor, current: string | null) { const special = new Set([...(descriptor.promptInjectedValues ?? []), ...NAMED_LEVELS]); diff --git a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx index 915ed5f929538..7287547df71fc 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx @@ -53,9 +53,7 @@ describe("ExpandedImageDialog", () => { await userEvent.keyboard("{Tab}"); await userEvent.keyboard("{Enter}"); } - await expect - .element(page.getByRole("button", { name: "Back, close image preview" })) - .toHaveFocus(); + await expect.element(page.getByRole("button", { name: "Close image preview" })).toHaveFocus(); await userEvent.keyboard("{Escape}"); await expect.element(opener).toHaveFocus(); expect(opener.element().matches(":focus-visible")).toBe(c.focusVisible); @@ -116,9 +114,7 @@ describe("ExpandedImageDialog", () => { expect(onClose).not.toHaveBeenCalled(); // Focus returns to the popup's trigger and opens its tooltip; leave it for a plain control. - ( - screen.getByRole("button", { name: "Back, close image preview" }).element() as HTMLElement - ).focus(); + (screen.getByRole("button", { name: "Close image preview" }).element() as HTMLElement).focus(); await userEvent.keyboard("{Escape}"); await vi.waitFor(() => expect(onClose).toHaveBeenCalledOnce()); }); diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 0f278c408d487..0d6f1b812de69 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -1,13 +1,7 @@ import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react"; import { flushSync } from "react-dom"; -import { T, useGT } from "gt-react"; -import { - ArrowLeftIcon, - ChevronLeftIcon, - ChevronRightIcon, - ImageIcon, - TextIcon, -} from "lucide-react"; +import { useGT } from "gt-react"; +import { ChevronLeftIcon, ChevronRightIcon, ImageIcon, TextIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview"; @@ -200,14 +194,13 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ {preview.images.length > 1 && (