diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 8bb226018940e..15e512aad101e 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -18,6 +18,11 @@ import { beginAcpMockPrompt } from "./acpMockCancellationState.ts"; const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH; const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1"; +// GitHub Copilot CLI advertises URL-shaped session mode ids. +const copilotModesProfile = process.env.T3_ACP_COPILOT_MODES === "1"; +const copilotModeId = (name: string) => + `https://agentclientprotocol.com/protocol/session-modes#${name}`; +const modeOptionCategory = process.env.T3_ACP_MODE_OPTION_CATEGORY ?? "mode"; const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1"; const emitInterleavedAssistantToolCalls = process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1"; @@ -78,7 +83,11 @@ const permissionOptionIds = { }; const sessionId = "mock-session-1"; -let currentModeId = antigravityProfile ? "default" : "ask"; +let currentModeId = antigravityProfile + ? "default" + : copilotModesProfile + ? copilotModeId("agent") + : "ask"; let currentModelId = antigravityProfile ? "gemini-test-low" : "default"; let parameterizedModelPicker = false; let currentReasoning = "medium"; @@ -267,7 +276,7 @@ function configOptions(): ReadonlyArray { { configId: "mode", name: "Mode", - category: "mode", + category: modeOptionCategory, type: "select" as const, currentValue: currentModeId, options: availableModes.map((mode) => ({ @@ -332,23 +341,29 @@ const availableModes: ReadonlyArray = antigravityProfile { id: "auto_edit", name: "Auto edit" }, { id: "yolo", name: "YOLO" }, ] - : [ - { - id: "ask", - name: "Ask", - description: "Request permission before making any changes", - }, - { - id: "architect", - name: "Architect", - description: "Design and plan software systems without implementation", - }, - { - id: "code", - name: "Code", - description: "Write and modify code with full tool access", - }, - ]; + : copilotModesProfile + ? [ + { id: copilotModeId("agent"), name: "Agent" }, + { id: copilotModeId("plan"), name: "Plan" }, + { id: copilotModeId("autopilot"), name: "Autopilot" }, + ] + : [ + { + id: "ask", + name: "Ask", + description: "Request permission before making any changes", + }, + { + id: "architect", + name: "Architect", + description: "Design and plan software systems without implementation", + }, + { + id: "code", + name: "Code", + description: "Write and modify code with full tool access", + }, + ]; function modeState(): AcpCompat.SessionModeState { return { @@ -1133,6 +1148,18 @@ const program = Effect.gen(function* () { entries: [{ content: "Ship B", priority: "high", status: "in_progress" }], }, }, + { + sessionUpdate: "plan_update", + plan: { + type: "items", + planId: "plan-c", + entries: [ + { content: "Write the fix", priority: "high", status: "completed" }, + { content: "Try another approach", priority: "low", status: "cancelled" }, + { content: "Add a test", priority: "medium", status: "completed" }, + ], + }, + }, { sessionUpdate: "plan_removed", planId: "plan-a" }, { sessionUpdate: "terminal_update", diff --git a/apps/server/src/coderEnvironment.ts b/apps/server/src/coderEnvironment.ts index abf4e13d6c082..f6d5459580ad6 100644 --- a/apps/server/src/coderEnvironment.ts +++ b/apps/server/src/coderEnvironment.ts @@ -94,6 +94,7 @@ export const CODER_ENVIRONMENT_CAPABILITIES = { projectCloneTracking: true, projectOrganization: true, threadProjectFromScratch: true, + oneTimeSchedules: true, // Links are the gateway's workspace link rules; calls between workspaces go through its hub. peerLinks: true, linkFence: true, diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 202807128fab1..530b1f2f1c767 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -492,7 +492,12 @@ function createFakeSourceControlProvider(scenario: FakeProviderScenario = {}): { repository: input.repository, }).pipe( Effect.flatMap(() => { - const cloneUrls = scenario.repositoryCloneUrls?.[input.repository]; + const repository = input.host ? `${input.host}/${input.repository}` : input.repository; + const cloneUrls = + scenario.repositoryCloneUrls?.[repository] ?? + (input.host === "github.com" + ? scenario.repositoryCloneUrls?.[input.repository] + : undefined); return cloneUrls ? Effect.succeed({ nameWithOwner: input.repository, ...cloneUrls }) : Effect.fail( @@ -3900,6 +3905,163 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect.each([ + { mode: "local", repositoryType: "same repo" }, + { mode: "local", repositoryType: "fork" }, + { mode: "worktree", repositoryType: "same repo" }, + { mode: "worktree", repositoryType: "fork" }, + ] as const)( + "checks out same-named repositories on the pull request host ($mode, $repositoryType)", + ({ mode, repositoryType }) => + Effect.gen(function* () { + const isCrossRepository = repositoryType === "fork"; + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + // The checkout is on github.com, which also has a same-named repository, + // and the pull request is on another host. Clone lookups that fall back + // to the checkout's host find the github.com repository. + const enterpriseRemote = yield* createBareRemote(); + const defaultHostRemote = yield* createBareRemote(); + const host = "github.enterprise.test"; + const repository = isCrossRepository ? "fork/repo" : "owner/base"; + const cloneUrl = `https://${host}/${repository}.git`; + yield* runGit(repoDir, ["remote", "add", "origin", defaultHostRemote]); + yield* runGit(repoDir, ["push", "origin", "main", "main:feature/host"]); + yield* runGit(repoDir, ["push", enterpriseRemote, "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/host"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "host.txt"), "enterprise head\n"); + yield* runGit(repoDir, ["add", "host.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Enterprise head"]); + const expectedHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + yield* runGit(repoDir, ["push", enterpriseRemote, "feature/host"]); + yield* runGit(repoDir, ["checkout", "main"]); + if (mode === "worktree") { + yield* runGit(repoDir, ["branch", "-D", "feature/host"]); + } + yield* configureVisibleRemoteUrlWithLocalRewrite( + repoDir, + "origin", + "https://github.com/owner/base.git", + defaultHostRemote, + ); + yield* runGit(repoDir, ["config", `url.${enterpriseRemote}.insteadOf`, cloneUrl]); + const defaultCloneUrl = `https://github.com/${repository}.git`; + yield* runGit(repoDir, [ + "config", + "--add", + `url.${defaultHostRemote}.insteadOf`, + defaultCloneUrl, + ]); + + const { manager } = yield* makeManager({ + providerScenario: { + pullRequest: { + number: 42, + title: "Enterprise head", + url: `https://${host}/owner/base/pull/42`, + baseRefName: "main", + headRefName: "feature/host", + state: "open", + isCrossRepository, + headRepositoryNameWithOwner: repository, + headRepositoryOwnerLogin: isCrossRepository ? "fork" : "owner", + }, + repositoryCloneUrls: { + [repository]: { url: defaultCloneUrl, sshUrl: defaultCloneUrl }, + [`${host}/${repository}`]: { url: cloneUrl, sshUrl: cloneUrl }, + }, + }, + }); + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "42", + mode, + }); + const checkoutDir = result.worktreePath ?? repoDir; + const upstreamRemote = (yield* runGit(checkoutDir, [ + "config", + `branch.${result.branch}.remote`, + ])).stdout.trim(); + const upstreamUrl = (yield* runGit(checkoutDir, [ + "config", + `remote.${upstreamRemote}.url`, + ])).stdout.trim(); + const head = (yield* runGit(checkoutDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect({ upstreamUrl, head }).toEqual({ upstreamUrl: cloneUrl, head: expectedHead }); + expect(NodeFS.readFileSync(NodePath.join(checkoutDir, "host.txt"), "utf8")).toBe( + "enterprise head\n", + ); + }), + ); + + it.effect.each([ + { mode: "local", url: "malformed pull request URL" }, + { mode: "worktree", url: "malformed pull request URL" }, + { mode: "local", url: "file:///owner/base/pull/42" }, + { mode: "worktree", url: "file:///owner/base/pull/42" }, + ] as const)( + "checks out pull requests with hostless URLs using the default host ($mode, $url)", + ({ mode, url }) => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const originDir = yield* createBareRemote(); + const forkDir = yield* createBareRemote(); + const cloneUrl = "https://github.com/fork/repo.git"; + yield* runGit(repoDir, ["remote", "add", "origin", originDir]); + yield* runGit(repoDir, ["push", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/malformed-url"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "fork.txt"), "fork head\n"); + yield* runGit(repoDir, ["add", "fork.txt"]); + yield* runGit(repoDir, ["commit", "-m", "Fork head"]); + const expectedHead = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout.trim(); + yield* runGit(repoDir, ["push", forkDir, "feature/malformed-url"]); + yield* runGit(repoDir, ["checkout", "main"]); + if (mode === "worktree") { + yield* runGit(repoDir, ["branch", "-D", "feature/malformed-url"]); + } + yield* runGit(repoDir, ["config", `url.${forkDir}.insteadOf`, cloneUrl]); + + const { manager } = yield* makeManager({ + providerScenario: { + pullRequest: { + number: 42, + title: "Fork head", + url, + baseRefName: "main", + headRefName: "feature/malformed-url", + state: "open", + isCrossRepository: true, + headRepositoryNameWithOwner: "fork/repo", + headRepositoryOwnerLogin: "fork", + }, + repositoryCloneUrls: { + "fork/repo": { url: cloneUrl, sshUrl: cloneUrl }, + }, + }, + }); + const result = yield* preparePullRequestThread(manager, { + cwd: repoDir, + reference: "42", + mode, + }); + const checkoutDir = result.worktreePath ?? repoDir; + const upstreamRemote = (yield* runGit(checkoutDir, [ + "config", + `branch.${result.branch}.remote`, + ])).stdout.trim(); + const upstreamUrl = (yield* runGit(checkoutDir, [ + "config", + `remote.${upstreamRemote}.url`, + ])).stdout.trim(); + const head = (yield* runGit(checkoutDir, ["rev-parse", "HEAD"])).stdout.trim(); + expect({ upstreamUrl, head }).toEqual({ upstreamUrl: cloneUrl, head: expectedHead }); + expect(NodeFS.readFileSync(NodePath.join(checkoutDir, "fork.txt"), "utf8")).toBe( + "fork head\n", + ); + }), + ); + const setUpLocalCheckoutPullRequest = Effect.fnUntraced(function* ( reportedHead: (pullHead: string) => string | undefined = (pullHead) => pullHead, syncCheckoutWithPullHead = true, diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index bd7ea68cd749b..1e4a9fb430bb3 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -893,6 +893,11 @@ export const make = Effect.gen(function* () { }), ); + const pullRequestHostOptions = (url: string) => { + const host = URL.parse(url)?.host; + return host ? { host } : {}; + }; + const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")( function* ( cwd: string, @@ -923,6 +928,7 @@ export const make = Effect.gen(function* () { const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({ cwd, repository: repositoryNameWithOwner, + ...pullRequestHostOptions(pullRequest.url), }); const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url"); const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; @@ -1036,6 +1042,7 @@ export const make = Effect.gen(function* () { const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({ cwd, repository: repositoryNameWithOwner, + ...pullRequestHostOptions(pullRequest.url), }); const originRemoteUrl = yield* gitCore.readConfigValue(cwd, "remote.origin.url"); const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url; diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 077c39d0a4532..10f61f9f395c3 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest"; import { CommandId, EnvironmentId, + GitCommandError, MessageId, NodeId, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, @@ -19,11 +20,13 @@ import { RunId, ThreadId, type OrchestrationV2ServerCommand, + type OrchestrationV2StoredEvent, type OrchestrationV2ThreadProjection, type ServerProvider, } from "@t3tools/contracts"; import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace"; 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"; @@ -1129,6 +1132,155 @@ describe("OrchestratorMcpService provider resolution", () => { turnItems: [], } as unknown as OrchestrationV2ThreadProjection; + it.effect.each([ + "parent completion", + "nested child completion", + "child run completion", + "child question", + "child approval", + ] as const)("a task wait still returns on %s", (wake) => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const subscribed = yield* Deferred.make(); + const nestedId = NodeId.make("node:mcp-wait-nested"); + const childRunId = RunId.make("run:mcp-wait-child"); + const childRootId = NodeId.make("node:mcp-wait-child-root"); + const eventThreadId = wake === "parent completion" ? parentThreadId : childThreadId; + const eventType = + wake === "child run completion" + ? "run.updated" + : wake === "child question" || wake === "child approval" + ? "runtime-request.updated" + : "subagent.updated"; + const terminal = wake.endsWith("completion"); + let ready = false; + const task = () => ({ + id: taskId, + threadId: parentThreadId, + runId: parentRunId, + parentNodeId, + origin: "app_owned", + providerInstanceId: codexInstanceId, + driver: "codex", + childThreadId, + model: "gpt-5.4", + status: ready && terminal ? "completed" : "running", + result: ready && wake === "parent completion" ? "done" : null, + }); + const child = () => + ({ + ...childProjection, + runs: [ + { + id: childRunId, + ordinal: 1, + status: + wake === "nested child completion" || (ready && terminal) ? "completed" : "running", + startedAt: DateTime.makeUnsafe(0), + completedAt: ready && terminal ? DateTime.makeUnsafe(1) : null, + }, + ], + subagents: + wake === "nested child completion" + ? [{ id: nestedId, status: ready ? "completed" : "running" }] + : [], + nodes: [{ id: childRootId, runId: childRunId }], + runtimeRequests: + ready && !terminal + ? [ + { + id: "request:mcp-wait-answer", + nodeId: childRootId, + kind: wake === "child question" ? "user_input" : "command", + status: "pending", + responseCapability: { type: "live" }, + createdAt: DateTime.makeUnsafe(0), + }, + ] + : [], + }) as unknown as OrchestrationV2ThreadProjection; + const dependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + assertProviderInstanceEnabled: () => Effect.void, + isProviderInstanceEnabledForProject: () => Effect.succeed(true), + getThreadRecords: (threadId) => + Effect.sync(() => (threadId === parentThreadId ? parentProjection([task()]) : child())), + getThreadEventSequence: () => Effect.succeed(0), + delegatedTaskResultPending: () => Effect.succeed(false), + streamStoredEventsFrom: (input) => + input?.threadId === eventThreadId && input.eventType === eventType + ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe( + Stream.drain, + Stream.concat(Stream.fromQueue(events)), + ) + : Stream.never, + dispatch: () => + Effect.succeed({ + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task() } }], + } as never), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + model: "gpt-5.4", + }), + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const waiting = yield* service + .delegateTask(scope, { task: "Review the change.", mode: "wait" }) + .pipe(Effect.forkChild); + yield* Deferred.await(subscribed); + ready = true; + if (wake === "parent completion") { + yield* Queue.offer(events, { + sequence: 2, + event: { + type: "subagent.updated", + threadId: parentThreadId, + payload: { ...task(), id: nestedId }, + }, + } as unknown as OrchestrationV2StoredEvent); + } + yield* Queue.offer(events, { + sequence: 3, + event: { + type: eventType, + threadId: eventThreadId, + payload: { id: wake === "parent completion" ? taskId : nestedId }, + }, + } as unknown as OrchestrationV2StoredEvent); + const result = yield* Fiber.join(waiting); + assert.isFalse(result.waitTimedOut); + if (terminal) { + assert.equal(result.status, "completed"); + if (wake === "parent completion") assert.equal(result.summary, "done"); + } else { + assert.equal(result.status, "running"); + if (wake === "child question") assert.isTrue(result.hasPendingQuestion); + else { + assert.deepEqual(result.pendingApproval, { + requestId: "request:mcp-wait-answer", + kind: "command", + runId: childRunId, + }); + } + } + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + it.effect( "advertises orchestration capability from registered adapters rather than a driver allowlist", () => @@ -2427,6 +2579,218 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); }); + + describe("the base branch of an unbound scheduled task", () => { + const projectId = ProjectId.make("project:scheduled-base"); + const workspaceRoot = "/repo/scheduled-base"; + const existing: ScheduledTask = { + id: ScheduledTaskId.make("scheduled-task:base"), + title: "Nightly", + prompt: "Check the build", + enabled: true, + schedule: { type: "interval", everyMs: 3_600_000 }, + projectId, + threadId: null, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "approval-required", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + createdAt: "2026-10-05T00:00:00.000Z", + updatedAt: "2026-10-05T00:00:00.000Z", + nextRunAt: null, + lastRunAt: null, + lastRunStatus: "never", + lastRunError: null, + runCount: 0, + }; + const client: McpInvocationScope = { + environmentId: EnvironmentId.make("environment:scheduled-base"), + requestNamespace: "client:scheduled-base", + thread: undefined, + client: { + sessionId: "scheduled-base", + label: "Claude Code", + access: "approval-required", + }, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const service = ( + git: Partial, + saved: Ref.Ref>, + ) => + OrchestratorMcpService.layer.pipe( + Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})), + Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)), + Layer.provide( + Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + }), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeedSome({ + id: projectId, + workspaceRoot, + defaultModelSelection: existing.modelSelection, + } as never), + }), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({ + list: () => Effect.succeed({ tasks: [existing] }), + upsert: (input) => + Ref.update(saved, (strategies) => [...strategies, input.workspaceStrategy]).pipe( + Effect.as({ task: existing }), + ), + }), + ), + ), + ); + const masterRepository: Partial = { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + resolveDefaultBranchName: (cwd, remoteName) => + Effect.succeed(cwd === workspaceRoot && remoteName === "origin" ? "master" : null), + resolveCommit: () => Effect.succeed({ commitSha: "abc123" }), + }; + const schedule = { type: "interval", everyMs: 3_600_000 } as const; + + it.effect("starts from the project's default branch", () => + Effect.gen(function* () { + const saved = yield* Ref.make>([]); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide(service(masterRepository, saved)), + ); + yield* mcp.scheduleTask(client, { projectId, prompt: "Check the build", schedule }); + assert.deepEqual(yield* Ref.get(saved), [ + { type: "worktree", baseRef: "origin/master", startFromOrigin: true }, + ]); + }), + ); + + it.effect("follows the default branch when a task is unbound from its thread", () => + Effect.gen(function* () { + const saved = yield* Ref.make>([]); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide(service(masterRepository, saved)), + ); + yield* mcp.updateScheduledTask(client, { + scheduledTaskId: existing.id, + bindToCurrentThread: false, + }); + assert.deepEqual(yield* Ref.get(saved), [ + { type: "worktree", baseRef: "origin/master", startFromOrigin: true }, + ]); + }), + ); + + it.effect.each([ + { + name: "no remote, only master", + remote: null, + remoteDefault: null, + refs: ["refs/heads/master"], + baseRef: "master", + }, + { + name: "no remote, main and master", + remote: null, + remoteDefault: null, + refs: ["refs/heads/master", "refs/heads/main"], + baseRef: "main", + }, + { + name: "no remote, neither main nor master", + remote: null, + remoteDefault: null, + refs: ["refs/heads/develop"], + baseRef: "main", + }, + { + name: "no recorded HEAD, remote main and a stale local master", + remote: "origin", + remoteDefault: null, + refs: ["refs/heads/master", "refs/remotes/origin/main"], + baseRef: "origin/main", + }, + { + name: "no recorded HEAD, master only on the remote", + remote: "origin", + remoteDefault: null, + refs: ["refs/remotes/origin/master"], + baseRef: "origin/master", + }, + { + name: "no recorded HEAD, local main and master only on the remote", + remote: "origin", + remoteDefault: null, + refs: ["refs/heads/main", "refs/remotes/origin/master"], + baseRef: "origin/master", + }, + { + name: "no recorded HEAD, nothing conventional on the remote, local main", + remote: "origin", + remoteDefault: null, + refs: ["refs/heads/main", "refs/remotes/origin/develop"], + baseRef: "main", + }, + { + name: "a recorded HEAD whose branch is gone", + remote: "origin", + remoteDefault: "main", + refs: ["refs/heads/main", "refs/remotes/origin/master"], + baseRef: "origin/master", + }, + { + name: "a remote not called origin", + remote: "upstream", + remoteDefault: "develop", + refs: ["refs/remotes/upstream/develop"], + baseRef: "upstream/develop", + }, + { + name: "a remote not called origin, no recorded HEAD", + remote: "upstream", + remoteDefault: null, + refs: ["refs/remotes/upstream/main"], + baseRef: "upstream/main", + }, + ])("$name starts from $baseRef", ({ remote, remoteDefault, refs, baseRef }) => + Effect.gen(function* () { + const saved = yield* Ref.make>([]); + const gitFailure = (cwd: string, detail: string) => + new GitCommandError({ operation: "GitVcsDriver.test", command: "git", cwd, detail }); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + { + resolvePrimaryRemoteName: (cwd) => + remote === null + ? Effect.fail(gitFailure(cwd, "No git remote is configured.")) + : Effect.succeed(remote), + resolveDefaultBranchName: () => Effect.succeed(remoteDefault), + resolveCommit: ({ cwd, revision }) => + refs.includes(revision) + ? Effect.succeed({ commitSha: "abc123" }) + : Effect.fail(gitFailure(cwd, "Needed a single revision")), + }, + saved, + ), + ), + ); + yield* mcp.scheduleTask(client, { projectId, prompt: "Check the build", schedule }); + assert.deepEqual(yield* Ref.get(saved), [ + { type: "worktree", baseRef, startFromOrigin: true }, + ]); + }), + ); + }); it.effect( "reports the child run's selection after a restart and the thread selection before launch", () => @@ -2616,6 +2980,96 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); + it.effect("accepts the inherited options it reports back as a delegate target", () => + Effect.gen(function* () { + // t3_thread_launch keeps a model selection as given, so a thread can hold an option its model lacks. + const inherited = { + instanceId: codexInstanceId, + model: "gpt-5.4", + options: [ + { id: "reasoningEffort", value: "low" }, + { id: "fastMode", value: false }, + ], + } as const; + const commands: Array<{ readonly modelSelection?: unknown }> = []; + const task = { + id: taskId, + threadId: parentThreadId, + origin: "app_owned", + childThreadId, + providerInstanceId: codexInstanceId, + model: inherited.model, + status: "running", + result: null, + }; + const dependencies = Layer.mergeAll( + NodeServices.layer, + Layer.mock(ThreadManagementService.ThreadManagementService)({ + hasReceipt: () => Effect.succeed(false), + assertProviderInstanceEnabled: () => Effect.void, + getThreadRecords: (threadId) => + Effect.succeed( + threadId === parentThreadId + ? parentProjection(commands.length > 0 ? [task] : [], inherited) + : childProjection, + ), + dispatch: (command) => + Effect.sync(() => { + commands.push(command as { readonly modelSelection?: unknown }); + return { + sequence: 1, + storedEvents: [{ event: { type: "subagent.updated", payload: task } }], + } as never; + }), + }), + ServerSettings.layerTest(), + providerRegistryLayer([ + { + ...providerSnapshot({ + instanceId: codexInstanceId, + driver: ProviderDriverKind.make("codex"), + }), + models: [ + { + slug: inherited.model, + name: inherited.model, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "reasoningEffort", + label: "Reasoning", + type: "select", + options: [{ id: "low", label: "Low" }], + }, + ], + }, + }, + ], + }, + ]), + adapterRegistryLayer([codexInstanceId]), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}), + ); + yield* Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + const { inheritedOptions } = yield* service.capabilities(scope); + yield* service.delegateTask(scope, { + task: "Review the change.", + target: yield* decodeTarget({ options: inheritedOptions }), + mode: "async", + }); + assert.deepEqual(commands[0]?.modelSelection, { + ...inherited, + options: [inherited.options[0]], + }); + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); + }), + ); + describe("resolveRuntimeMode", () => { const muse = { modelSelection: { instanceId: ProviderInstanceId.make("muse"), model: "muse-model" }, @@ -2653,7 +3107,11 @@ describe("OrchestratorMcpService thread lookup", () => { capabilities: new Set(["orchestration"]), issuedAt: 1, }; - const service = (shells: ReadonlyArray, sent: Ref.Ref) => + const service = ( + shells: ReadonlyArray, + sent: Ref.Ref, + overrides: Partial = {}, + ) => layerOrchestratorService.pipe( Layer.provide( Layer.mergeAll( @@ -2662,6 +3120,7 @@ describe("OrchestratorMcpService thread lookup", () => { getThreadShell: (threadId) => Effect.succeed(shells.find((shell) => shell.id === threadId) ?? null), sendToThread: () => Ref.update(sent, (count) => count + 1).pipe(Effect.as({} as never)), + ...overrides, }), ServerSettings.layerTest(), Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }), @@ -2684,14 +3143,15 @@ describe("OrchestratorMcpService thread lookup", () => { const send = yield* mcp .sendToThread(client, { threadId: bareId, message: "hello" }) .pipe(Effect.flip); - return { read, send, sends: yield* Ref.get(sent) }; + const wait = yield* mcp.waitForThread(client, { threadId: bareId }).pipe(Effect.flip); + return { read, send, wait, sends: yield* Ref.get(sent) }; }).pipe(Effect.provide(service(shells, sent))); }); it.effect("points a bare uuid at the mcp: thread it belongs to", () => Effect.gen(function* () { - const { read, send, sends } = yield* failuresFor([launched]); - for (const error of [read, send]) { + const { read, send, wait, sends } = yield* failuresFor([launched]); + for (const error of [read, send, wait]) { assert.equal(error.code, "thread_not_found"); assert.include(error.message, `mcp:${bareId}`); } @@ -2701,19 +3161,76 @@ describe("OrchestratorMcpService thread lookup", () => { it.effect("keeps the plain message for an id that matches nothing", () => Effect.gen(function* () { - const { read, send } = yield* failuresFor([]); + const { read, send, wait } = yield* failuresFor([]); assert.equal(read.code, "thread_not_found"); assert.equal(read.message, `Thread ${bareId} is no longer available.`); assert.equal(send.code, "thread_not_found"); assert.equal(send.message, `Thread ${bareId} was not found.`); + assert.equal(wait.code, "thread_not_found"); + assert.equal(wait.message, send.message); }), ); it.effect("does not name an mcp: thread that was deleted", () => Effect.gen(function* () { - const { read, send } = yield* failuresFor([deletedLaunched]); + const { read, send, wait } = yield* failuresFor([deletedLaunched]); assert.equal(read.message, `Thread ${bareId} is no longer available.`); assert.equal(send.message, `Thread ${bareId} was not found.`); + assert.equal(wait.message, send.message); + }), + ); + + it.effect("refuses waiting without orchestration capability before reading the target", () => + Effect.gen(function* () { + const sent = yield* Ref.make(0); + return yield* Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + const error = yield* mcp + .waitForThread({ ...client, capabilities: new Set() }, { threadId: bareId }) + .pipe(Effect.flip); + assert.equal(error.code, "capability_denied"); + }).pipe( + Effect.provide( + service([], sent, { + getThreadShell: () => Effect.die("Unauthorized target access"), + }), + ), + ); + }), + ); + + it.effect("waits on the caller's own thread without a separate shell lookup", () => + Effect.gen(function* () { + const sent = yield* Ref.make(0); + return yield* Effect.gen(function* () { + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService; + const result = yield* mcp.waitForThread( + { + ...client, + thread: { + threadId: launched.id, + providerSessionId: "provider-session:wait-self", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + }, + { threadId: launched.id }, + ); + assert.deepEqual(result, { + threadId: launched.id, + runId: null, + status: "idle", + timedOut: false, + }); + }).pipe( + Effect.provide( + service([], sent, { + getThreadShell: () => Effect.die("Unexpected shell lookup for the caller"), + getThreadRecords: () => Effect.succeed(idleThreadProjection(launched)), + waitForThread: () => + Effect.succeed({ threadId: launched.id, run: null, timedOut: false }), + }), + ), + ); }), ); }); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index c1a32166ede7f..987d1b9142bac 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -251,14 +251,6 @@ function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } -function scheduledTaskWorkspaceStrategy( - boundToThread: boolean, -): ScheduledTask["workspaceStrategy"] { - return boundToThread - ? { type: "root" } - : { type: "worktree", baseRef: "main", startFromOrigin: true }; -} - function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): OrchestratorMcpScheduledTask { return { scheduledTaskId: task.id, @@ -372,6 +364,15 @@ function providerConstraints( return constraints; } +/** t3_thread_launch keeps a selection as given, so it can hold options its model does not have. */ +function knownOptions( + options: ReadonlyArray | undefined, + descriptors: ReadonlyArray | undefined, +): ReadonlyArray | undefined { + if (options === undefined || descriptors === undefined) return options; + return options.filter((option) => descriptors.some((descriptor) => descriptor.id === option.id)); +} + /** Skip checks without descriptors; reject duplicate IDs because consumers disagree on precedence. */ function invalidOptionSelections( selections: ReadonlyArray, @@ -1151,6 +1152,7 @@ const make = Effect.gen(function* () { const loadTargetThread = Effect.fn("OrchestratorMcpService.loadTargetThread")(function* ( threadId: ThreadId, + includeHistory = true, ) { const shell = yield* threadManagement .getThreadShell(threadId) @@ -1158,18 +1160,24 @@ const make = Effect.gen(function* () { if (shell === null || shell.deletedAt !== null) { return yield* threadNotFound(threadManagement, threadId, `Thread ${threadId} was not found.`); } - return yield* loadProjectThread(shell.projectId, threadId); + // Native wait owns its history reads; keep legacy import and project validation here. + return yield* includeHistory + ? loadProjectThread(shell.projectId, threadId) + : threadManagement + .getProjectThreadRecords({ projectId: shell.projectId, threadId }, []) + .pipe(Effect.mapError(threadManagementFailure)); }); const loadScopedThread = Effect.fn("OrchestratorMcpService.loadScopedThread")(function* ( scope: McpInvocationScope, threadId: ThreadId, + includeHistory = true, ) { const caller = yield* loadCaller(scope); const target = caller.parent !== undefined && threadId === caller.parent.thread.id ? caller.parent - : yield* loadTargetThread(threadId); + : yield* loadTargetThread(threadId, includeHistory); return { ...caller, target } as const; }); @@ -1394,10 +1402,10 @@ const make = Effect.gen(function* () { ); } + const descriptors = provider.models.find((candidate) => candidate.slug === model)?.capabilities + ?.optionDescriptors; const requestedOptions = input.target?.options; if (requestedOptions !== undefined) { - const descriptors = provider.models.find((candidate) => candidate.slug === model) - ?.capabilities?.optionDescriptors; const invalid = invalidOptionSelections(requestedOptions, descriptors); if (invalid.length > 0) { return yield* failure( @@ -1409,7 +1417,9 @@ const make = Effect.gen(function* () { const inheritsOptions = instanceId === inheritedSelection.instanceId && model === inheritedSelection.model; - let options = inheritsOptions ? inheritedSelection.options : undefined; + let options = inheritsOptions + ? knownOptions(inheritedSelection.options, descriptors) + : undefined; if (requestedOptions !== undefined) { const selections = new Map( (requestedOptions.length === 0 ? [] : (options ?? [])).map((selection) => [ @@ -1695,7 +1705,17 @@ const make = Effect.gen(function* () { task.completionDelivery?.state !== "acknowledged" && task.completionDelivery?.state !== "disposed" ) { - const parentProjection = yield* loadProjection(scope.thread.threadId); + const parentThreadId = scope.thread.threadId; + const parentProjection = yield* threadManagement + .getThreadRecords(parentThreadId, ["runs"]) + .pipe( + Effect.mapError((error) => + failure( + "orchestration_error", + `Unable to read thread ${parentThreadId}: ${errorMessage(error)}`, + ), + ), + ); const observingRun = ThreadManagementService.latestActiveRun(parentProjection); yield* threadManagement .dispatch({ @@ -1773,12 +1793,23 @@ const make = Effect.gen(function* () { : TASK_WAKE_EVENTS; return yield* Stream.mergeAll( wakeEvents.map(({ thread, eventType }) => - threadManagement.streamStoredEventsFrom({ - threadId: - thread === "parent" || childThreadId === null ? scope.thread.threadId : childThreadId, - afterSequence, - eventType, - }), + threadManagement + .streamStoredEventsFrom({ + threadId: + thread === "parent" || childThreadId === null + ? scope.thread.threadId + : childThreadId, + afterSequence, + eventType, + }) + .pipe( + Stream.filter( + ({ event }) => + thread === "child" || + event.type !== "subagent.updated" || + event.payload.id === taskId, + ), + ), ), { concurrency: "unbounded" }, ).pipe( @@ -1792,6 +1823,52 @@ const make = Effect.gen(function* () { effect.pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)), ); + const refExists = (cwd: string, revision: string) => + gitDriver.resolveCommit({ cwd, revision }).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ); + + const resolveScheduledTaskBaseRef = Effect.fn( + "OrchestratorMcpService.resolveScheduledTaskBaseRef", + )(function* (cwd: string) { + const remoteName = yield* gitDriver + .resolvePrimaryRemoteName(cwd) + .pipe(Effect.orElseSucceed(() => null)); + const conventional = ["main", "master"]; + if (remoteName !== null) { + const remoteDefault = yield* gitDriver + .resolveDefaultBranchName(cwd, remoteName) + .pipe(Effect.orElseSucceed(() => null)); + // Fetch does not update a recorded HEAD, so it can outlive the branch it names. + for (const branch of remoteDefault === null + ? conventional + : [remoteDefault, ...conventional]) { + // Launch resolves a bare name through a local branch's upstream, or else assumes `origin`. + if (yield* refExists(cwd, `refs/remotes/${remoteName}/${branch}`)) { + return `${remoteName}/${branch}`; + } + } + } + // Local-only repositories, or a remote with neither a usable HEAD nor a conventional branch. + for (const branch of conventional) { + if (yield* refExists(cwd, `refs/heads/${branch}`)) return branch; + } + return "main"; + }); + + const scheduledTaskWorkspaceStrategy = Effect.fn( + "OrchestratorMcpService.scheduledTaskWorkspaceStrategy", + )(function* (boundToThread: boolean, projectId: ProjectId) { + if (boundToThread) return { type: "root" as const }; + const { workspaceRoot } = yield* requireProject(projectId); + return { + type: "worktree" as const, + baseRef: yield* resolveScheduledTaskBaseRef(workspaceRoot), + startFromOrigin: true, + }; + }); + const scheduledTaskRunModes = Effect.fn("OrchestratorMcpService.scheduledTaskRunModes")( function* (task: ScheduledTask) { const modes = [{ runtimeMode: task.runtimeMode, interactionMode: task.interactionMode }]; @@ -1903,7 +1980,7 @@ const make = Effect.gen(function* () { schedule: input.schedule, projectId, threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null, - workspaceStrategy: scheduledTaskWorkspaceStrategy(bindToCurrentThread), + workspaceStrategy: yield* scheduledTaskWorkspaceStrategy(bindToCurrentThread, projectId), modelSelection, runtimeMode: limits.runtimeMode, interactionMode: limits.interactionMode, @@ -1975,7 +2052,7 @@ const make = Effect.gen(function* () { const workspaceStrategy = input.bindToCurrentThread === undefined ? existing.workspaceStrategy - : scheduledTaskWorkspaceStrategy(input.bindToCurrentThread); + : yield* scheduledTaskWorkspaceStrategy(input.bindToCurrentThread, existing.projectId); const upsertInput: ScheduledTaskUpsertInput = { id: existing.id, title: input.title ?? existing.title, @@ -2160,7 +2237,14 @@ const make = Effect.gen(function* () { parentThreadId: parent?.thread.id ?? null, inheritedProviderInstanceId: inherited?.instanceId ?? null, inheritedModel: inherited?.model ?? null, - inheritedOptions: inherited?.options ?? [], + inheritedOptions: + knownOptions( + inherited?.options, + providers + .find((provider) => provider.instanceId === inherited?.instanceId) + ?.models.find((model) => model.slug === inherited?.model)?.capabilities + ?.optionDescriptors, + ) ?? [], runtimeMode: limits.runtimeMode, interactionMode: limits.interactionMode, providers: providers.map((provider) => { @@ -3018,7 +3102,7 @@ const make = Effect.gen(function* () { } satisfies OrchestratorMcpThreadSendResult; }), waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) { - const { parent, target } = yield* loadScopedThread(scope, input.threadId); + const { parent, target } = yield* loadScopedThread(scope, input.threadId, false); const result = yield* threadManagement .waitForThread({ projectId: target.thread.projectId, diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 12c1ba5a3836d..ceca7a47e213a 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -153,7 +153,7 @@ const ScheduleTaskTool = Tool.make("schedule_task", { failureMode: "return", dependencies, }) - .annotate(Tool.Title, "Schedule a recurring task") + .annotate(Tool.Title, "Schedule a task") .annotate(Tool.Destructive, true) .annotate(Tool.OpenWorld, true); diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 53d3c1c2846c5..a2ab0b095b1c7 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -484,6 +484,62 @@ describe("pull request toolkit handlers", () => { }), ); + it.effect("links several pull requests in one call", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + thread: makeThread([makeLink(1), { ...makeLink(2), source: "stack-dismissed" }]), + }); + const url = (number: number) => + `https://gitlab.com/t3tools/t3code/-/merge_requests/${number}`; + const result = yield* harness.call("link_pull_requests", { + urls: [url(1), url(2), url(3), url(3), "https://example.com/not-a-pr"], + }); + expect(result).toEqual({ + linked: [{ host: "gitlab.com", repository: "t3tools/t3code", numbers: [2, 3] }], + alreadyLinked: [{ host: "gitlab.com", repository: "t3tools/t3code", numbers: [1] }], + linkedCount: 3, + invalidUrls: ["https://example.com/not-a-pr"], + }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.link", number: 2, source: "agent" }, + { type: "thread.pull-request.link", number: 3, source: "agent" }, + ]); + }), + ); + + it.effect("unlinks every visible pull request in the given states in one call", () => + Effect.gen(function* () { + const withState = (number: number, state: "open" | "closed" | "merged") => { + const link = makeLink(number, { headBranch: `branch-${number}` }); + return { ...link, snapshot: { ...link.snapshot!, state } }; + }; + const harness = yield* makeHarness({ + thread: makeThread([ + withState(1, "merged"), + withState(2, "open"), + withState(3, "closed"), + makeLink(4), + { ...withState(5, "merged"), source: "stack-dismissed" }, + ]), + }); + const result = yield* harness.call("unlink_pull_requests", { + states: ["closed", "merged"], + }); + expect(result).toEqual({ + unlinked: [ + { host: "gitlab.com", repository: "t3tools/t3code", state: "merged", numbers: [1] }, + { host: "gitlab.com", repository: "t3tools/t3code", state: "closed", numbers: [3] }, + ], + unlinkedCount: 2, + remaining: 2, + }); + expect(yield* Ref.get(harness.commands)).toMatchObject([ + { type: "thread.pull-request.unlink", number: 1 }, + { type: "thread.pull-request.unlink", number: 3 }, + ]); + }), + ); + it.effect("lists visible links with host state and derived chain order", () => Effect.gen(function* () { const harness = yield* makeHarness({ diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index a4cd07b89fb4f..581dc6708dc22 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -392,6 +392,55 @@ const make = Effect.gen(function* () { return { ...target, alreadyLinked, ...next }; }), ), + link_pull_requests: writesThread((input) => + Effect.gen(function* () { + const thread = yield* requireThread(PullRequestLinkFailedError, input.threadId); + const targets: Array = []; + const invalidUrls: Array = []; + for (const url of input.urls) { + const target = yield* resolveTarget({ url }, undefined).pipe(Effect.option); + if (Option.isNone(target)) invalidUrls.push(url); + else if (!targets.some((seen) => threadPullRequestKeysEqual(seen, target.value))) + targets.push(target.value); + } + const links = threadPullRequestsOf(thread); + const isLinked = (target: ResolvedTarget) => + links.some( + (link) => link.source !== "stack-dismissed" && threadPullRequestKeysEqual(link, target), + ); + const fresh = targets.filter((target) => !isLinked(target)); + const alreadyLinked = targets.filter(isLinked); + yield* Effect.forEach(fresh, (target) => + Effect.gen(function* () { + yield* engine.dispatch({ + type: "thread.pull-request.link", + commandId: yield* commandId("mcp-pr-link", thread.id), + threadId: thread.id, + host: target.host, + repository: target.repository, + number: target.number, + url: target.url, + source: "agent", + }); + }).pipe(Effect.catchCause(dispatchFailure(PullRequestLinkFailedError))), + ); + const byRepository = (prs: ReadonlyArray) => + [...Map.groupBy(prs, (pr) => `${pr.host}/${pr.repository}`).values()].map((group) => ({ + host: group[0]!.host, + repository: group[0]!.repository, + numbers: group.map((pr) => pr.number), + })); + return { + linked: byRepository(fresh), + alreadyLinked: byRepository(alreadyLinked), + linkedCount: targets.length, + ...(invalidUrls.length > 0 ? { invalidUrls } : {}), + ...(thread.lineage.relationshipToParent === "subagent" + ? { next: CHILD_PULL_REQUEST_REPORT_NEXT } + : {}), + }; + }), + ), unlink_pull_request: writesThread((input) => Effect.gen(function* () { const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId); @@ -426,6 +475,42 @@ const make = Effect.gen(function* () { }; }), ), + unlink_pull_requests: writesThread((input) => + Effect.gen(function* () { + const thread = yield* requireThread(PullRequestUnlinkFailedError, input.threadId); + const visible = visibleThreadPullRequests(threadPullRequestsOf(thread)); + const matching = visible.flatMap((link) => { + const state = link.snapshot?.state; + return state !== undefined && input.states.includes(state) + ? [{ ...normalizeThreadPullRequestKey(link), state }] + : []; + }); + yield* Effect.forEach(matching, ({ host, repository, number }) => + Effect.gen(function* () { + yield* engine.dispatch({ + type: "thread.pull-request.unlink", + commandId: yield* commandId("mcp-pr-unlink", thread.id), + threadId: thread.id, + host, + repository, + number, + }); + }).pipe(Effect.catchCause(dispatchFailure(PullRequestUnlinkFailedError))), + ); + // Numbers grouped by repository and state keep a large batch's result small. + const groups = Map.groupBy(matching, (pr) => `${pr.host}/${pr.repository}/${pr.state}`); + return { + unlinked: [...groups.values()].map((prs) => ({ + host: prs[0]!.host, + repository: prs[0]!.repository, + state: prs[0]!.state, + numbers: prs.map((pr) => pr.number), + })), + unlinkedCount: matching.length, + remaining: visible.length - matching.length, + }; + }), + ), list_thread_pull_requests: McpToolAccess.reads((input) => requireThread(PullRequestListFailedError, input.threadId).pipe( Effect.map(listThreadPullRequests), diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 186a20d056353..c6403b1dba394 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -223,6 +223,23 @@ export const LinkPullRequestResult = Schema.Struct({ }); export type LinkPullRequestResult = typeof LinkPullRequestResult.Type; +const PullRequestNumbersByRepository = Schema.Array( + Schema.Struct({ + host: Schema.String, + repository: Schema.String, + numbers: Schema.Array(Schema.Int), + }), +); + +export const LinkPullRequestsResult = Schema.Struct({ + linked: PullRequestNumbersByRepository, + alreadyLinked: PullRequestNumbersByRepository, + linkedCount: Schema.Int, + invalidUrls: Schema.optional(Schema.Array(Schema.String)), + next: Schema.optional(Schema.String), +}); +export type LinkPullRequestsResult = typeof LinkPullRequestsResult.Type; + export const UnlinkPullRequestResult = Schema.Struct({ host: Schema.String, repository: Schema.String, @@ -231,6 +248,20 @@ export const UnlinkPullRequestResult = Schema.Struct({ }); export type UnlinkPullRequestResult = typeof UnlinkPullRequestResult.Type; +export const UnlinkPullRequestsResult = Schema.Struct({ + unlinked: Schema.Array( + Schema.Struct({ + host: Schema.String, + repository: Schema.String, + state: PullRequestState, + numbers: Schema.Array(Schema.Int), + }), + ), + unlinkedCount: Schema.Int, + remaining: Schema.Int, +}); +export type UnlinkPullRequestsResult = typeof UnlinkPullRequestsResult.Type; + export const WatchPullRequestResult = Schema.Struct({ ...PullRequestIdentity, watching: Schema.Boolean, @@ -271,7 +302,8 @@ export const ListThreadPullRequestsResult = Schema.Struct({ export type ListThreadPullRequestsResult = typeof ListThreadPullRequestsResult.Type; const LinkPullRequestTool = Tool.make("link_pull_request", { - description: "Link a MR to this thread. T3 shows its status and settles the thread on merge.", + description: + "Link a MR to this thread. T3 shows its status and settles the thread on merge. For several MRs, use `link_pull_requests`.", parameters: PullRequestTargetInput, success: LinkPullRequestResult, failure: PullRequestToolError, @@ -283,6 +315,24 @@ const LinkPullRequestTool = Tool.make("link_pull_request", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false); +const LinkPullRequestsTool = Tool.make("link_pull_requests", { + description: + "Link several MRs to a thread in one call. Use it instead of one `link_pull_request` per MR. URLs that are not MRs come back in `invalidUrls`.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })), + urls: Schema.Array(TrimmedNonEmptyString).check(Schema.isMinLength(1)), + }), + success: LinkPullRequestsResult, + failure: PullRequestToolError, + dependencies, +}) + .annotate(Tool.Title, "Link merge requests to thread") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, false) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false); + const UnlinkPullRequestTool = Tool.make("unlink_pull_request", { description: "Remove a MR link from this thread. Succeeds with `wasLinked=false` when it was not linked.", @@ -297,6 +347,24 @@ const UnlinkPullRequestTool = Tool.make("unlink_pull_request", { .annotate(Tool.Idempotent, true) .annotate(Tool.OpenWorld, false); +const UnlinkPullRequestsTool = Tool.make("unlink_pull_requests", { + description: + "Unlink every MR on a thread whose last known state (as `list_thread_pull_requests` shows) is in `states`, in one call. Use it instead of one `unlink_pull_request` per MR. MRs with no known state stay linked.", + parameters: Schema.Struct({ + environmentId: OrchestratorMcpEnvironmentTarget, + threadId: Schema.optional(ThreadId.annotate({ description: "Thread. Default: this thread." })), + states: Schema.Array(PullRequestState).check(Schema.isMinLength(1)), + }), + success: UnlinkPullRequestsResult, + failure: PullRequestToolError, + dependencies, +}) + .annotate(Tool.Title, "Unlink merge requests by state") + .annotate(Tool.Readonly, false) + .annotate(Tool.Destructive, true) + .annotate(Tool.Idempotent, true) + .annotate(Tool.OpenWorld, false); + const ListThreadPullRequestsTool = Tool.make("list_thread_pull_requests", { description: "List MRs linked to a thread, with last known state and stack order (bottom to top). Call only when you need that list. Never as an end-of-work check.", @@ -410,7 +478,9 @@ const ReadPullRequestGuideTool = Tool.make("read_pull_request_guide", { export const PullRequestsToolkit = Toolkit.make( LinkPullRequestTool, + LinkPullRequestsTool, UnlinkPullRequestTool, + UnlinkPullRequestsTool, ListThreadPullRequestsTool, WatchPullRequestTool, UnwatchPullRequestTool, diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index b1d34c91be8af..f968312437518 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -102,7 +102,12 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { }); const { task, threadId } = yield* scheduler .runNow({ id: input.taskId }) - .pipe(Effect.mapError(unavailable)); + .pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ code: "orchestration_error", message: error.message }), + ), + ); const scope = yield* McpInvocationContext.McpInvocationContext; return { taskId: task.id, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index a4cfd9b8bca74..cbf3ae7533d02 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1022,4 +1022,7 @@ describe("AcpRegistryAdapterV2", () => { assert.notInclude(text, "preview_"); }).pipe(Effect.provide(layerTest), Effect.scoped), ); + + // Coder: upstream's Copilot lost-session restart cases (#26651) are not carried; the adapter has + // no Copilot flavor. }); diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e8a921cb63141..1b942685680ee 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -1326,6 +1326,74 @@ describe("ClaudeAdapterV2 resume compaction", () => { assert.isFunction(callback); const canUseTool = openedOptions?.canUseTool; assert.isFunction(canUseTool); + const shellSafetyReason = + "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed"; + for (const [safetyIndex, { askRule, reason }] of [ + { askRule: false, reason: shellSafetyReason }, + { askRule: true, reason: shellSafetyReason }, + { + askRule: false, + reason: + "Dangerous rm operation on possibly-empty variable path: $TARGET\nUse a literal absolute path instead.", + }, + { askRule: false, reason: "This shell -c script runs rm and could not be checked" }, + { askRule: false, reason: "A permission rule denies a command in this shell -c script" }, + ].entries()) { + const safetyRequest = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "runtime_request.updated"), + Stream.runHead, + Effect.forkScoped, + ); + const safetySignal = yield* Effect.abortSignal; + const safetyDecision = yield* Effect.promise(() => + canUseTool!( + "Bash", + { command: "for pair in a b; do echo $pair; done" }, + { + signal: safetySignal, + toolUseID: `tool-shell-safety-${safetyIndex}`, + requestId: `request-shell-safety-${safetyIndex}`, + decisionReason: `\u001b[33m${reason}\u001b[39m`, + suppressAlwaysAllowRule: true, + ...(askRule + ? { + matchedAskRule: { + source: "userSettings" as const, + toolName: "Bash", + ruleContent: "*", + }, + } + : {}), + }, + ), + ).pipe(Effect.forkScoped); + const safety = yield* Effect.raceFirst( + Fiber.join(safetyDecision).pipe( + Effect.map((result) => ({ type: "decision", result }) as const), + ), + Fiber.join(safetyRequest).pipe( + Effect.map((event) => ({ type: "approval", event }) as const), + ), + ); + assert.equal(safety.type, askRule ? "approval" : "decision"); + if (safety.type === "decision") { + assert.equal(safety.result?.behavior, "deny"); + if (safety.result?.behavior === "deny") { + assert.include(safety.result.message, reason); + assert.notInclude(safety.result.message, "\u001b["); + } + } else if ( + Option.isSome(safety.event) && + safety.event.value.type === "runtime_request.updated" + ) { + yield* runtime.respondToRuntimeRequest({ + requestId: safety.event.value.runtimeRequest.id, + decision: "decline", + }); + assert.equal((yield* Fiber.join(safetyDecision))?.behavior, "deny"); + } + yield* Fiber.interrupt(safetyRequest); + } const longQuestion = `Choose a deployment target: ${"region ".repeat(80)}`; const questionRequestEvent = yield* runtime.events.pipe( Stream.filter((event) => event.type === "runtime_request.updated"), @@ -3735,6 +3803,32 @@ describe("ClaudeAdapterV2 background wake turns", () => { assert.equal((yield* Fiber.join(forwardedDecision))?.behavior, "deny"); yield* harness.offerAndWait(frame); } + const fallbackDecision = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + "Bash", + { command: "echo checked" }, + { + signal: new AbortController().signal, + toolUseID: "safety-check-after-downgrade", + requestId: "request-safety-check-after-downgrade", + decisionReason: + "Dangerous rm operation not ruled out — the shell may read this command differently than it was parsed", + }, + ), + ).pipe(Effect.forkScoped); + const fallbackFirst = yield* Effect.raceFirst( + Queue.take(harness.runtimeRequestReceipts).pipe( + Effect.map((event) => ({ type: "request", event }) as const), + ), + Fiber.join(fallbackDecision).pipe(Effect.map(() => ({ type: "decision" }) as const)), + ); + assert.equal(fallbackFirst.type, "request"); + if (fallbackFirst.type !== "request") return; + yield* harness.runtime.respondToRuntimeRequest({ + requestId: fallbackFirst.event.runtimeRequest.id, + decision: "decline", + }); + assert.equal((yield* Fiber.join(fallbackDecision))?.behavior, "deny"); yield* finish; const unrestrictedOptions = harness.getOpenedOptions(); yield* start(unrestricted); @@ -8595,6 +8689,126 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("lets the native SDK acknowledge Stop before closing its own query", () => + Effect.scoped( + Effect.gen(function* () { + let closes = 0; + let acknowledge = Effect.void; + const harness = yield* makeWakeHarnessWithOptions({ + interrupt: Effect.suspend(() => { + assert.equal(closes, 0); + return acknowledge; + }), + close: (messages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(Queue.shutdown(messages))), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("graceful-stop"), + text: "Work until stopped", + attachments: [], + }), + ); + acknowledge = harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000620", + result: "", + subtype: "error_during_execution", + errors: ["Error: Request was aborted."], + terminalReason: "aborted_streaming", + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ), + ); + const active = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + if (active?.type !== "provider_turn.updated") + return yield* Effect.die("Missing running native turn"); + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: active.providerTurn.id, + requestRuntimeRestart: true, + }); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + assert.equal(closes, 1); + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + + it.effect("bounds an unacknowledged native Stop and settles its turn once", () => + Effect.scoped( + Effect.gen(function* () { + let closes = 0; + const interruptStarted = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + interrupt: Deferred.succeed(interruptStarted, undefined).pipe( + Effect.andThen(Effect.never), + ), + close: (messages) => + Effect.sync(() => { + closes++; + }).pipe(Effect.andThen(Queue.shutdown(messages))), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("unacknowledged-stop"), + text: "Work until stopped", + attachments: [], + }), + ); + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ), + ); + const active = harness.events.find( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "running", + ); + if (active?.type !== "provider_turn.updated") + return yield* Effect.die("Missing running native turn"); + const stop = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: active.providerTurn.id, + requestRuntimeRestart: true, + }) + .pipe(Effect.forkChild); + yield* Deferred.await(interruptStarted); + assert.equal(closes, 0); + yield* TestClock.adjust("11 seconds"); + yield* Fiber.join(stop); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted"); + assert.equal(closes, 1); + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + it.effect("preserves settled background work until an explicit stop", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index b4eb808da7c5a..325923b3611bf 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -9658,6 +9658,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } satisfies PermissionResult; } + const activePermissionMode = + (yield* Ref.get(queryContext))?.permissionMode ?? context.queryPolicy.permissionMode; + const safetyReason = NodeUtil.stripVTControlCharacters( + callbackOptions.decisionReason ?? "", + ).trim(); + // The SDK omits the CLI's dangerousRemoval discriminator, so match its removal warnings. + if ( + toolName === "Bash" && + activePermissionMode === "bypassPermissions" && + callbackOptions.matchedAskRule === undefined && + (/^Dangerous rm(?:dir)?\b/i.test(safetyReason) || + safetyReason === "This shell -c script runs rm and could not be checked" || + safetyReason === "A permission rule denies a command in this shell -c script") + ) { + return { + behavior: "deny", + message: `Claude Code's removal safety check denied this command; the user did not reject it. The command did not run. Do not bypass the check by splitting the removal, putting it in a script, or using another tool or shell. If the warning below supplies a safe rewrite, use it and let the same check evaluate it. Otherwise continue the rest of the task without the removal and tell the user what you needed to delete and why. Warning: ${safetyReason}`, + toolUseID: callbackOptions.toolUseID, + } satisfies PermissionResult; + } + const requestKind = providerRequestKindFromClaudeTool(toolName); // The user approves the command itself; Claude's title and description only summarize it. const command = inputRecordValue(nativeToolInput, "command"); @@ -10633,7 +10654,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( next.add(turnInput.providerTurnId); return next; }); - yield* existing.query.interrupt; + yield* existing.query.interrupt.pipe(Effect.timeoutOption("10 seconds")); yield* existing.query.close.pipe(Effect.ignore); const closed = yield* Deferred.await(existing.closed).pipe( Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts index d9005e6b6402e..b5109cb99d930 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + ContextTransferId, MessageId, ProjectId, ProviderInstanceId, @@ -160,34 +161,56 @@ it.layer(layerTest)("ContextHandoffService legacy import", (it) => { ); }); -it("caps the side chat context block, keeping the newest parent items", () => { - const parentThreadId = ThreadId.make("thread:side-chat-parent"); - const digest = Array.from({ length: 60 }, (_, index) => - ContextHandoffService.summarizeDeltaItem( - importedItem({ +it.effect("caps the side chat context block without summarizing discarded parent history", () => + Effect.gen(function* () { + const parentThreadId = ThreadId.make("thread:side-chat-parent"); + let summarizedItems = 0; + const parentItems = Array.from({ length: 60 }, (_, index) => ({ + ...importedItem({ role: index % 2 === 0 ? "user" : "assistant", id: `parent-${index}`, text: `item-${index} ${"x".repeat(300)}`, ordinal: index, }), - )!, - ); - const context = ContextHandoffService.makeSideChatContext({ parentThreadId, digest }); + get text() { + summarizedItems++; + return `item-${index} ${"x".repeat(300)}`; + }, + })); + const service = yield* ContextHandoffService.ContextHandoffServiceV2; + const handoff = yield* service.prepareSideChatContext({ + parentThreadId, + threadId: ThreadId.make("thread:side-chat"), + targetRunId: RunId.make("run:side-chat"), + transferId: ContextTransferId.make("transfer:side-chat"), + toProviderThreadId: ProviderThreadId.make("provider-thread:side-chat"), + fromProviderInstanceId: ProviderInstanceId.make("codex"), + toProviderInstanceId: ProviderInstanceId.make("codex"), + coveredRunOrdinals: { from: 1, to: 1 }, + parentItems, + createdAt: DateTime.makeUnsafe(0), + }); + const context = handoff.summaryText; + assert.isBelow(summarizedItems, parentItems.length); - assert.include(context, "- Earlier items truncated."); - assert.notInclude(context, "item-0 "); - assert.include(context, "- Assistant: item-59 "); - assert.isAtMost(context.length, 8_000); - assert.isTrue( - context.endsWith( - `Use t3_thread_read on thread ${parentThreadId} to see the main thread's live state.`, - ), - ); + assert.include(context, "- Earlier items truncated."); + assert.notInclude(context, "item-0 "); + assert.include(context, "- Assistant: item-59 "); + assert.isAtMost(context.length, 8_000); + assert.isTrue( + context.endsWith( + `Use t3_thread_read on thread ${parentThreadId} to see the main thread's live state.`, + ), + ); - const framingOnly = ContextHandoffService.makeSideChatContext({ parentThreadId, digest: [] }); - assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread.")); - assert.notInclude(framingOnly, "Main thread activity"); -}); + const framingOnly = ContextHandoffService.makeSideChatContext({ + parentThreadId, + digest: [], + }); + assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread.")); + assert.notInclude(framingOnly, "Main thread activity"); + }).pipe(Effect.provide(layerTest)), +); it("covers the run range of a very long delta", () => { const runs = [ diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.ts index 67a474d963bb0..7eef0afefbc17 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts @@ -202,7 +202,7 @@ export const readForkHistoryItems = Effect.fn( ]; }); -export function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { +function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { switch (item.type) { case "user_message": return `- User: ${compactText(item.text)}`; @@ -244,10 +244,10 @@ function makeForkDeltaSummary(input: { const SIDE_CHAT_CONTEXT_MAX_CHARS = 8_000; -/** `digest` holds `summarizeDeltaItem` lines for parent items after the fork point, oldest first. */ +/** Oldest first; raw parent items are summarized only until the context cap is reached. */ export function makeSideChatContext(input: { readonly parentThreadId: ThreadId; - readonly digest: ReadonlyArray; + readonly digest: ReadonlyArray; }): string { const framing = "You are in a side chat beside the main thread. The main thread may still be running in the same worktree. Answer the user's questions; do not continue or redo the main thread's task."; @@ -255,19 +255,24 @@ export function makeSideChatContext(input: { const truncated = "- Earlier items truncated."; const footer = `Use t3_thread_read on thread ${input.parentThreadId} to see the main thread's live state.`; const kept: Array = []; + let omitted = false; // The cap covers the whole block, so the fixed lines are reserved before any digest line. let remaining = SIDE_CHAT_CONTEXT_MAX_CHARS - [framing, "", header, truncated, "", footer].join("\n").length; - for (const line of input.digest.toReversed()) { - if (line.length + 1 > remaining) break; + for (let index = input.digest.length - 1; index >= 0; index--) { + const item = input.digest[index]!; + const line = typeof item === "string" ? item : summarizeDeltaItem(item); + if (line === null) continue; + if (line.length + 1 > remaining) { + omitted = true; + break; + } kept.unshift(line); remaining -= line.length + 1; } return [ framing, - ...(kept.length === 0 - ? [] - : ["", header, ...(kept.length < input.digest.length ? [truncated] : []), ...kept]), + ...(kept.length === 0 ? [] : ["", header, ...(omitted ? [truncated] : []), ...kept]), "", footer, ].join("\n"); @@ -588,10 +593,7 @@ const makeContextHandoffService = Effect.fn("orchestrationV2.ContextHandoffServi summaryMessageId: null, summaryText: makeSideChatContext({ parentThreadId: input.parentThreadId, - digest: input.parentItems.flatMap((item) => { - const line = summarizeDeltaItem(item); - return line === null ? [] : [line]; - }), + digest: input.parentItems, }), createdByProviderInstanceId: null, createdAt: input.createdAt, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index f9485db4edc3e..c7bc6fc64b0ab 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -766,7 +766,8 @@ function followsCurrentConversation( message: OrchestrationV2ConversationMessage | undefined, ): boolean { return ( - message?.notification?.source.kind === "monitor" && !isBufferedProviderNotification(message) + message?.delegatedCompletion !== undefined || + (message?.notification?.source.kind === "monitor" && !isBufferedProviderNotification(message)) ); } @@ -775,7 +776,6 @@ function queuedRunModelSelection( run: OrchestrationV2Run, ): ModelSelection { const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); - // App-owned monitor updates follow the agent currently handling the thread. return followsCurrentConversation(message) ? projection.thread.modelSelection : run.modelSelection; @@ -2377,8 +2377,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const projection = yield* projectionStore .getThreadRecords( command.parentThreadId, - ["subagents", "runs", "messages", "nodes", "attempts", "turnItems"], - { turnItemTypes: [], messageRoles: ["user"] }, + ["subagents", "runs", "nodes", "attempts", "turnItems"], + { turnItemTypes: [] }, ) .pipe( Effect.mapError( @@ -2466,8 +2466,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return; } + const { messages } = yield* projectionStore + .getThreadRecords(command.parentThreadId, ["messages"], { + messageRoles: ["user"], + messageIds: [delivery.messageId], + }) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }), + ), + ); + const deliveryProjection = { ...projection, messages }; const remainingTaskIds = delivery.taskIds.filter((taskId) => taskId !== task.id); - const deliveryRun = completionDeliveryRun(projection, delivery); + const deliveryRun = completionDeliveryRun(deliveryProjection, delivery); const clearDelivery = remainingTaskIds.length === 0 && (deliveryRun === undefined || deliveryRun.status === "queued"); @@ -2504,7 +2515,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); return parentRun.id; } - const message = completionDeliveryMessage(projection, delivery); + const message = completionDeliveryMessage(deliveryProjection, delivery); if (message !== undefined) { yield* emitEvent({ type: "message.updated", @@ -4249,11 +4260,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const sourceProjection = yield* projectionStore .getThreadRecords(command.sourceThreadId, [ "runs", - "checkpoints", + ...(command.sourcePoint.type === "checkpoint" ? (["checkpoints"] as const) : []), "providerThreads", "providerTurns", "attempts", - "contextTransfers", ]) .pipe( Effect.mapError( @@ -9428,7 +9438,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events, effects, projection, - modelSelection: projection.thread.modelSelection, + modelSelection: queuedRun.modelSelection, targetRunId: command.targetRunId, messageId: queuedMessage.id, text: queuedMessage.text, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 069511b8e4dd8..cd92632ec7929 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -215,6 +215,71 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate return threadId; }); +it.effect("record reads filter notification sources without dropping matching message bodies", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* addRolledBackRecoveryCandidate("notification-filter"); + const now = yield* DateTime.now; + for (const [id, role, kind] of [ + ["ordinary", "user", null], + ["monitor", "user", "monitor"], + ["system", "user", "system"], + ["assistant-monitor", "assistant", "monitor"], + ] as const) { + yield* store.apply({ + id: EventId.make(`notification-filter:${id}`), + type: "message.updated", + threadId, + occurredAt: now, + payload: { + id: MessageId.make(id), + threadId, + runId: null, + nodeId: null, + createdBy: "agent", + creationSource: "server", + role, + text: `Complete body for ${id}`, + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + ...(kind === null + ? {} + : { + notification: { + source: { kind }, + outcome: "updated", + summary: "Background notification", + }, + }), + }, + }); + } + const matching = yield* store.getThreadRecords(threadId, ["messages"], { + messageRoles: ["user"], + monitorNotificationsOnly: true, + }); + assert.deepEqual( + matching.messages.map((message) => [message.id, message.text]), + [["monitor", "Complete body for monitor"]], + ); + assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 4); + assert.lengthOf( + (yield* store.getThreadRecords(threadId, ["messages"], { + monitorNotificationsOnly: true, + })).messages, + 2, + ); + assert.lengthOf( + (yield* store.getThreadRecords(threadId, ["messages"], { + monitorNotificationsOnly: false, + })).messages, + 4, + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("SQL queue readiness skips held runs without bypassing active work", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; @@ -2820,6 +2885,176 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { }), ); + it.effect("keeps an open question's row in the window after the run kept working", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + const threadId = ThreadId.make("thread:open-question-window"); + yield* projectionStore.apply({ + id: EventId.make("event:open-question-window:thread"), + type: "thread.created", + threadId, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project:open-question-window"), + title: "Open question window", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + }); + for (let ordinal = 10; ordinal <= 300; ordinal += 1) { + const id = `turn-item:open-question-window:${ordinal}`; + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id, + parent_item_id, ordinal, type, status, updated_at, payload_json + ) VALUES ( + ${id}, ${threadId}, NULL, NULL, NULL, NULL, NULL, ${ordinal}, + 'command_execution', 'completed', ${nowIso}, + ${encodeUnknownJsonString({ + id, + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: `command ${ordinal}`, + input: `echo ${ordinal}`, + output: "ok", + exitCode: 0, + startedAt: nowIso, + completedAt: nowIso, + updatedAt: nowIso, + type: "command_execution", + })} + ) + `; + } + const requestId = RuntimeRequestId.make("request:open-question-window"); + const nodeId = NodeId.make("node:open-question-window"); + const itemId = TurnItemId.make("turn-item:open-question-window:question"); + yield* projectionStore.apply({ + id: EventId.make("event:open-question-window:node"), + type: "node.updated", + threadId, + nodeId, + occurredAt: now, + payload: { + id: nodeId, + threadId, + runId: null, + parentNodeId: null, + rootNodeId: nodeId, + kind: "user_input_request", + status: "waiting", + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: requestId, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }, + }); + const request = { + id: requestId, + nodeId, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input" as const, + status: "pending" as const, + responseCapability: { type: "message" as const }, + createdAt: now, + resolvedAt: null, + }; + yield* projectionStore.apply({ + id: EventId.make("event:open-question-window:request"), + type: "runtime-request.updated", + threadId, + nodeId, + occurredAt: now, + payload: request, + }); + yield* projectionStore.apply({ + id: EventId.make("event:open-question-window:item"), + type: "turn-item.updated", + threadId, + nodeId, + occurredAt: now, + payload: { + id: itemId, + type: "user_input_request", + threadId, + runId: null, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 5, + status: "waiting", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + requestId, + responseMode: "message", + questions: [{ id: "choice", header: "Choice", question: "Continue?", options: [] }], + }, + }); + + const questionRows = (snapshot: { + readonly projection: { readonly turnItems: ReadonlyArray<{ readonly id: string }> }; + }) => snapshot.projection.turnItems.filter((item) => item.id === itemId).length; + const open = yield* projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 }); + assert.strictEqual(questionRows(open), 1); + const bounded = buildBoundedThreadProjection({ + policy: { ...THREAD_HISTORY_PAGE_POLICY, maxUserTurns: undefined, maxItems: 50 }, + projection: open.projection, + snapshotSequence: open.snapshotSequence, + }); + assert.strictEqual(questionRows(bounded), 1); + assert.isFalse( + bounded.projection.visibleTurnItems.some((row) => row.sourceItemId === itemId), + ); + + yield* projectionStore.apply({ + id: EventId.make("event:open-question-window:resolved"), + type: "runtime-request.updated", + threadId, + nodeId, + occurredAt: now, + payload: { ...request, status: "resolved", resolvedAt: now }, + }); + const answered = yield* projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 }); + assert.strictEqual(questionRows(answered), 0); + }), + ); + it.effect("scopes actionable provider state to the requested bounded thread", () => Effect.gen(function* () { const projectionStore = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 770f33a3e6342..3f96fe7d0818e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -330,6 +330,7 @@ export interface ProjectionRuntimeResponseContext { export interface ProjectionRecordFilter { readonly messageRoles?: ReadonlyArray; + readonly monitorNotificationsOnly?: boolean; readonly turnItemRunId?: RunId; readonly messageIds?: ReadonlyArray; readonly messageRunIds?: ReadonlyArray; @@ -2965,6 +2966,21 @@ export const layer: Layer.Layer = ) AND request.type = 'run_interrupt_request' UNION + -- An open question or approval stays in the window: clients + -- build the answer panel from its row, and a run that kept + -- working pushes the row out of the newest turns. + SELECT question.rowid AS item_rowid, question.ordinal, question.turn_item_id + FROM orchestration_v2_projection_runtime_requests AS pending + JOIN orchestration_v2_projection_turn_items AS question + ON question.node_id = pending.node_id + WHERE pending.thread_id = ${threadId} + AND pending.status = 'pending' + AND question.thread_id = ${threadId} + AND question.type IN ('user_input_request', 'approval_request') + AND ${window.rowLimit} > 0 + AND ${window.anchorItemId ?? null} IS NULL + AND ${window.requiredRunId ?? null} IS NULL + UNION SELECT latest.item_rowid, latest.ordinal, latest.turn_item_id FROM ( SELECT rowid AS item_rowid, ordinal, turn_item_id @@ -3421,6 +3437,7 @@ export const layer: Layer.Layer = WHERE thread_id = ${threadId} ${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`} ${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`} + ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``} ${filter?.messageRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageRunIds)}))`} ORDER BY created_at ASC, message_id ASC ` diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index d2224720b89f1..a318130500b3b 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -915,7 +915,9 @@ it.effect("continues a cut run past queued follow-ups, which stay held", () => ...cut, runs: [...cut.runs, queuedFollowUp], } as unknown as OrchestrationV2ThreadProjection); - assert.deepEqual(texts, ["Continue where you left off."]); + assert.deepEqual(texts, [ + "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it.", + ]); }), ); @@ -945,7 +947,9 @@ it.effect("continues a resumed queued run that ran after an earlier continuation ...cut, runs: [...cut.runs, finishedContinuation], } as unknown as OrchestrationV2ThreadProjection); - assert.deepEqual(texts, ["Continue where you left off."]); + assert.deepEqual(texts, [ + "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it.", + ]); }), ); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index e4d7ac2b7f900..8741fb7bc5993 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -30,7 +30,8 @@ import { restartContinuationNote, } from "./RestartBackgroundNote.ts"; -const CONTINUE_PROMPT = "Continue where you left off."; +const CONTINUE_PROMPT = + "Continue where you left off. Your last turn was cut short, so a command or other action it started may have finished or may still be running. Before you repeat one that changes state, confirm it did not take effect and is not still running; if you cannot tell, say so instead of repeating it."; const MAX_CONTINUATION_CHAIN = 3; const CONTINUATION_LOOP_WINDOW_MS = 5 * 60 * 1_000; diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index d4867a264ec9c..c09b7401df773 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1132,6 +1132,48 @@ it.effect("keeps a held commentary draft before the steer when turn end flushes ), ); +it.effect("steers a promoted queued message with the selection it was queued with", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "promote-queued-selection", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("queued"), + threadId, + messageId: MessageId.make("message:queued"), + text: "queued", + attachments: [], + modelSelection: composerSelection, + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["queued"]); + assert.deepEqual(projection.thread.modelSelection, composerSelection); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("keeps a queued message queued when promoted into a run that Stop reached", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index c410d6682da38..ed643c2ff1ab7 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -1,5 +1,6 @@ import { assert, it } from "@effect/vitest"; import { + CommandId, type ModelSelection, NodeId, RunId, @@ -82,7 +83,10 @@ function makeParentThread(): OrchestrationV2AppThread { } it("keeps a subagent child awake when its parent thread is snoozed", () => { - const parentThread = makeParentThread(); + const parentThread: OrchestrationV2AppThread = { + ...makeParentThread(), + titleRegeneration: { requestId: CommandId.make("command:parent-title"), startedAt: snoozedAt }, + }; const childProviderThreadId = ProviderThreadId.make("provider-thread:subagent-awake-child"); const parentNodeId = NodeId.make("node:subagent-parent"); const childThread = makeSubagentChildThread({ @@ -100,6 +104,7 @@ it("keeps a subagent child awake when its parent thread is snoozed", () => { assert.isNull(childThread.snoozedUntil); assert.isNull(childThread.snoozedAt); + assert.isNull(childThread.titleRegeneration); assert.equal(childThread.projectId, parentThread.projectId); assert.equal(childThread.runtimeMode, parentThread.runtimeMode); assert.equal(childThread.interactionMode, parentThread.interactionMode); diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 71d40332f2d7a..96c7263173f32 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -1,6 +1,8 @@ import { assert, it } from "@effect/vitest"; import { CheckpointId, + CheckpointRef, + CheckpointScopeId, CommandId, EventId, MessageId, @@ -17,6 +19,7 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Statement from "effect/sql/Statement"; import * as TestClock from "effect/testing/TestClock"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; @@ -865,6 +868,61 @@ const askSideChat = (threadId: ThreadId, commandId: string) => }); }); +it.effect("resolves an explicit checkpoint fork to its source run", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const parentId = ThreadId.make("checkpoint-fork-parent"); + const childId = ThreadId.make("checkpoint-fork-child"); + const runId = RunId.make("checkpoint-fork-run"); + const checkpointId = CheckpointId.make("checkpoint-fork-checkpoint"); + yield* createParent(parentId); + yield* writeParentRun({ + threadId: parentId, + runId, + ordinal: 1, + status: "completed", + text: "Work", + }); + yield* eventSink.write({ + events: [ + { + id: EventId.make("checkpoint-fork-captured"), + type: "checkpoint.captured", + threadId: parentId, + occurredAt: now, + payload: { + id: checkpointId, + threadId: parentId, + scopeId: CheckpointScopeId.make("checkpoint-fork-scope"), + runId, + nodeId: NodeId.make("checkpoint-fork-node"), + parentCheckpointId: null, + ordinalWithinScope: 1, + appRunOrdinal: 1, + ref: CheckpointRef.make("refs/t3/checkpoint-fork/1"), + status: "ready", + files: [], + capturedAt: now, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "thread.fork", + commandId: CommandId.make("checkpoint-fork"), + sourceThreadId: parentId, + targetThreadId: childId, + sourcePoint: { type: "checkpoint", checkpointId }, + createdBy: "user", + creationSource: "mcp", + }); + const child = yield* orchestrator.getThreadShell(childId); + assert.deepEqual(child?.forkedFrom, { type: "run", threadId: parentId, runId }); + }).pipe(Effect.provide(forkCases[0]!.layer)), +); + it.effect("a side chat of an idle parent still starts with the framing note", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -880,7 +938,22 @@ it.effect("a side chat of an idle parent still starts with the framing note", () stable: true, }); - yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId); + const reads: Array = []; + const recordReads: Statement.Transformer = (statement) => { + const [query] = statement.compile(); + if (/^\s*SELECT/i.test(query)) reads.push(query); + return Effect.succeed(statement); + }; + yield* forkSideChat("side-chat-idle-fork", parentId, sideChatId).pipe( + Effect.provideService(Statement.CurrentTransformer, recordReads), + ); + assert.isEmpty( + reads.filter( + (query) => + query.includes("FROM orchestration_v2_projection_checkpoints") || + query.includes("FROM orchestration_v2_projection_context_transfers"), + ), + ); yield* askSideChat(sideChatId, "side-chat-idle-first-message"); const started = yield* orchestrator.getThreadProjection(sideChatId); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 424762fd36b06..fcffd831f2971 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -941,7 +941,7 @@ const make = Effect.gen(function* () { const records = yield* getProjectThreadRecords( input, ["runs", "messages", "subagents", "providerThreads"], - { messageRoles: ["user"] }, + { messageRoles: ["user"], monitorNotificationsOnly: true }, ); const progress = delegatedTaskProgress(records); // A thread rolled back past all its work, with nothing left running, has no answer to wait for. diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index 526e0ed729e8d..28ac06b6c8153 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -571,6 +571,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const snapshotReads = yield* Queue.unbounded(); const candidateReads = yield* Ref.make>([]); const settings = yield* Ref.make(options.settings ?? DEFAULT_SERVER_SETTINGS); + const settingsReadCount = yield* Ref.make(0); const settingsChanges = yield* PubSub.unbounded(); const mergedPullRequests = yield* PubSub.unbounded(); const commands = yield* Ref.make>([]); @@ -640,7 +641,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: const serverSettings = ServerSettings.ServerSettingsService.of({ start: Effect.void, ready: Effect.void, - getSettings: Ref.get(settings), + getSettings: Ref.update(settingsReadCount, (count) => count + 1).pipe( + Effect.andThen(Ref.get(settings)), + ), updateSettings, updateProviderInstance: () => Effect.die("Unexpected provider mutation"), withSettingsSnapshot: (use) => Ref.get(settings).pipe(Effect.flatMap(use)), @@ -710,6 +713,7 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: activation, snapshots, snapshotReadCount, + settingsReadCount, snapshotReads, candidateReads, commands, @@ -746,6 +750,37 @@ const startHarness = Effect.fn("startThreadSettlementHarness")(function* ( }); describe("ThreadSettlementServiceV2 worker", () => { + it.effect("skips settings and PR decisions for recent branchless threads", () => + Effect.scoped( + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse(NOW)); + const threads = Array.from({ length: 32 }, (_, index) => + makeThread(`recent-${index}`, { + updatedAt: DateTime.makeUnsafe(NOW), + latestUserMessageAt: DateTime.makeUnsafe(Date.parse(NOW) - 2 * DAY_MS), + }), + ); + const fixture = yield* makeHarness({ + snapshot: makeSnapshot(threads), + settings: { ...DEFAULT_SERVER_SETTINGS, sidebarAutoSettleAfterDays: 3 }, + }); + yield* Effect.gen(function* () { + const service = yield* ThreadSettlementService.ThreadSettlementServiceV2; + yield* startHarness(service, fixture.activation, fixture.snapshotReads); + assert.deepEqual(yield* Ref.get(fixture.commands), []); + assert.deepEqual(yield* Ref.get(fixture.branchCalls), []); + assert.equal(yield* Ref.get(fixture.settingsReadCount), 2); + yield* fixture.updateSettings({ sidebarAutoSettleAfterDays: 1 }); + yield* Queue.take(fixture.snapshotReads); + yield* service.drain; + assert.deepEqual( + new Set((yield* Ref.get(fixture.commands)).map((command) => command.threadId)), + new Set(threads.map((thread) => thread.id)), + ); + }).pipe(Effect.provide(fixture.layer)); + }), + ), + ); it.effect("settles a merged pull request stored only in the thread links", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 6a3d4fffb0399..fa0bf3dff448e 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -364,11 +364,29 @@ export const make = Effect.gen(function* () { const lookupCandidates = (yield* Effect.forEach( candidates, - (thread) => settleThread(thread, null), + (thread) => { + const projectSettings = resolveProjectSettings(settings, thread.projectId).settings; + // Skip no-op decisions; actual settlement still reads fresh settings before dispatch. + const settledAt = resolveAutoSettlementAt({ + thread, + pullRequest: null, + nowMs, + autoSettleAfterDays: projectSettings.sidebarAutoSettleAfterDays, + autoSettleOnMerge: projectSettings.sidebarAutoSettleOnMerge, + autoSettleKeepPullRequests: projectSettings.sidebarAutoSettleKeepPullRequests, + }); + return settledAt === null ? Effect.succeed(thread) : settleThread(thread, null); + }, { concurrency: 8 }, )) .filter((thread) => thread !== null) - .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0); + .filter((thread) => visibleThreadPullRequests(thread.pullRequests ?? []).length === 0) + .filter( + (thread) => + thread.branch !== null || + thread.linkedPullRequest != null || + thread.branchPullRequest != null, + ); const lookupCwdByThreadId = new Map(); yield* Effect.forEach( lookupCandidates, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 8ac7490357c3e..e68b73e4b7ba8 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -5691,6 +5691,116 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect.each([ + { ...modelSelection, model: "gpt-5.5", options: [{ id: "reasoningEffort", value: "high" }] }, + { instanceId: alternateInstanceId, model: "gpt-5.5" }, + ])( + "starts a queued delegated completion on a selection set while it waited: %j", + (newerSelection) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make( + `runtime-layer-queued-delegated-completion-selection-${newerSelection.instanceId}`, + ); + const taskId = NodeId.make(`${threadId}:task`); + const completionMessageId = MessageId.make(`${threadId}:completion`); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + createdBy: "user", + creationSource: "web", + title: "Delegated completion selection", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: MessageId.make(`${threadId}:active`), + text: "Delegate a task", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:cohort`), + type: "run.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { + ...active, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { messageId: completionMessageId, generation: 1, taskIds: [taskId] }, + }, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:completion`), + threadId, + messageId: completionMessageId, + text: "Delegated task finished", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + delegatedCompletion: { parentRunId: active.id, generation: 1, taskIds: [taskId] }, + }); + yield* orchestrator.dispatch({ + type: "thread.model-selection.set", + commandId: CommandId.make(`${threadId}:select-newer`), + threadId, + modelSelection: newerSelection, + }); + const waiting = yield* orchestrator.getThreadProjection(threadId); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:completed`), + type: "run.updated", + threadId, + runId: active.id, + occurredAt: now, + payload: { + ...waiting.runs.find((run) => run.id === active.id)!, + status: "completed", + completedAt: now, + }, + }, + ], + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const delivered = after.runs.find((run) => run.userMessageId === completionMessageId)!; + assert.equal(delivered.status, "starting"); + assert.deepEqual(delivered.modelSelection, newerSelection); + assert.equal( + after.attempts.find((attempt) => attempt.id === delivered.activeAttemptId) + ?.providerInstanceId, + newerSelection.instanceId, + ); + assert.deepEqual(after.thread.modelSelection, newerSelection); + }), + ); + it.effect("keeps the queue after a user interrupts the active run", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index 7f1ea4db95d6f..03d056531a760 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -501,6 +501,29 @@ function isLocalProjectedRow( return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id); } +function pendingRequestIdsOf( + projection: Pick, +): ReadonlySet { + return new Set( + projection.runtimeRequests + .filter((request) => request.status === "pending") + .map((request) => String(request.id)), + ); +} + +// Clients build the answer panel of an open question or approval from its row, +// and a run that kept working pushes that row out of the newest turns. +function isRetainedDependency( + item: OrchestrationV2TurnItem, + pendingRequestIds: ReadonlySet, +): boolean { + return ( + item.type === "run_interrupt_request" || + ((item.type === "user_input_request" || item.type === "approval_request") && + pendingRequestIds.has(String(item.requestId))) + ); +} + /** Retain small requests outside the visible window; later result pages still need them for attempt/run reducers. */ function retainedInterruptRequestTurnItems( projection: OrchestrationV2ThreadProjection, @@ -513,9 +536,10 @@ function retainedInterruptRequestTurnItems( } } + const pendingRequestIds = pendingRequestIdsOf(projection); const retained: OrchestrationV2TurnItem[] = []; for (const item of projection.turnItems) { - if (item.type !== "run_interrupt_request") { + if (!isRetainedDependency(item, pendingRequestIds)) { continue; } if (visibleLocalIds.has(String(item.id))) { @@ -635,8 +659,9 @@ export function buildBoundedThreadProjection(input: { const dependencyReserve = (() => { let reserve = 0; + const pendingRequestIds = pendingRequestIdsOf(controlProjection); for (const item of controlProjection.turnItems) { - if (item.type === "run_interrupt_request") { + if (isRetainedDependency(item, pendingRequestIds)) { reserve += bytesOfJson(item); } } diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts index 2f21ea0a8a942..9b95422c4f5c1 100644 --- a/apps/server/src/persistence/Sqlite.ts +++ b/apps/server/src/persistence/Sqlite.ts @@ -41,7 +41,7 @@ const layerSetup = Layer.effectDiscard( yield* sql`DELETE FROM sqlite_stat1;`; yield* sql`ANALYZE sqlite_schema;`; } - }), + }).pipe(Effect.withSpan("Sqlite.setup")), ); export const layerFromPath = Effect.fn("makeSqlitePersistenceLive")(function* (dbPath: string) { diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index 4248e51b55977..0e3a3c67a7666 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -75,6 +75,7 @@ function candidate( model: modelSelection.model, createdAt: timestamp, updatedAt: timestamp, + omittedMessageCount: 0, messages: [ { role: "user" as const, text: "Fix it", createdAt: timestamp }, { role: "assistant" as const, text: "Fixed", createdAt: timestamp }, @@ -273,6 +274,7 @@ it.effect( "claudeAgent", ); const unowned = candidate(CODEX_MODEL_SELECTION, "unowned"); + unowned.thread.omittedMessageCount = 1; const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi"); const importer = yield* makeImporter([ active, @@ -307,9 +309,23 @@ it.effect( const threadId = importId(source); const records = yield* projections.getThreadRecords(threadId, [ "messages", + "turnItems", "providerThreads", ]); expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); + const notices = records.turnItems.filter((item) => item.type === "system_notice"); + if (source === unowned) { + expect(records.turnItems[0]).toBe(notices[0]); + expect(notices).toMatchObject([ + { + ordinal: 1, + runId: null, + message: expect.stringContaining("1 earlier message was not imported"), + }, + ]); + } else { + expect(notices).toEqual([]); + } expect(records.thread.historyOrigin).toBe("v1_import"); expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id); expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source)); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 038b488635053..a3f587c1c6d49 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -365,6 +365,34 @@ const make = Effect.gen(function* () { occurredAt: createdAt, payload: appThread, }, + ...(thread.omittedMessageCount > 0 + ? [ + { + id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + type: "turn-item.updated" as const, + threadId, + occurredAt: createdAt, + payload: { + id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt: createdAt, + completedAt: createdAt, + updatedAt: createdAt, + type: "system_notice" as const, + message: `${thread.omittedMessageCount} earlier ${thread.omittedMessageCount === 1 ? "message was" : "messages were"} not imported. This thread keeps the first user message and the most recent history. The original session transcript is unchanged.`, + }, + }, + ] + : []), ...thread.messages.flatMap((message, index) => messageEvents({ threadId, index, message }), ), diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 043b7ad1044b0..2c79aef7b8422 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1827,6 +1827,48 @@ describe("parseAgentSessionTranscript", () => { }, ); + it.each([199, 200, 201, 205])( + "counts only omitted conversation messages for a %s-message Claude transcript", + (count) => { + const thread = AgentSessionScanner.parseAgentSessionTranscript({ + contents: [ + ...Array.from({ length: count }, (_, index) => + encodeTranscriptRecord({ + type: index === 0 ? "user" : "assistant", + sessionId: "claude-session", + message: { content: `Message ${index}` }, + }), + ), + encodeTranscriptRecord({ type: "user", isMeta: true, message: { content: "Setup" } }), + encodeTranscriptRecord({ + type: "user", + isCompactSummary: true, + message: { content: "Summary" }, + }), + encodeTranscriptRecord({ + type: "assistant", + isSidechain: true, + message: { content: "Sidechain" }, + }), + encodeTranscriptRecord({ + type: "assistant", + message: { content: [{ type: "tool_use" }] }, + }), + "malformed", + ].join("\n"), + source: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + fallbackSessionId: "fallback", + lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), + }); + + expect(thread?.omittedMessageCount).toBe(Math.max(0, count - 200)); + expect(thread?.messages).toHaveLength(Math.min(200, count)); + expect(thread?.messages[0]?.text).toBe("Message 0"); + expect(thread?.messages.at(-1)?.text).toBe(`Message ${count - 1}`); + }, + ); + it("keeps Claude text and titles while dropping malformed and tool records", () => { const thread = AgentSessionScanner.parseAgentSessionTranscript({ contents: [ @@ -1978,10 +2020,10 @@ describe("parseAgentSessionTranscript", () => { ]); }); - it("keeps the canonical first prompt after long Codex transcripts are capped", () => { + it.each([199, 200])("keeps the canonical first prompt with %s later Codex messages", (count) => { const canonicalPrompt = "\n Keep the canonical prompt \n"; const canonicalTimestamp = "2026-08-24T10:01:00.000Z"; - const laterAssistantMessages = Array.from({ length: 200 }, (_, index) => + const laterAssistantMessages = Array.from({ length: count }, (_, index) => encodeTranscriptRecord({ type: "response_item", timestamp: `2026-08-24T11:${String(index % 60).padStart(2, "0")}:00.000Z`, @@ -2017,6 +2059,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); + expect(thread?.omittedMessageCount).toBe(count - 199); expect(thread?.messages).toHaveLength(200); expect(thread?.messages[0]).toMatchObject({ role: "user", @@ -2079,6 +2122,7 @@ describe("parseAgentSessionTranscript", () => { lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"), }); + expect(thread?.omittedMessageCount).toBe(1); expect(thread?.messages).toHaveLength(200); expect(thread?.messages[0]).toMatchObject({ role: "user", diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index f0a0627f3925e..10c94a5198751 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -171,6 +171,7 @@ export interface AgentSessionThread { readonly createdAt: string; readonly updatedAt: string; readonly messages: ReadonlyArray; + readonly omittedMessageCount: number; } export type AgentSessionRecentThread = @@ -465,6 +466,7 @@ function parseAgentSessionRecords( finishCodexTurn(); } + let conversationMessageCount = 0; const retainMessage = ( message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean }, ) => { @@ -474,6 +476,7 @@ function parseAgentSessionRecords( if (derivedTitle === undefined && message.role === "user") { derivedTitle = deriveTitle(input.source, message.text); } + conversationMessageCount += 1; messages.push(message); if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift(); }; @@ -545,6 +548,7 @@ function parseAgentSessionRecords( if (message?.codexResponseUser === true && message.text.trim() === text.trim()) { if (firstUserMessage === message) firstUserMessage = undefined; messages.splice(index, 1); + conversationMessageCount -= 1; break; } } @@ -599,6 +603,7 @@ function parseAgentSessionRecords( createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp, updatedAt: fallbackTimestamp, messages: retainedMessages, + omittedMessageCount: conversationMessageCount - retainedMessages.length, }; } diff --git a/apps/server/src/project/RepositoryIdentityResolver.test.ts b/apps/server/src/project/RepositoryIdentityResolver.test.ts index 2b5d9c62b4d54..1dee261c0302e 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.test.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.test.ts @@ -1,12 +1,35 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Duration from "effect/Duration"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import { TestClock } from "effect/testing"; import { ChildProcessSpawner } from "effect/process"; import * as ProcessRunner from "../processRunner.ts"; import { make } from "./RepositoryIdentityResolver.ts"; +// Coder: the mocked cases resolve made-up workspace paths, so every path reads as a folder holding +// the entries the resolver checks before it probes with Git (#27980). +const existingFolders = Layer.merge( + FileSystem.layerNoop({ + stat: () => Effect.succeed({ type: "Directory" } as FileSystem.File.Info), + exists: () => Effect.succeed(true), + }), + Path.layer, +); + +const git = (cwd: string, args: ReadonlyArray) => + Effect.gen(function* () { + const processRunner = yield* ProcessRunner.ProcessRunner; + return yield* processRunner.run({ + command: "git", + args: ["-C", cwd, ...args], + }); + }).pipe(Effect.provide(ProcessRunner.layer)); + function output(stdout: string): ProcessRunner.ProcessRunOutput { return { code: ChildProcessSpawner.ExitCode(0), @@ -33,6 +56,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); const identity = yield* resolver.resolve("/workspace/project/src"); @@ -61,6 +85,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); const first = yield* resolver.resolve("/workspace/project/src"); @@ -91,6 +116,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); expect(yield* resolver.resolve("/workspace/project/src")).toBeNull(); @@ -126,6 +152,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); const identity = yield* resolver.resolve("/workspace/project"); @@ -159,6 +186,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); const identity = yield* resolver.resolve("/workspace/project"); @@ -193,6 +221,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); expect(yield* resolver.resolve("/workspace/project")).toBeNull(); @@ -223,6 +252,7 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); const identity = yield* resolver.resolve(layout === "dot-bare" ? "/srv/smoke" : gitDir); @@ -247,9 +277,50 @@ describe("RepositoryIdentityResolver", () => { }); const resolver = yield* make().pipe( Effect.provideService(ProcessRunner.ProcessRunner, process), + Effect.provide(existingFolders), ); expect(yield* resolver.resolve("/workspace/project/.git")).toBeNull(); }), ); + + // Coder: upstream's case on real temporary folders, outside its `it.layer`. + it.effect( + "returns null for non-git, missing and no-remote folders, probing only what can exist", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nonGitDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-non-git-", + }); + const gitDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-repository-identity-no-remote-", + }); + + yield* git(gitDir, ["init"]); + + const runner = yield* ProcessRunner.ProcessRunner; + const runs: Array> = []; + const resolver = yield* make().pipe( + Effect.provideService(ProcessRunner.ProcessRunner, { + run: (input) => + Effect.suspend(() => { + runs.push(input.args); + return runner.run(input); + }), + }), + ); + const bareProbes = () => + runs.filter((args) => args.some((arg) => arg.startsWith("--git-dir="))); + + expect(yield* resolver.resolve(path.join(nonGitDir, "deleted"))).toBeNull(); + expect(runs).toEqual([]); + + expect(yield* resolver.resolve(nonGitDir)).toBeNull(); + expect(bareProbes()).toEqual([]); + + expect(yield* resolver.resolve(gitDir)).toBeNull(); + }).pipe(Effect.provide(ProcessRunner.layer), Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/project/RepositoryIdentityResolver.ts b/apps/server/src/project/RepositoryIdentityResolver.ts index 659ace3fd2b49..cdf9dc5e1b309 100644 --- a/apps/server/src/project/RepositoryIdentityResolver.ts +++ b/apps/server/src/project/RepositoryIdentityResolver.ts @@ -6,7 +6,9 @@ import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; import * as ProcessRunner from "../processRunner.ts"; import { sourceControlDefinitions } from "../sourceControl/sourceControlDefinitions.ts"; @@ -138,8 +140,18 @@ class RepositoryIdentityCacheKey extends Data.Class<{ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver.resolveCacheKey")( function* (cwd: string) { const processRunner = yield* ProcessRunner.ProcessRunner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const env = explicitBareRepositoryEnv(process.env, yield* HostProcess.Platform); + // `git -C` cannot enter a missing folder or a file, so every probe below would fail. + const isFolder = yield* fileSystem.stat(cwd).pipe( + Effect.map((info) => info.type === "Directory"), + Effect.catchReason("PlatformError", "NotFound", () => Effect.succeed(false)), + Effect.orElseSucceed(() => true), + ); + if (!isFolder) return null; + // git is always a real executable; cmd shell mode would split spaced paths on re-tokenization. const topLevelResult = yield* processRunner .run({ @@ -160,7 +172,25 @@ const resolveRepositoryIdentityCacheKey = Effect.fn("RepositoryIdentityResolver. } // Explicit Git directories preserve safe.bareRepository=explicit for both layouts. - for (const gitDir of [".", ".git"]) { + for (const [gitDir, entry] of [ + [".", "HEAD"], + [".git", ".git"], + ] as const) { + // An explicit --git-dir fails unless the folder has this entry; a symlink counts even + // when its target is missing, as git reads a symlinked HEAD's target text. + const target = path.join(cwd, entry); + const hasEntry = yield* fileSystem.exists(target).pipe( + Effect.flatMap((exists) => + exists + ? Effect.succeed(true) + : fileSystem.readLink(target).pipe( + Effect.as(true), + Effect.orElseSucceed(() => false), + ), + ), + Effect.orElseSucceed(() => true), + ); + if (!hasEntry) continue; const bareResult = yield* processRunner .run({ command: "git", @@ -224,6 +254,8 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( options: RepositoryIdentityResolverOptions = {}, ) { const processRunner = yield* ProcessRunner.ProcessRunner; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const cacheCapacity = options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY; const refine = options.refine ?? Effect.succeed; const timeToLive = (exit: Exit.Exit) => @@ -237,6 +269,8 @@ export const make = Effect.fn("RepositoryIdentityResolver.make")(function* ( (cwd) => resolveRepositoryIdentityCacheKey(cwd).pipe( Effect.provideService(ProcessRunner.ProcessRunner, processRunner), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), ), { capacity: cacheCapacity, timeToLive }, ); diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 72724f0adcbee..1599371245cb8 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -232,6 +232,7 @@ describe("ACP Registry probe", () => { { id: "medium", label: "Medium" }, { id: "high", label: "High" }, ], + role: "reasoning", }, ]); }); diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index 9b7d1ffb35d41..6f3e49e4d4c46 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -7,6 +7,7 @@ import { } from "@t3tools/contracts"; import { ServerProviderUpdateError } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -15,6 +16,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -755,6 +757,41 @@ describe("providerMaintenanceRunner", () => { ), ); + // A native updater such as `claude update` downloads a ~300 MB binary and + // prints nothing while it does. Killed mid-download, it leaves a truncated + // 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." }, + ] as const)("lets a slow installer run for $runFor", ({ runFor, status, message }) => { + const started = Deferred.makeUnsafe(); + return Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseNativeCliProvider); + const updater = yield* makeTestRunner(registry); + + const update = yield* updater.updateProvider(NATIVE_CLI_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(started); + yield* TestClock.adjust(runFor); + const result = yield* Fiber.join(update); + + assert.strictEqual(result.providers[0]?.updateState?.status, status); + assert.strictEqual(result.providers[0]?.updateState?.message, message); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("1.0.0"), + layerMockSpawner(() => ({ + exitCode: Deferred.succeed(started, undefined).pipe( + Effect.andThen(Effect.sleep(runFor)), + Effect.as(ChildProcessSpawner.ExitCode(0)), + ), + })), + ), + ), + ); + }); + it.effect("prevents concurrent updates for the same provider", () => { const startedLatch: { resolve: () => void } = { resolve: () => {} }; const releaseLatch: { resolve: () => void } = { resolve: () => {} }; @@ -856,17 +893,31 @@ describe("providerMaintenanceRunner", () => { ), ); - it.effect("resolves npm to a .cmd shim and routes through the shell on win32", () => { + it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { const captured: Array<{ readonly command: string; readonly args: ReadonlyArray; readonly shell: boolean | string | undefined; + readonly env: NodeJS.ProcessEnv | undefined; }> = []; return Effect.gen(function* () { const { registry } = yield* makeRegistry(baseProvider, { installedVersionAfterUpdate: "1.0.0", }); - const runner = yield* makeTestRunner(registry); + const runner = yield* makeTestRunner({ + ...registry, + getProviderMaintenanceCapabilitiesForInstance: () => + Effect.succeed( + makeProviderMaintenanceCapabilities({ + provider: CODEX_DRIVER, + packageName: "@openai/codex", + updateExecutable: "npm", + updateArgs: ["install", "-g", "@openai/codex@latest"], + updateLockKey: "npm-global", + env: { PATH: "C:\\fake\\npm" }, + }), + ), + }); const result = yield* runner.updateProvider(CODEX_DRIVER); @@ -879,17 +930,21 @@ describe("providerMaintenanceRunner", () => { ); assert.deepEqual(call.args, []); assert.strictEqual(call.shell, true); + assert.deepStrictEqual(call.env, { PATH: "C:\\fake\\npm" }); assert.strictEqual(result.providers[0]?.updateState?.status, "succeeded"); }).pipe( Effect.provide( Layer.mergeAll( Layer.succeed(HostProcess.Platform, "win32"), + // Only the provider's PATH has npm. Layer.succeed(HostProcess.Environment, { - PATH: "C:\\fake\\npm", + PATH: "C:\\Windows\\System32", PATHEXT: ".COM;.EXE;.BAT;.CMD", }), - Layer.succeed(SpawnExecutableResolution, (command) => - command === "npm" ? "C:\\fake\\npm\\npm.cmd" : undefined, + Layer.succeed(SpawnExecutableResolution, (command, _platform, env) => + command === "npm" && env.PATH === "C:\\fake\\npm" + ? "C:\\fake\\npm\\npm.cmd" + : undefined, ), layerLatestVersionHttpClient("1.0.0"), Layer.succeed( @@ -898,12 +953,16 @@ describe("providerMaintenanceRunner", () => { const childProcess = command as unknown as { readonly command: string; readonly args: ReadonlyArray; - readonly options: { readonly shell?: boolean | string | undefined }; + readonly options: { + readonly shell?: boolean | string | undefined; + readonly env?: NodeJS.ProcessEnv | undefined; + }; }; captured.push({ command: childProcess.command, args: childProcess.args, shell: childProcess.options.shell, + env: childProcess.options.env, }); return Effect.succeed(mockHandle({ stdout: "updated" })); }), diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index c2347da003300..ee7709e710eda 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -41,7 +41,11 @@ import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/ser import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); -const UPDATE_TIMEOUT_MS = 5 * 60_000; +// 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); @@ -98,13 +102,14 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR }) { const collectCommandResult = Effect.fn("ProviderMaintenanceRunner.collectCommandResult")( function* () { + const env = input.env ? { env: input.env, extendEnv: true } : {}; // Windows batch shims require shell dispatch through resolveSpawnCommand. - const resolved = yield* resolveSpawnCommand(input.command, input.args); + const resolved = yield* resolveSpawnCommand(input.command, input.args, env); const child = yield* input.spawner .spawn( ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell, - ...(input.env ? { env: input.env, extendEnv: true } : {}), + ...env, }), ) .pipe( @@ -259,7 +264,7 @@ function lastOutputLine(result: ProviderMaintenanceCommandResult): string | null function failureMessage(result: ProviderMaintenanceCommandResult): string { if (result.timedOut) { - return "Update timed out."; + return `Update timed out after ${UPDATE_TIMEOUT_MINUTES} minutes.`; } const summary = result.exitCode !== null && result.exitCode !== 0 diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts index a47743b34263a..92704c51102fe 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.test.ts @@ -152,6 +152,48 @@ describe("normalizeReviewGuide", () => { expect(result.stops).toHaveLength(1); }); + it("merges excerpts that a later excerpt bridges into one", () => { + const result = normalizeReviewGuide( + guide({ + stops: [ + stop({ + excerpts: [ + excerpt("src/a.ts", 40, 41), + { ...excerpt("src/a.ts", 50, 51), caption: "Second" }, + excerpt("src/a.ts", 41, 50), + ], + }), + ], + }), + change, + ); + expect(result.stops[0]?.excerpts).toEqual([ + { ...excerpt("src/a.ts", 40, 51), caption: "Second" }, + ]); + + const tailNote = { path: "src/a.ts", line: 40, title: "Tail", body: "Keep this note." }; + const wide = normalizeReviewGuide( + guide({ + stops: [ + stop({ + excerpts: [ + excerpt("src/a.ts", 1, 25), + { ...excerpt("src/a.ts", 30, 45), caption: "Second" }, + excerpt("src/a.ts", 24, 32), + ], + notes: [tailNote], + }), + ], + }), + parseReviewGuideChange( + "src/a.ts\0", + "diff --git a/src/a.ts b/src/a.ts\n--- a/src/a.ts\n+++ b/src/a.ts\n@@ -0,0 +1,60 @@\n+added", + ), + ); + expect(wide.stops[0]?.excerpts).toEqual([{ ...excerpt("src/a.ts", 1, 25), caption: "Second" }]); + expect(wide.stops[0]?.notes).toEqual([]); + }); + it("drops notes outside the stop's remaining excerpts", () => { const result = normalizeReviewGuide( guide({ diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts index 184908e4bd7f2..82edfc5fb8159 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideNormalize.ts @@ -87,26 +87,29 @@ function clampExcerpt( function mergeExcerpts( excerpts: ReadonlyArray, ): Array { - const merged: Array = []; + let merged: Array = []; for (const excerpt of excerpts) { - const index = merged.findIndex( - (other) => - other.path === excerpt.path && - other.side === excerpt.side && - other.start <= excerpt.end + 1 && - excerpt.start <= other.end + 1, - ); - const other = merged[index]; - if (other === undefined) { + const touches = (other: PullRequestReviewGuideExcerpt) => + other.path === excerpt.path && + other.side === excerpt.side && + other.start <= excerpt.end + 1 && + excerpt.start <= other.end + 1; + // An excerpt can bridge several earlier ones; fold them all into the first. + const group = merged.filter(touches); + const first = group[0]; + if (first === undefined) { merged.push(excerpt); continue; } - merged[index] = { - ...other, - start: Math.min(other.start, excerpt.start), - end: Math.max(other.end, excerpt.end), - caption: other.caption || excerpt.caption, + const combined = { + ...first, + start: Math.min(excerpt.start, ...group.map((other) => other.start)), + end: Math.max(excerpt.end, ...group.map((other) => other.end)), + caption: group.find((other) => other.caption)?.caption ?? excerpt.caption, }; + merged = merged.flatMap((other) => + other === first ? [combined] : touches(other) ? [] : [other], + ); } return merged.map((excerpt) => ({ ...excerpt, diff --git a/apps/server/src/scheduledTasks/Schedule.test.ts b/apps/server/src/scheduledTasks/Schedule.test.ts index f5973969747f7..0941c7392ff94 100644 --- a/apps/server/src/scheduledTasks/Schedule.test.ts +++ b/apps/server/src/scheduledTasks/Schedule.test.ts @@ -27,6 +27,12 @@ describe("scheduled task schedule calculation", () => { }); it("compares schedules structurally", () => { + expect( + isSameSchedule( + { type: "once", runAt: "2026-11-01T03:00:00-05:00" }, + { type: "once", runAt: "2026-11-01T08:00:00.000Z" }, + ), + ).toBe(true); expect( isSameSchedule({ type: "interval", everyMs: 60_000 }, { type: "interval", everyMs: 60_000 }), ).toBe(true); diff --git a/apps/server/src/scheduledTasks/Schedule.ts b/apps/server/src/scheduledTasks/Schedule.ts index bac32bb913146..f8fb648aaaaa9 100644 --- a/apps/server/src/scheduledTasks/Schedule.ts +++ b/apps/server/src/scheduledTasks/Schedule.ts @@ -1,5 +1,6 @@ import { MIN_SCHEDULED_TASK_INTERVAL_MS, type ScheduledTaskSchedule } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; const MINUTE_MS = 60_000; @@ -14,6 +15,13 @@ export function nextScheduledRunAt( from: DateTime.DateTime, ): DateTime.DateTime | null { if (schedule.type === "webhook") return null; + if (schedule.type === "once") { + const runAt = DateTime.make(schedule.runAt); + return Option.isSome(runAt) && + DateTime.toEpochMillis(runAt.value) > DateTime.toEpochMillis(from) + ? runAt.value + : null; + } if (schedule.type === "interval") { // Intervals advance elapsed time, including across daylight-saving changes. return DateTime.addDuration(from, Math.max(schedule.everyMs, MIN_SCHEDULED_TASK_INTERVAL_MS)); @@ -48,6 +56,7 @@ export function isSameSchedule(a: ScheduledTaskSchedule, b: ScheduledTaskSchedul return b.type === "interval" && a.everyMs === b.everyMs; } if (a.type === "webhook") return b.type === "webhook"; + if (a.type === "once") return b.type === "once" && Date.parse(a.runAt) === Date.parse(b.runAt); if (b.type !== "fixed_time") return false; // Compare parsed times so padded-hour edits do not reschedule pending runs. const aTime = parseTimeOfDay(a.timeOfDay); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts index 4a1a58505c5cb..c2cc1f382b68c 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.interval.test.ts @@ -4,6 +4,7 @@ import { ScheduledTaskUpsertInput } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; import * as TestClock from "effect/testing/TestClock"; import { afterEach, vi } from "vite-plus/test"; @@ -129,3 +130,185 @@ it.effect.each([ Effect.provide(SqlitePersistence.layerMemory), ), ); + +// Each launch takes two minutes, so a manual run can start before the run time and end after it. +const slowLaunchLayer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.merge( + dependencies, + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => TestClock.adjust("2 minutes").pipe(Effect.andThen(Effect.die("synthetic"))), + }), + ), + ), +); + +it.effect("runs a one-time schedule once and rejects past times", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z")); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const decoded = yield* decodeInput({ + ...input, + schedule: { type: "once", runAt: "2026-11-01T03:00:00-05:00" }, + }); + const created = yield* service.upsert(decoded); + expect(created.task.schedule).toEqual({ type: "once", runAt: "2026-11-01T08:00:00.000Z" }); + expect(created.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z"); + + // A manual run that starts before the time keeps the scheduled run, even if it ends after. + const early = yield* service.runNow({ id: created.task.id }); + expect(early.task.nextRunAt).toBe("2026-11-01T08:00:00.000Z"); + + const due = yield* service.runNow({ id: created.task.id }); + expect(due.task.nextRunAt).toBeNull(); + expect((yield* service.list()).tasks[0]?.nextRunAt).toBeNull(); + + yield* service.setEnabled({ id: created.task.id, enabled: false }); + const resumed = yield* service + .setEnabled({ id: created.task.id, enabled: true }) + .pipe(Effect.flip); + expect(resumed.message).toBe("The run time has passed. Pick a time in the future."); + + const past = yield* service + .upsert({ ...decoded, commandId: undefined, title: "Late" }) + .pipe(Effect.flip); + expect(past.message).toBe("The run time has passed. Pick a time in the future."); + }).pipe(Effect.provide(slowLaunchLayer)); + }).pipe( + Effect.provideService(ServerActivation, Effect.never), + Effect.provide(SqlitePersistence.layerMemory), + ), +); + +const ONCE = { type: "once", runAt: "2026-11-01T08:00:00Z" } as const; +/** A next run that only the simulated concurrent write produces. */ +const MOVED = "2030-01-01T00:00:00.000Z"; + +const onceInput = { + ...input, + commandId: "once-race", + schedule: { type: "once", runAt: "2026-11-01T08:00:00Z" }, +}; + +it.effect.each([ + { change: "a run completes", saved: ONCE, edited: ONCE, pause: false, expected: MOVED }, + { + change: "a run completes during a padded-time edit", + saved: { type: "fixed_time", timeOfDay: "9:00" }, + edited: { type: "fixed_time", timeOfDay: "09:00" }, + pause: false, + expected: MOVED, + }, + { + change: "another client pauses the task", + saved: ONCE, + edited: ONCE, + pause: true, + expected: "2026-11-01T08:00:00.000Z", + }, +] as const)( + "a title save keeps the stored next run only while nothing else changed: $change", + ({ saved, edited, pause, expected }) => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z")); + // The project check runs between the save's read and write, so it stands in for + // a concurrent write in that gap. + const writeMidSave = Layer.unwrap( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => + sql`UPDATE scheduled_tasks SET next_run_at = ${MOVED}, enabled = ${pause ? 0 : 1}`.pipe( + Effect.as(false), + Effect.orDie, + ), + }); + }), + ); + const layer = ScheduledTaskService.layer.pipe( + Layer.provide(Layer.merge(dependencies, writeMidSave)), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const worktree = { type: "worktree", baseRef: "main" }; + yield* service.upsert( + yield* decodeInput({ + ...onceInput, + schedule: saved, + workspaceStrategy: { type: "root" }, + }), + ); + const renamed = yield* service.upsert( + yield* decodeInput({ + ...onceInput, + schedule: edited, + workspaceStrategy: worktree, + title: "Renamed", + }), + ); + expect(renamed.task.enabled).toBe(true); + expect(renamed.task.nextRunAt).toBe(expected); + }).pipe(Effect.provide(layer)); + }).pipe( + Effect.provideService(ServerActivation, Effect.never), + Effect.provide(SqlitePersistence.layerMemory), + ), +); + +it.effect("keeps a one-time run after a restart interrupts an earlier manual run", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:59:00.000Z")); + const sql = yield* SqlClient.SqlClient; + const created = yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + return yield* service.upsert(yield* decodeInput(onceInput)); + }).pipe(Effect.provide(serviceLayer)); + yield* sql`UPDATE scheduled_tasks SET last_run_status = 'running', last_run_at = '2026-11-01T07:59:00.000Z'`; + + yield* TestClock.setTime(Date.parse("2026-11-01T08:05:00.000Z")); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const [task] = (yield* service.list()).tasks; + expect(task?.id).toBe(created.task.id); + expect(task?.lastRunStatus).toBe("failed"); + expect(task?.nextRunAt).toBe("2026-11-01T08:00:00.000Z"); + }).pipe(Effect.provide(serviceLayer)); + }).pipe( + Effect.provideService(ServerActivation, Effect.never), + Effect.provide(SqlitePersistence.layerMemory), + ), +); + +it.effect("reports the stored task when the row was replaced during the run", () => + Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-11-01T07:00:00.000Z")); + // The launch stands in for a delete and same-id recreate while the run is out. + const replaceRowDuringLaunch = Layer.unwrap( + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + return Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => + sql`UPDATE scheduled_tasks SET last_run_status = 'never', last_run_at = NULL, run_count = 0`.pipe( + Effect.orDie, + Effect.andThen(Effect.die("synthetic dispatch failure")), + ), + }); + }), + ); + const layer = ScheduledTaskService.layer.pipe( + Layer.provide(Layer.merge(dependencies, replaceRowDuringLaunch)), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const created = yield* service.upsert(yield* decodeInput(onceInput)); + const ran = yield* service.runNow({ id: created.task.id }); + expect(ran.task.runCount).toBe(0); + expect(ran.task.lastRunStatus).toBe("never"); + }).pipe(Effect.provide(layer)); + }).pipe( + Effect.provideService(ServerActivation, Effect.never), + Effect.provide(SqlitePersistence.layerMemory), + ), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index 82d165972750f..75650b55354b4 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -2,7 +2,7 @@ import * as Scheduler from "../scheduling/Scheduler.ts"; import * as NodeUtil from "node:util"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; -import { assert, it } from "@effect/vitest"; +import { assert, it, vi } from "@effect/vitest"; import { ProjectId, ProviderInstanceId, @@ -12,6 +12,7 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as SqlClient from "effect/sql/SqlClient"; @@ -476,3 +477,70 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", () }).pipe(Effect.provide(layer)); }).pipe(Effect.provide(SqlitePersistence.layerMemory)), ); + +it.effect("a run interrupted right after it reserves the task does not block the next run", () => + Effect.gen(function* () { + const launches = yield* Ref.make(0); + const layer = ScheduledTaskService.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadLaunchService.ThreadLaunchService)({ + launch: () => + Ref.update(launches, (n) => n + 1).pipe( + Effect.as({ threadId: ThreadId.make("thread:launched"), resumed: false } as never), + ), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + namedProjectsRoot: "/projects", + isScratchProject: () => Effect.succeed(false), + }), + NodeCrypto.layer, + Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }), + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* ScheduledTaskService.ScheduledTaskService; + const { task } = yield* service.upsert({ + id: ScheduledTaskId.make("task:interrupted-reservation"), + title: "Check in", + prompt: "Check progress", + enabled: true, + schedule: { type: "interval", everyMs: 60_000 }, + projectId: ProjectId.make("project:test"), + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + + // The reservation is the first Set.add of the task id; interrupt the run right there. + const add = Set.prototype.add; + let interrupted = false; + const first = yield* Effect.gen(function* () { + using _reserve = vi.spyOn(Set.prototype, "add").mockImplementation(function ( + this: Set, + value: unknown, + ) { + const result = add.call(this, value); + if (value === task.id && !interrupted) { + interrupted = true; + Fiber.getCurrent()?.interruptUnsafe(); + } + return result; + }); + return yield* service + .runNow({ id: task.id }) + .pipe(Effect.forkChild, Effect.flatMap(Fiber.await)); + }); + assert.isTrue(interrupted); + assert.isTrue(Exit.hasInterrupts(first)); + + const second = yield* service.runNow({ id: task.id }); + assert.equal(second.threadId, ThreadId.make("thread:launched")); + assert.equal(yield* Ref.get(launches), 1); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.provide(SqlitePersistence.layerMemory)), +); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 472102f031409..f25f260119b51 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -295,6 +295,35 @@ function nextRunAt( } } +/** + * Next run after an interrupted run. A one-time task counts from the run's start + * (`lastRunAt`), so a manual run that began before its time does not use it up. + */ +function nextRunAfterRun( + task: Pick, + now: DateTime.DateTime, +): string | null { + const startedAt = + task.schedule.type === "once" && task.lastRunAt !== null + ? DateTime.make(task.lastRunAt) + : Option.none(); + return nextRunAt( + task, + Option.getOrElse(startedAt, () => now), + ); +} + +/** An enabled one-time task with a past time would never run, so saving it is an error. */ +function requireFutureOnce( + task: Pick, + now: DateTime.DateTime, + taskId: ScheduledTaskId, +) { + return task.enabled && task.schedule.type === "once" && nextRunAt(task, now) === null + ? taskError("The run time has passed. Pick a time in the future.", { taskId }) + : Effect.void; +} + function errorMessage(error: unknown): string { if (Cause.isCause(error)) return Cause.pretty(error); if (error instanceof Error) return error.message; @@ -539,6 +568,8 @@ export const layer = Layer.effect( const saveTask = ( task: ScheduledTask, requireExisting: boolean, + /** The schedule this save read, when it left the schedule unchanged. */ + keptSchedule: ScheduledTask["schedule"] | null, webhook: { readonly token: string | null; readonly secret: string | null; @@ -609,7 +640,18 @@ export const layer = Layer.effect( interaction_mode = excluded.interaction_mode, creation_source = excluded.creation_source, updated_at = excluded.updated_at, - next_run_at = excluded.next_run_at, + -- Keep a next_run_at that a finishing run moved during this save, unless + -- another edit changed the schedule or enabled state meanwhile. + next_run_at = CASE + WHEN ${keptSchedule === null ? 0 : 1} = 1 + AND scheduled_tasks.schedule_json IN ( + excluded.schedule_json, + ${keptSchedule === null ? null : JSON.stringify(keptSchedule)} + ) + AND scheduled_tasks.enabled = excluded.enabled + THEN scheduled_tasks.next_run_at + ELSE excluded.next_run_at + END, -- Only rotate changes a live token, so a save racing a rotation -- cannot bring the old URL back. webhook_token = CASE @@ -682,7 +724,9 @@ export const layer = Layer.effect( WHERE task_id = ${input.id} AND last_run_status = 'running' AND last_run_at = ${input.startedAtIso} + RETURNING task_id `.pipe( + Effect.map((rows) => rows.length > 0), Effect.mapError((cause) => taskError("Could not record schedule task run.", { taskId: input.id, cause }), ), @@ -692,7 +736,12 @@ export const layer = Layer.effect( // runDueTasks skips 'running' rows forever, and the dispatch may already have gone out, // so next_run_at must advance. Pending webhook attempts count only with their completion. const releaseStuckRun = Effect.fn("ScheduledTaskService.releaseStuckRun")( - function* (task: ScheduledTask, message: string, pendingDeliveryId?: string) { + function* ( + task: ScheduledTask, + startedAtIso: string, + message: string, + pendingDeliveryId?: string, + ) { const now = yield* localNow; const reread = yield* Effect.result(findTask(task.id)); if (Result.isSuccess(reread) && reread.success === null) return; @@ -701,7 +750,7 @@ export const layer = Layer.effect( UPDATE scheduled_tasks SET last_run_status = 'failed', last_run_error = ${message}, - next_run_at = ${nextRunAt(source, now)}, + next_run_at = ${nextRunAfterRun({ ...source, lastRunAt: startedAtIso }, now)}, updated_at = ${iso(now)}, run_count = run_count + CASE WHEN EXISTS ( SELECT 1 FROM scheduled_task_webhook_pending @@ -711,7 +760,7 @@ export const layer = Layer.effect( `; yield* notifyChanged; }, - (effect, task, _message, _pendingDeliveryId) => + (effect, task, _startedAtIso, _message, _pendingDeliveryId) => effect.pipe( Effect.catch((cause) => Effect.logWarning("Could not release stuck schedule task run", { @@ -731,23 +780,10 @@ export const layer = Layer.effect( readonly dispatched: Ref.Ref; }, ) { - const reserved = yield* Ref.modify(activeRuns, (active) => { - if (active.has(task.id)) return [false, active] as const; - const next = new Set(active); - next.add(task.id); - return [true, next] as const; - }); - if (!reserved) { - if (trigger !== "scheduled") { - return yield* taskError("Schedule task is already running.", { taskId: task.id }); - } - return { task, threadId: null }; - } - - return yield* Effect.gen(function* () { - const startedAt = yield* localNow; - const startedAtIso = iso(startedAt); - + // Read before reserving: nothing between the reservation and its release may fail. + const startedAt = yield* localNow; + const startedAtIso = iso(startedAt); + const run = Effect.gen(function* () { // Re-read stale poll snapshots so deleted, paused or postponed tasks cannot fire. const active = yield* findTask(task.id); if (active === null) { @@ -759,7 +795,7 @@ export const layer = Layer.effect( if (trigger !== "scheduled") { return yield* taskError("Schedule task not found.", { taskId: task.id }); } - return { task, threadId: null }; + return { task, threadId: null, dispatchFailed: false }; } if ( webhook !== undefined && @@ -767,7 +803,11 @@ export const layer = Layer.effect( NodeSqliteClient.readOnly, )).length > 0 ) - return { task: { ...active, lastRunStatus: "succeeded" as const }, threadId: null }; + return { + task: { ...active, lastRunStatus: "succeeded" as const }, + threadId: null, + dispatchFailed: false, + }; const parsedNextRunAt = active.nextRunAt === null ? Option.none() : DateTime.make(active.nextRunAt); if ( @@ -776,7 +816,7 @@ export const layer = Layer.effect( Option.isNone(parsedNextRunAt) || DateTime.toEpochMillis(parsedNextRunAt.value) > DateTime.toEpochMillis(startedAt)) ) { - return { task: active, threadId: null }; + return { task: active, threadId: null, dispatchFailed: false }; } // Reject queued deliveries after pause, same-id recreation or trigger changes. if (webhook !== undefined) { @@ -892,18 +932,28 @@ export const layer = Layer.effect( const lastRunStatus = runSucceeded ? ("succeeded" as const) : ("failed" as const); const lastRunError = runSucceeded ? null : errorMessage(result.cause); const threadId = runSucceeded ? result.value : null; - const current = yield* findTask(task.id); - const scheduleSource = current ?? task; - const completed: ScheduledTask = { - ...scheduleSource, - updatedAt: iso(completedAt), - lastRunAt: startedAtIso, - nextRunAt: nextRunAt(scheduleSource, completedAt), - lastRunStatus, - lastRunError, - runCount: scheduleSource.runCount + 1, - }; - if (current !== null) { + // One transaction, so an edit cannot land between reading the schedule and + // writing the next run computed from it. The origin is read first: it reads + // files, and the transaction holds SQLite's writer lock. + const origin = yield* readWebhookOrigin; + const record = Effect.gen(function* () { + const [row] = yield* getRows(task.id); + const current = row === undefined ? null : yield* decodeRow(row, origin); + const scheduleSource = current ?? task; + const completed: ScheduledTask = { + ...scheduleSource, + updatedAt: iso(completedAt), + lastRunAt: startedAtIso, + // A manual run that starts before a one-time run must not use it up. + nextRunAt: nextRunAt( + scheduleSource, + scheduleSource.schedule.type === "once" ? startedAt : completedAt, + ), + lastRunStatus, + lastRunError, + runCount: scheduleSource.runCount + 1, + }; + if (current === null) return { recorded: completed, written: false }; // startedAtIso in the guard ensures this writes only to the row this // run marked as running — a task deleted mid-run and recreated with // the same id (idempotent commandId replay) must not be stamped. @@ -915,40 +965,68 @@ export const layer = Layer.effect( error: lastRunError, startedAtIso, }); - if (webhook === undefined) yield* completion; - else - yield* sql - .withTransaction( - Effect.gen(function* () { - const pending = - yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`; - if (pending.length === 0) yield* completion; - else { - const counted = - yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"} - WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`; - if (counted.length > 0) yield* completion; - } - }), - ) - .pipe( - Effect.mapError((cause) => - taskError("Could not record webhook completion.", { taskId: task.id, cause }), - ), - ); - yield* notifyChanged; - } - return { task: completed, threadId }; + let written = false; + if (webhook === undefined) written = yield* completion; + else { + const pending = + yield* sql`SELECT 1 FROM scheduled_task_webhook_pending WHERE delivery_id = ${webhook.deliveryId}`; + if (pending.length === 0) written = yield* completion; + else { + const counted = + yield* sql`UPDATE scheduled_task_webhook_pending SET state = ${runSucceeded ? "completed" : "failed"} + WHERE delivery_id = ${webhook.deliveryId} AND state NOT IN ('completed', 'failed') RETURNING delivery_id`; + if (counted.length > 0) written = yield* completion; + } + } + // A row recreated mid-run is not this run's, so report what is stored. + return { recorded: written ? completed : current, written }; + }); + const { recorded, written } = yield* sql + .withTransaction(record) + .pipe( + Effect.mapError((cause) => + isScheduledTaskError(cause) + ? cause + : taskError( + webhook === undefined + ? "Could not record schedule task run." + : "Could not record webhook completion.", + { taskId: task.id, cause }, + ), + ), + ); + if (written) yield* notifyChanged; + // The stored row can belong to a replacement, so report this dispatch separately. + return { task: recorded, threadId, dispatchFailed: !runSucceeded }; }).pipe( - Effect.onError((cause) => releaseStuckRun(task, errorMessage(cause), webhook?.deliveryId)), - Effect.ensuring( - Ref.update(activeRuns, (active) => { - const next = new Set(active); - next.delete(task.id); - return next; - }), + Effect.onError((cause) => + releaseStuckRun(task, startedAtIso, errorMessage(cause), webhook?.deliveryId), ), ); + + // Reserve and release as one bracket so an interrupt cannot leave the task marked busy. + return yield* Effect.acquireUseRelease( + Ref.modify(activeRuns, (active) => { + if (active.has(task.id)) return [false, active] as const; + const next = new Set(active); + next.add(task.id); + return [true, next] as const; + }), + (reserved) => + reserved + ? run + : trigger !== "scheduled" + ? Effect.fail(taskError("Schedule task is already running.", { taskId: task.id })) + : Effect.succeed({ task, threadId: null, dispatchFailed: false }), + (reserved) => + reserved + ? Ref.update(activeRuns, (active) => { + const next = new Set(active); + next.delete(task.id); + return next; + }) + : Effect.void, + ); }); const rescheduleMissedRun = Effect.fn("ScheduledTaskService.rescheduleMissedRun")(function* ( @@ -1036,7 +1114,7 @@ export const layer = Layer.effect( UPDATE scheduled_tasks SET last_run_status = 'failed', last_run_error = 'Run was interrupted by a server restart.', - next_run_at = ${nextRunAt(decoded.success, now)}, + next_run_at = ${nextRunAfterRun(decoded.success, now)}, updated_at = ${iso(now)}, run_count = run_count + CASE WHEN EXISTS ( SELECT 1 FROM scheduled_task_webhook_pending @@ -1147,7 +1225,9 @@ export const layer = Layer.effect( : undefined), ), } - : input.schedule; + : input.schedule.type === "once" + ? { type: "once", runAt: iso(DateTime.makeUnsafe(input.schedule.runAt)) } + : input.schedule; const webhook = input.schedule.type === "webhook" ? yield* Effect.gen(function* () { @@ -1193,6 +1273,8 @@ export const layer = Layer.effect( existingTask !== null && existingTask.enabled === input.enabled && isSameSchedule(existingTask.schedule, schedule); + if (!scheduleUnchanged) + yield* requireFutureOnce({ enabled: input.enabled, schedule }, now, id); const task: ScheduledTask = { id, title: input.title, @@ -1217,7 +1299,12 @@ export const layer = Layer.effect( lastRunError: existingTask?.lastRunError ?? null, runCount: existingTask?.runCount ?? 0, }; - yield* saveTask(task, input.requireExisting === true, webhook); + yield* saveTask( + task, + input.requireExisting === true, + scheduleUnchanged ? existingTask.schedule : null, + webhook, + ); yield* notifyChanged; return { task: (yield* findTask(id)) ?? task }; }); @@ -1228,6 +1315,11 @@ export const layer = Layer.effect( const existing = yield* loadTask(input.id); if (existing.enabled === input.enabled) return { task: existing }; const now = yield* localNow; + yield* requireFutureOnce( + { enabled: input.enabled, schedule: existing.schedule }, + now, + input.id, + ); const next = nextRunAt({ enabled: input.enabled, schedule: existing.schedule }, now); // RETURNING so a task deleted between the load and this UPDATE is a // visible not-found error, not a false success. @@ -1663,8 +1755,8 @@ export const layer = Layer.effect( Effect.annotateCurrentSpan({ "scheduled_task.webhook.run_outcome": outcome }); const dispatched = yield* Ref.make(false); return yield* runTask(task, "webhook", { deliveryId, prompt, dispatched }).pipe( - Effect.flatMap(({ task: completed }) => - completed.lastRunStatus === "failed" + Effect.flatMap(({ dispatchFailed }) => + dispatchFailed ? runOutcome("failed").pipe( Effect.andThen(markDeliveryFailed(deliveryId, "The run failed to start.")), Effect.andThen(releaseFailedDelivery(deliveryId)), @@ -2147,83 +2239,87 @@ export const layer = Layer.effect( } yield* Effect.forEach( tasks, - ({ task_id: taskId }) => - Effect.gen(function* () { - const reserved = yield* Ref.modify(pendingInFlight, (active) => - active.has(taskId) - ? ([false, active] as const) - : ([true, new Set(active).add(taskId)] as const), - ); - if (!reserved) return; - const permit = yield* webhookPermit(taskId); - // One worker per task waits on its permit, then drains persisted rows in order. - // Other tasks remain independent and ticks never reload an active task's payloads. - const dispatch = Effect.gen(function* () { - while (true) { - const [entry] = yield* sql<{ - delivery_id: string; - task_json: string; - request_json: string; - state: string; - }>` + ({ task_id: taskId }) => { + // One worker per task waits on its permit, then drains persisted rows in order. + // Other tasks remain independent and ticks never reload an active task's payloads. + const dispatch = Effect.gen(function* () { + while (true) { + const [entry] = yield* sql<{ + delivery_id: string; + task_json: string; + request_json: string; + state: string; + }>` SELECT delivery_id, task_json, request_json, state FROM scheduled_task_webhook_pending WHERE task_id = ${taskId} AND state IN ('dispatching', 'running', 'completed', 'failed') ORDER BY due_at, rowid LIMIT 1 `.pipe(NodeSqliteClient.readOnly); - if (entry === undefined) return; - const remove = sql`DELETE FROM scheduled_task_webhook_pending WHERE delivery_id = ${entry.delivery_id}`; - if (entry.state === "completed" || entry.state === "failed") { - if (entry.state === "failed") { - yield* markDeliveryFailed(entry.delivery_id, "The run failed to start."); - yield* releaseFailedDelivery(entry.delivery_id); - } - yield* remove; - continue; - } - const prepared = yield* Effect.gen(function* () { - const task = yield* decodePendingTask(entry.task_json); - const request = yield* decodePendingRequest(entry.request_json); - const frameId = Buffer.from(yield* crypto.randomBytes(6)).toString("hex"); - return { task, rendered: renderWebhookPrompt(task.prompt, request, frameId) }; - }).pipe(Effect.exit); - if (Exit.isFailure(prepared)) { - if (Cause.hasInterruptsOnly(prepared.cause)) - return yield* Effect.failCause(prepared.cause); - yield* markDeliveryFailed( - entry.delivery_id, - "The pending webhook payload could not be prepared.", - ); + if (entry === undefined) return; + const remove = sql`DELETE FROM scheduled_task_webhook_pending WHERE delivery_id = ${entry.delivery_id}`; + if (entry.state === "completed" || entry.state === "failed") { + if (entry.state === "failed") { + yield* markDeliveryFailed(entry.delivery_id, "The run failed to start."); yield* releaseFailedDelivery(entry.delivery_id); - yield* remove; - continue; - } - const { task, rendered } = prepared.value; - if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { - yield* markDeliveryFailed(entry.delivery_id, PROMPT_TOO_LONG); - yield* releaseFailedDelivery(entry.delivery_id); - } else { - yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; - if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) - return; } yield* remove; + continue; } - }); - yield* dispatch.pipe( - permit.withPermits(1), - Effect.catch((cause) => - Effect.logWarning("Pending webhook dispatch failed", { cause }), - ), - Effect.ensuring( - Ref.update(pendingInFlight, (active) => { - const next = new Set(active); - next.delete(taskId); - return next; - }), - ), - Effect.withSpan("ScheduledTaskService.dispatchPendingWebhook", { root: true }), - Effect.forkIn(serviceScope), - ); - }), + const prepared = yield* Effect.gen(function* () { + const task = yield* decodePendingTask(entry.task_json); + const request = yield* decodePendingRequest(entry.request_json); + const frameId = Buffer.from(yield* crypto.randomBytes(6)).toString("hex"); + return { task, rendered: renderWebhookPrompt(task.prompt, request, frameId) }; + }).pipe(Effect.exit); + if (Exit.isFailure(prepared)) { + if (Cause.hasInterruptsOnly(prepared.cause)) + return yield* Effect.failCause(prepared.cause); + yield* markDeliveryFailed( + entry.delivery_id, + "The pending webhook payload could not be prepared.", + ); + yield* releaseFailedDelivery(entry.delivery_id); + yield* remove; + continue; + } + const { task, rendered } = prepared.value; + if (rendered.prompt.trim().length > PROVIDER_SEND_TURN_MAX_INPUT_CHARS) { + yield* markDeliveryFailed(entry.delivery_id, PROMPT_TOO_LONG); + yield* releaseFailedDelivery(entry.delivery_id); + } else { + yield* sql`UPDATE scheduled_task_webhook_deliveries SET outcome = 'accepted', error = NULL, rendered_prompt = ${rendered.prompt.slice(0, WEBHOOK_DELIVERY_LOG_PROMPT_LIMIT)}, missing_fields_json = ${encodeMissingFieldsJson(rendered.missing)} WHERE delivery_id = ${entry.delivery_id}`; + if (!(yield* runWebhookDelivery(task, entry.delivery_id, rendered.prompt))) return; + } + yield* remove; + } + }); + // The worker owns its reservation, so an interrupt anywhere still releases it. + return Effect.acquireUseRelease( + Ref.modify(pendingInFlight, (active) => + active.has(taskId) + ? ([false, active] as const) + : ([true, new Set(active).add(taskId)] as const), + ), + (reserved) => + reserved + ? webhookPermit(taskId).pipe( + Effect.flatMap((permit) => dispatch.pipe(permit.withPermits(1))), + Effect.catch((cause) => + Effect.logWarning("Pending webhook dispatch failed", { cause }), + ), + Effect.withSpan("ScheduledTaskService.dispatchPendingWebhook", { + root: true, + }), + ) + : Effect.void, + (reserved) => + reserved + ? Ref.update(pendingInFlight, (active) => { + const next = new Set(active); + next.delete(taskId); + return next; + }) + : Effect.void, + ).pipe(Effect.forkIn(serviceScope)); + }, { discard: true }, ); }); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts index cdd4e60e62d76..aaeb374bd0dd4 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.webhook.test.ts @@ -12,6 +12,7 @@ import * as DateTime from "effect/DateTime"; import * as Crypto from "effect/Crypto"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; @@ -1005,6 +1006,57 @@ it.effect("recovers a persisted coalescing window after restarting the service", ); }); +it.effect("a pending dispatch interrupted at its permit does not block later polls", () => { + const workers = new Map>(); + // One shared dispatcher lets the test run the retry's forked worker to completion. + const mixed = new EffectScheduler.MixedScheduler("sync"); + const dispatcher = mixed.makeDispatcher(); + return withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert( + yield* webhookTaskInput({ + schedule: { + type: "webhook", + dedupe: { coalesceKey: "{{headers.content-type}}", coalesceWindowSeconds: 10 }, + }, + }), + ); + yield* service.triggerWebhook(requestFor(task)); + yield* TestClock.adjust("10 seconds"); + const poll = workers.get("webhook-coalescing")!; + + const entered = yield* Deferred.make>(); + const interruptAtPermit = Tracer.make({ + span: (options) => { + if (options.name === "ScheduledTaskService.webhookPermit") { + const fiber = Fiber.getCurrent()!; + Deferred.doneUnsafe(entered, Effect.succeed(fiber)); + fiber.interruptUnsafe(); + } + return new Tracer.NativeSpan(options); + }, + }); + const firstPoll = yield* poll.pipe(Effect.withTracer(interruptAtPermit), Effect.forkChild); + assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(yield* Deferred.await(entered)))); + yield* Fiber.await(firstPoll); + + yield* poll; + dispatcher.flush(); + + assert.equal(yield* Queue.size(launches), 1); + assert.lengthOf(yield* sql`SELECT 1 FROM scheduled_task_webhook_pending`, 0); + }), + { workers }, + ).pipe( + Effect.provideService(EffectScheduler.Scheduler, { + executionMode: mixed.executionMode, + makeDispatcher: () => dispatcher, + shouldYield: (fiber) => mixed.shouldYield(fiber), + }), + ); +}); + it.effect("rolls back replay and pending state when recording a delivery fails", () => { const workers = new Map>(); return withService( @@ -1199,6 +1251,32 @@ it.effect("start failures release both replay keys and relay claims for redelive ), ); +it.effect("a start failure releases the relay claim when the task row is replaced mid-run", () => + Effect.gen(function* () { + const gate = yield* Deferred.make(); + yield* withService( + ({ service, sql, launches }) => + Effect.gen(function* () { + const { task } = yield* service.upsert(yield* webhookTaskInput()); + const request = requestFor(task, { relayDeliveryId: "replaced-mid-run" }); + const first = yield* waitForSpan( + service.triggerWebhook(request), + "ScheduledTaskService.runWebhookDelivery", + ).pipe(Effect.forkChild); + yield* Queue.take(launches); + // A same-id recreate while the launch is out: the stored row is no longer this run's. + yield* sql`UPDATE scheduled_tasks SET last_run_status = 'never', last_run_at = NULL`; + yield* Deferred.succeed(gate, undefined); + yield* Fiber.join(first); + const retry = yield* service.triggerWebhook(request); + assert.equal(retry._tag === "accepted" && retry.outcome, "accepted"); + yield* Queue.take(launches); + }), + { gate, failLaunches: { remaining: 1 } }, + ); + }), +); + it.effect("main retention keeps fifty runs and preserves filtered and dedupe buckets", () => withService(({ service, sql, launches }) => Effect.gen(function* () { diff --git a/apps/server/src/scheduledTasks/webhookFilter.test.ts b/apps/server/src/scheduledTasks/webhookFilter.test.ts index 1194a1aed5177..2c7f2cc4062e8 100644 --- a/apps/server/src/scheduledTasks/webhookFilter.test.ts +++ b/apps/server/src/scheduledTasks/webhookFilter.test.ts @@ -16,6 +16,28 @@ const issueComment: WebhookRequest = { }; describe("findFailedWebhookFilter", () => { + it("matches exists on wildcard object values", () => { + assert.isNull( + findFailedWebhookFilter([{ path: "body.issue.labels[]", op: "exists" }], issueComment), + ); + assert.isNull( + findFailedWebhookFilter([{ path: "body.issues[].labels", op: "exists" }], { + ...issueComment, + bodyText: JSON.stringify({ issues: [{ labels: [] }] }), + }), + ); + }); + + it("rejects exists when wildcard values are all null or missing", () => { + assert.deepEqual( + findFailedWebhookFilter([{ path: "body.issues[].labels", op: "exists" }], { + ...issueComment, + bodyText: JSON.stringify({ issues: [{ labels: null }, {}] }), + }), + { index: 0, path: "body.issues[].labels" }, + ); + }); + it("matches a wildcard path when any element matches", () => { assert.isNull( findFailedWebhookFilter( diff --git a/apps/server/src/scheduledTasks/webhookFilter.ts b/apps/server/src/scheduledTasks/webhookFilter.ts index 882f300364288..2ad0e0237e079 100644 --- a/apps/server/src/scheduledTasks/webhookFilter.ts +++ b/apps/server/src/scheduledTasks/webhookFilter.ts @@ -36,6 +36,8 @@ function matchesScalar(filter: ScheduledTaskWebhookFilter, text: string): boolea */ function matchesWebhookFilter(filter: ScheduledTaskWebhookFilter, value: unknown): boolean { if (Array.isArray(value) && /\[\]/.test(filter.path)) { + if (filter.op === "exists") + return value.some((element) => element !== null && element !== undefined); const texts = value.map(scalarText).filter((text): text is string => text !== undefined); if (filter.op === "notEquals") return texts.every((text) => text !== filter.value); return texts.some((text) => matchesScalar(filter, text)); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index 0c0073b97563a..3cbe08b384245 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -903,6 +903,30 @@ it.layer( }), ); + it.effect("labels a running command by its whole process name, spaces included", () => + Effect.gen(function* () { + const { manager } = yield* createManager(5, { + subprocessPollIntervalMs: 1_000, + processKillGraceMs: 0, + processTable: Effect.succeed([ + { pid: 9000, ppid: 1, name: "zsh" }, + { pid: 200, ppid: 9000, name: "Google Chrome" }, + ]), + }).pipe(Effect.provide(layerWithHostPlatform("darwin"))); + const label = yield* Deferred.make(); + const unsubscribe = yield* manager.subscribe((event) => + event.type === "activity" + ? Deferred.succeed(label, event.label).pipe(Effect.asVoid) + : Effect.void, + ); + yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); + yield* manager.open(openInput()); + yield* TestClock.adjust("1 second"); + + expect(yield* Deferred.await(label)).toBe("Google Chrome"); + }).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 e702cf71cd52b..d2a8a24c323f3 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -366,10 +366,9 @@ function normalizeChildCommandName(raw: string, platform: NodeJS.Platform): stri ) { trimmed = trimmed.slice(1, -1).trim(); } - const firstToken = (trimmed.split(/\s+/)[0] ?? trimmed).trim(); - if (firstToken.length === 0) return null; + // Process names and macOS `comm` paths can contain spaces ("Google Chrome"). const separators = platform === "win32" ? /[\\/]/ : /\//; - const base = firstToken.split(separators).at(-1) ?? firstToken; + const base = (trimmed.split(separators).at(-1) ?? trimmed).trim(); const withoutExe = platform === "win32" && base.toLowerCase().endsWith(".exe") ? base.slice(0, -4) : base; return withoutExe.length > 0 ? withoutExe : null; diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 8183f574a56b7..f64ade1219bdf 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2581,6 +2581,39 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reads range patches from source without running textconv", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + yield* git(cwd, ["config", "diff.probe.textconv", "touch textconv-ran; echo converted"]); + yield* git(cwd, ["checkout", "-b", "feature/range"]); + yield* writeTextFile(cwd, ".gitattributes", "*.doc diff=probe\n"); + yield* writeTextFile(cwd, "notes.doc", "source line\n"); + yield* writeTextFile(cwd, "plain.txt", "plain line\n"); + yield* writeTextFile(cwd, "binary.dat", "binary\0data"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "range files"]); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + + const context = yield* driver.readRangeContext(cwd, initialBranch); + + assert.include(context.diffPatch, "+source line"); + assert.notInclude(context.diffPatch, "converted"); + assert.include(context.diffPatch, "+plain line"); + assert.include(context.diffPatch, "Binary files /dev/null and b/binary.dat differ"); + assert.include(context.diffSummary, "notes.doc"); + assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); + + yield* writeTextFile(cwd, "notes.doc", "updated source line\n"); + const staged = yield* driver.prepareCommitContext(cwd, ["notes.doc"]); + assert.include(staged?.stagedPatch ?? "", "+updated source line"); + assert.notInclude(staged?.stagedPatch ?? "", "converted"); + assert.include(staged?.stagedSummary ?? "", "notes.doc"); + assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); + }), + ); + it.effect("loads new and deleted files without reading their missing side", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3680,6 +3713,47 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("flattens a generated name when a branch at its parent path blocks it", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + // A local `t3` branch is why launches start on the flat `t3-` temporary branch. + yield* git(cwd, ["branch", "t3"]); + yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); + yield* git(cwd, ["branch", "t3-fix-login"]); + + const renamed = yield* driver.renameBranch({ + cwd, + oldBranch: "t3-abcd1234", + newBranch: "t3/fix-login", + }); + + assert.equal(renamed.branch, "t3-fix-login-1"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3-fix-login-1"); + }), + ); + + it.effect("skips a flattened name that a nested branch blocks", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "t3"]); + yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); + yield* git(cwd, ["branch", "t3-fix-login/child"]); + + const renamed = yield* driver.renameBranch({ + cwd, + oldBranch: "t3-abcd1234", + newBranch: "t3/fix-login", + }); + + assert.equal(renamed.branch, "t3-fix-login-1"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3-fix-login-1"); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4795,6 +4869,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }); describe("commit context", () => { + it.effect("prepares source patches without running textconv", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["config", "diff.probe.textconv", "touch textconv-ran; echo converted"]); + yield* writeTextFile(cwd, ".gitattributes", "*.doc diff=probe\n"); + yield* writeTextFile(cwd, "notes.doc", "original source\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "source document"]); + yield* writeTextFile(cwd, "notes.doc", "updated source\n"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const fileSystem = yield* FileSystem.FileSystem; + + const context = yield* driver.prepareCommitContext(cwd, ["notes.doc"]); + + assert.include(context?.stagedPatch ?? "", "-original source"); + assert.include(context?.stagedPatch ?? "", "+updated source"); + assert.notInclude(context?.stagedPatch ?? "", "converted"); + assert.include(context?.stagedSummary ?? "", "notes.doc"); + assert.isFalse(yield* fileSystem.exists(`${cwd}/textconv-ran`)); + }), + ); + it.effect("can omit the patch while preserving change detection and the real index", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 27e9b6247d4f1..fce1566f428c3 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1234,16 +1234,37 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* ( cwd: string, - desiredBranch: string, + requestedBranch: string, ) { - const isDesiredTaken = yield* branchExists(cwd, desiredBranch); + // A branch at a parent path (such as `t3`) blocks every ref nested under it, so no suffix + // would help; flatten to a sibling the way temporary worktree branches already do. + const segments = requestedBranch.split("/"); + let blockedByParent = false; + for (let index = 1; index < segments.length && !blockedByParent; index += 1) { + blockedByParent = yield* branchExists(cwd, segments.slice(0, index).join("/")); + } + const desiredBranch = blockedByParent ? segments.join("-") : requestedBranch; + // A branch nested under the name (`t3-fix/child`) blocks it as surely as one with the name. + const isBranchNameTaken = (name: string) => + Effect.zipWith( + branchExists(cwd, name), + runGitStdout( + "GitVcsDriver.branchExists", + cwd, + ["for-each-ref", "--count=1", "--format=%(refname)", `refs/heads/${name}/`], + true, + ), + (exists, nested) => exists || nested.trim().length > 0, + ); + + const isDesiredTaken = yield* isBranchNameTaken(desiredBranch); if (!isDesiredTaken) { return desiredBranch; } for (let suffix = 1; suffix <= 100; suffix += 1) { const candidate = `${desiredBranch}-${suffix}`; - const isCandidateTaken = yield* branchExists(cwd, candidate); + const isCandidateTaken = yield* isBranchNameTaken(candidate); if (!isCandidateTaken) { return candidate; } @@ -2489,7 +2510,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const stagedPatch = yield* runGitStdoutWithOptions( "GitVcsDriver.prepareCommitContext.stagedPatch", cwd, - ["diff", "--no-ext-diff", "--cached", "--patch", "--minimal"], + ["diff", "--no-ext-diff", "--no-textconv", "--cached", "--patch", "--minimal"], { env, maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, @@ -2900,7 +2921,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* runGitStdoutWithOptions( "GitVcsDriver.readRangeContext.diffPatch", cwd, - ["diff", "--no-ext-diff", "--patch", "--minimal", "--end-of-options", diffRange], + [ + "diff", + "--no-ext-diff", + "--no-textconv", + "--patch", + "--minimal", + "--end-of-options", + diffRange, + ], { maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, appendTruncationMarker: true, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index a96b7390c9952..0293211c42a64 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -685,6 +685,96 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(layerTestFor(state))); }); + it.effect("a remote poll refreshes Changes totals when divergence counts stay the same", () => { + const state: Parameters[0] = { + currentLocalStatus: { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 }, + }, + currentRemoteStatus: baseRemoteStatus, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + yield* broadcaster.getStatus({ cwd: "/repo" }); + const subscribed = yield* Deferred.make(); + const polled = yield* Deferred.make(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => { + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined); + if (event._tag === "remoteUpdated") return Deferred.succeed(polled, undefined); + return Effect.void; + }), + Effect.forkScoped, + ); + yield* Deferred.await(subscribed); + state.currentLocalStatus = { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 107, deletions: 4 }, + }; + state.currentRemoteStatus = remoteStatusWithPr; + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(polled); + const status = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + + it.effect("an explicit refresh reads local totals after the fetch", () => { + return Effect.gen(function* () { + const fetchStarted = yield* Deferred.make(); + const finishFetch = yield* Deferred.make(); + let local: VcsStatusLocalResult = { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 }, + }; + let cachedLocal: VcsStatusLocalResult | undefined; + const readLocalStatus = () => Effect.sync(() => (cachedLocal ??= local)); + const layerTest = VcsStatusBroadcaster.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(layerBackgroundPolicy(() => true)), + Layer.provide( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + localStatus: readLocalStatus, + invalidateStatus: () => + Effect.sync(() => { + cachedLocal = undefined; + }), + invalidateLocalStatus: () => + Effect.sync(() => { + cachedLocal = undefined; + }), + currentBranch: () => Effect.succeed(baseLocalStatus.refName), + invalidateRemoteStatus: () => Effect.void, + remoteStatus: () => + Deferred.succeed(fetchStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishFetch)), + Effect.as(baseRemoteStatus), + ), + }), + ), + ); + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(fetchStarted); + // Another reader can refill the local cache while fetch is still running. + yield* readLocalStatus(); + local = { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 }, + }; + yield* Deferred.succeed(finishFetch, undefined); + const status = yield* Fiber.join(refresh); + assert.deepStrictEqual(status.branchChanges, local.branchChanges); + }).pipe(Effect.provide(layerTest)); + }); + }); + it.effect("publishes local status while an earlier lookup holds the remote lock", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index a4f5ddede9b68..b9d40058051ac 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -487,23 +487,14 @@ export const make = Effect.gen(function* () { return yield* withRemoteWriteLock( cwd, Effect.gen(function* () { - const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value; const remoteRead = yield* readRemoteStatus(cwd, options); - const remote = remoteRead?.value; const pulled = options?.refreshUpstream === false ? null : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]); if (pulled !== null) return pulled.remote; - if ( - remote && - (!previousRemote || - previousRemote.aheadCount !== remote.aheadCount || - previousRemote.behindCount !== remote.behindCount || - previousRemote.aheadOfDefaultCount !== remote.aheadOfDefaultCount) - ) { - yield* refreshLocalStatusCore(cwd); - } + // Base refs and merge bases can move without changing divergence counts. + yield* refreshLocalStatusCore(cwd); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), ); @@ -540,8 +531,7 @@ export const make = Effect.gen(function* () { yield* workflow.invalidateStatus(cwd); const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream }); // Fetch can move the base used for local Changes totals. - const local = yield* workflow.localStatus({ cwd }); - yield* updateCachedLocalStatus(cwd, local, { publish: true }); + yield* refreshLocalStatusCore(cwd); // Without a fetch, the cached behind count cannot justify an automatic pull. const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null; if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 5848f3de615bb..d15de35a960f8 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFSP from "node:fs/promises"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { FileFinder } from "@ff-labs/fff-node"; import { it, afterEach, describe, expect } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -650,6 +651,53 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { expect(match.lineContent.slice(range.start, range.end)).toBe("wörld"); }), ); + + it.effect("keeps answering from the live index when a refresh outlasts the scan wait", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-content-refresh-" }); + yield* writeTextFile(cwd, "src/notes.ts", "const needle = 1;\n"); + let scansOutlastWait = false; + let finders = 0; + let rescans = 0; + const createFinder = FileFinder.create.bind(FileFinder); + vi.spyOn(FileFinder, "create").mockImplementation((options) => { + const created = createFinder(options); + if (created.ok) { + const finder = created.value; + finders += 1; + const scanFiles = finder.scanFiles.bind(finder); + finder.scanFiles = () => { + rescans += 1; + return scanFiles(); + }; + const waitForIndexReady = finder.waitForIndexReady.bind(finder); + finder.waitForIndexReady = (timeoutMs) => + scansOutlastWait + ? Promise.resolve({ ok: true, value: false }) + : waitForIndexReady(timeoutMs); + } + return created; + }); + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searchNeedle = workspaceEntries.searchContents({ + cwd, + query: "needle", + limit: 100, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }); + yield* searchNeedle; + + scansOutlastWait = true; + yield* workspaceEntries.refresh(cwd); + const result = yield* searchNeedle; + + expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]); + // The second search ran on the rescanned live finder, not a rebuild. + expect({ finders, rescans }).toEqual({ finders: 1, rescans: 1 }); + }), + ); }); describe("browse", () => { diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 8f2b64cf26a34..d5539e2f4e718 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -117,10 +117,7 @@ export class WorkspaceSearchIndex extends Context.Service< readonly searchContents: ( input: Omit, ) => Effect.Effect; - readonly refresh: () => Effect.Effect< - void, - WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut - >; + readonly refresh: () => Effect.Effect; } >()("t3/workspace/WorkspaceSearchIndex") {} @@ -419,6 +416,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( reason: result.error, }); } + // A rescan that outlasts the wait keeps running, and the finder answers + // from its previous index until it finishes, so the index stays usable. yield* waitForIndexReady( cwd, finder, @@ -428,7 +427,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( reason, cause, }), - ); + ).pipe(Effect.catchTags({ WorkspaceSearchIndexScanTimedOut: () => Effect.void })); }); const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")( diff --git a/apps/web/package.json b/apps/web/package.json index 6e586303faaeb..a39fa27e95232 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,12 +34,14 @@ "@tanstack/react-router": "^1.160.2", "@tiptap/core": "^3.31.3", "@tiptap/extension-blockquote": "^3.31.3", + "@tiptap/extension-bold": "^3.31.3", "@tiptap/extension-code": "^3.31.3", "@tiptap/extension-code-block": "^3.31.3", "@tiptap/extension-heading": "^3.31.3", "@tiptap/extension-horizontal-rule": "^3.31.3", "@tiptap/extension-italic": "^3.31.3", "@tiptap/extension-list": "^3.31.3", + "@tiptap/extension-strike": "^3.31.3", "@tiptap/extension-task-item": "^3.31.3", "@tiptap/extension-task-list": "^3.31.3", "@tiptap/pm": "^3.31.3", @@ -55,6 +57,7 @@ "hast-util-to-jsx-runtime": "^2.3.6", "heic-to": "^1.5.2", "html-url-attributes": "^3.0.1", + "jsonc-parser": "3.3.1", "jszip": "3.10.1", "katex": "^0.16.47", "lucide": "^0.564.0", diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index f843efcd92193..d8687a4213251 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -820,11 +820,7 @@ export function BranchToolbarBranchSelector({ )} /> - + diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx index 41bd2b008be89..ca511de43642c 100644 --- a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -73,7 +73,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe if (envLocked || forceNewWorktree) { const lockedRow = ( {activeWorktreePath ? ( diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx index 33faa9fdf510f..9db69a8a86a0f 100644 --- a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -52,7 +52,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir if (envLocked || onEnvironmentChange === undefined) { const lockedRow = ( expandMedia({ images: [{ src, name: "Mermaid diagram" }], index: 0 })} + onExpand={(src) => + expandMedia({ + images: [{ src, name: "Mermaid diagram", mimeType: "image/svg+xml" }], + index: 0, + }) + } > {highlightedCode} diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 60016423d6ed7..860e5c5b74ee9 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -190,6 +190,40 @@ describe("hasServerAcknowledgedLocalDispatch", () => { ).toBe(false); }); + it.each([ + ["queued", "message-queued", true], + ["queued", "message-before-send", false], + ["preparing", "message-queued", false], + ["starting", "message-queued", false], + ] as const)("acknowledges %s with latest message %s: %s", (status, messageId, acknowledged) => { + const localDispatch = createLocalDispatchSnapshot( + makeThread({ latestRun: completedTurn, runtime: readySession }), + { latestUserMessageId: MessageId.make("message-before-send") }, + ); + // The shell hides the silent compaction run, so its runtime reports the queued message's run. + const queuedRun = { + ...completedTurn, + runId: RunId.make("turn-queued"), + status: "queued" as const, + requestedAt: "2026-03-29T00:01:00.000Z", + startedAt: null, + completedAt: null, + }; + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "running", + latestRun: queuedRun, + latestUserMessageId: MessageId.make(messageId), + runtime: { ...readySession, status }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(acknowledged); + }); + it("waits for the matching running turn before acknowledging", () => { const localDispatch = createLocalDispatchSnapshot( makeThread({ latestRun: completedTurn, runtime: readySession }), diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index df5256a176b3d..79be5accb32cf 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1021,14 +1021,15 @@ export function hasServerAcknowledgedLocalDispatch(input: { if (input.hasPendingApproval || input.hasPendingUserInput || Boolean(input.threadError)) { return true; } + const latestUserMessageChanged = + input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null); if (input.phase === "connecting" || derivePhase(input.runtime ?? null) === "connecting") { - return false; + // A message queued behind other work, such as an idle compaction the shell hides, has landed. + return input.runtime?.status === "queued" && latestUserMessageChanged; } const latestRun = input.latestRun ?? null; const runtime = input.runtime ?? null; - const latestUserMessageChanged = - input.localDispatch.latestUserMessageId !== (input.latestUserMessageId ?? null); const latestRunChanged = input.localDispatch.latestRunId !== (latestRun?.runId ?? null) || input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) || diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 87abf50bf4bba..391b28ceb2bee 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,3 +1,4 @@ +import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; @@ -41,10 +42,6 @@ import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent"; import { usePendingThreadRequests } from "./chat/usePendingThreadRequests"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; -import { - latestExecutedRun, - latestRootProviderFailure, -} from "@t3tools/shared/orchestrationV2ThreadError"; import { useWorktreeSetup } from "./chat/useWorktreeSetup"; import { useChatShortcuts } from "./chat/useChatShortcuts"; import { ChatBannerLane } from "./chat/ChatBannerLane"; @@ -71,6 +68,7 @@ import { import { deriveProviderSubagentStatus, deriveReportedModelSelection, + deriveResumableRunId, formatModelSelectionEffort, deriveRunlessWorkStartedAt, deriveThreadActivityRun, @@ -715,16 +713,10 @@ export default function ChatView(props: ChatViewProps) { isServerThread && serverProjection?.runs.some((run) => run.status === "queued" && run.queueHeld === true) === true; - const resumableRunId = (() => { - if (!isServerThread || serverProjection === null) return null; - const run = latestExecutedRun(serverProjection.runs); - if (run?.status === "interrupted") return run.id; - return run?.status === "failed" && - serverRuntime?.lastErrorClass === "usage_limit" && - latestRootProviderFailure(run, serverProjection.turnItems)?.class === "usage_limit" - ? run.id - : null; - })(); + const resumableRunId = + !isServerThread || serverProjection === null + ? null + : deriveResumableRunId(serverProjection, serverRuntime); const parentSubagentThreadId = activeThread?.lineage.relationshipToParent === "subagent" ? activeThread.lineage.parentThreadId @@ -2809,6 +2801,11 @@ export default function ChatView(props: ChatViewProps) { (folders: Parameters[0]) => composerRef.current?.addDroppedFolders(folders), ); + // Above the early return, where React Compiler can cache it for the side chat pane. + const sideChatParentPanel = { + openToolDiff: onOpenToolDiffStable, + runShellCommand: runSideChatShellCommandStable, + }; if (!activeThread) { return embedded ? null : ; @@ -2825,10 +2822,7 @@ export default function ChatView(props: ChatViewProps) { workspaceMutationId={workspaceMutationId} getShortcutContext={getShortcutContextStable} onCloseSurface={closeRightPanelSurface} - sideChatParentPanel={{ - openToolDiff: onOpenToolDiffStable, - runShellCommand: runSideChatShellCommandStable, - }} + sideChatParentPanel={sideChatParentPanel} terminal={{ launchContext: activeTerminalLaunchContext ?? null, keybindings, @@ -3143,6 +3137,7 @@ export default function ChatView(props: ChatViewProps) { : undefined } > + void }).preventBaseUIHandler?.(); + event.preventDefault(); + if (highlightedItemValue === "browse:up") { + void browseUp(); + return; + } + const highlightedEntry = visibleBrowseEntries.find( + (entry) => `browse:${entry.fullPath}` === highlightedItemValue, + ); + const completion = highlightedEntry + ? { name: highlightedEntry.name, isComplete: true } + : getFilesystemBrowseTabCompletion(visibleBrowseEntries, browsePath.filterQuery); + if (completion?.isComplete) { + void browseTo(completion.name); + } else if (completion && !pinnedCloneDirectoryName) { + setHighlightedItemValue(null); + setQuery(`${getBrowseDirectoryPath(query)}${completion.name}`); + } + return; + } + const firstItemValue = autoHighlightsFirstRow ? resultRows.itemValues[0] : undefined; if ( event.key === "ArrowDown" && diff --git a/apps/web/src/components/ComposerContextLabel.tsx b/apps/web/src/components/ComposerContextLabel.tsx index 30567ac355f8a..89b54d5419821 100644 --- a/apps/web/src/components/ComposerContextLabel.tsx +++ b/apps/web/src/components/ComposerContextLabel.tsx @@ -24,7 +24,7 @@ export function ComposerContextLabel({ data-composer-label-motion className={cn( "block w-full min-w-0 truncate", - displayMode === "panel" && THREAD_DETAILS_PANEL_LABEL_CLASS, + THREAD_DETAILS_PANEL_LABEL_CLASS, displayMode === "toolbar" && "max-w-[240px] transition-opacity duration-180 ease-drawer group-data-[compact]/composer-context:opacity-0 motion-reduce:transition-none", )} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index abc9549ee3d00..fe78eaacbe850 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -73,7 +73,9 @@ import { ComposerBoldSelectionOnlyExtension, convertBulletItemToTask, ComposerCodeExtension, + ComposerBoldExtension, ComposerItalicExtension, + ComposerStrikeExtension, ComposerTaskItemExtension, ComposerTaskListExtension, flatToMarkdown, @@ -831,7 +833,8 @@ function createComposerExtensions(richText: boolean) { listKeymap: false, undoRedo: { newGroupDelay: COMPOSER_UNDO_GROUP_DELAY }, italic: false, - ...(richText ? {} : { bold: false, strike: false }), + bold: false, + strike: false, }), ComposerUndoGroupingExtension, ComposerTextDirectionExtension, @@ -844,6 +847,8 @@ function createComposerExtensions(richText: boolean) { ? [ ComposerBoldSelectionOnlyExtension, ComposerItalicExtension, + ComposerBoldExtension, + ComposerStrikeExtension, ComposerCodeExtension, ComposerCodeBlockExtension.extend({ addNodeView() { diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index 43c466184bf2c..91d4a54fd9e64 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -124,7 +124,7 @@ function CustomSnoozeDialog() {
{mode === "date" ? (
-
+
= Atom.Atom>; + +const state = vi.hoisted(() => ({ + thread: null as ReturnType | null, + threadRef: null as ScopedThreadRef | null, + previews: new Map>(), + config: null as unknown as Atom.Atom, + status: null as unknown as ResultAtom, + localRefs: null as unknown as ResultAtom, + remoteRefs: null as unknown as ResultAtom, + commits: null as unknown as ResultAtom, +})); + +vi.mock("~/state/server", () => ({ + serverEnvironment: { configValueAtom: () => state.config }, +})); +vi.mock("~/state/review", () => ({ + reviewEnvironment: { + diffPreview: ({ input }: { input: { baseRef?: string } }) => + state.previews.get(input.baseRef ?? null)!, + branchCommits: () => state.commits, + diffFileContents: {}, + }, +})); +vi.mock("~/state/vcs", () => ({ + vcsEnvironment: { + status: () => state.status, + listRefs: ({ input }: { input: { refKind: "local" | "remote" } }) => + input.refKind === "local" ? state.localRefs : state.remoteRefs, + }, +})); +vi.mock("~/state/entities", () => ({ + useQuietThreadShell: () => state.thread, + useProject: () => ({ workspaceRoot: "/project", repositoryIdentity: null }), + useThreadCheckpointSummaries: () => [], + useQuietThreadVisibleTurnItems: () => [], +})); +vi.mock("~/state/filesystem", () => ({ + useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }), +})); +vi.mock("~/hooks/useThreadRouteTarget", () => ({ useThreadRouteRef: () => state.threadRef })); +vi.mock("~/hooks/useSettings", () => ({ + useClientSettings: (select: (settings: ClientSettings) => unknown) => + select(DEFAULT_CLIENT_SETTINGS), + updateClientSettings: async () => {}, +})); +vi.mock("~/hooks/useTheme", () => ({ useRenderedAppearance: () => "dark" })); +vi.mock("~/state/queries", () => ({ + useCheckpointDiff: () => ({ data: null, error: null, isPending: false }), + useTurnItemDetail: () => ({ data: null, error: null, isPending: false }), +})); +vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => async () => {} })); +vi.mock("~/editorPreferences", () => ({ useOpenInPreferredEditor: () => async () => {} })); +vi.mock("~/fileContextMenu", () => ({ useFileContextMenuHandler: () => () => {} })); +vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => async () => {} })); +// The test drives comparison controls, without mounting virtualized diff viewers or their workers. +vi.mock("./diffs/AnnotatableCodeView", () => ({ AnnotatableCodeView: () => null })); +vi.mock("./diffs/DiffFileTree", () => ({ DiffFileTree: () => null })); +vi.mock("./DiffFilePathCopyButton", () => ({ DiffFilePathCopyButton: () => null })); + +import DiffPanel from "./DiffPanel"; +import { useDiffPanelSessionStore, useDiffPanelStore } from "~/diffPanelStore"; + +const cwd = "/project-worktree"; +const errorMessage = "Could not find a common commit between 'origin/orphan' and HEAD."; + +function preview(): ReviewDiffPreviewResult { + return { + cwd, + generatedAt: DateTime.makeUnsafe("2026-10-30T00:00:00Z"), + sources: [ + { + id: "branch", + kind: "branch-range", + title: "Changes", + baseRef: "main", + headRef: "dev", + diff: "", + diffHash: "empty", + truncated: false, + }, + ], + }; +} + +function setup(failedBaseRef: string | null) { + const reset = () => { + useDiffPanelStore.setState({ + byThreadKey: {}, + branchBaseRefByThreadKey: {}, + keepSelectionOnOpenThreadKey: null, + }); + useDiffPanelSessionStore.setState({ collapsedFileKeysByScopeKey: {} }); + }; + reset(); + state.threadRef = { + environmentId: EnvironmentId.make("environment"), + threadId: ThreadId.make("thread"), + }; + state.thread = makeThreadFixture({ + ...state.threadRef, + id: state.threadRef.threadId, + projectId: ProjectId.make("project"), + branch: "dev", + worktreePath: cwd, + }); + state.previews.clear(); + state.previews.set(null, Atom.make(AsyncResult.success(preview()))); + state.previews.set("main", Atom.make(AsyncResult.success(preview()))); + state.previews.set(failedBaseRef, Atom.make(AsyncResult.fail(new Error(errorMessage)))); + state.config = Atom.make(null); + state.status = Atom.make( + AsyncResult.success({ + isRepo: true, + hasPrimaryRemote: true, + isDefaultRef: false, + refName: "dev", + hasWorkingTreeChanges: false, + workingTree: { rootPath: cwd, files: [], insertions: 0, deletions: 0 }, + hasUpstream: true, + aheadCount: 0, + behindCount: 0, + pr: null, + }), + ); + const refs = (names: string[], isRemote: boolean): VcsListRefsResult => ({ + isRepo: true, + hasPrimaryRemote: true, + nextCursor: null, + totalCount: names.length, + refs: names.map((name) => ({ + name, + isRemote, + ...(isRemote ? { remoteName: "origin" } : {}), + current: name === "dev", + isDefault: name === "main", + worktreePath: null, + })), + }); + state.localRefs = Atom.make(AsyncResult.success(refs(["dev", "main"], false))); + state.remoteRefs = Atom.make(AsyncResult.success(refs(["origin/orphan"], true))); + state.commits = Atom.make(AsyncResult.success({ commits: [], truncated: false })); + useDiffPanelStore.getState().selectBranchBaseRef(state.threadRef, failedBaseRef); + const registry = AtomRegistry.make(); + return { + registry, + threadRef: state.threadRef, + [Symbol.dispose]() { + registry.dispose(); + reset(); + }, + }; +} + +it.each([ + { + name: "a saved unrelated branch", + failedBaseRef: "origin/orphan", + recovery: "Automatic", + baseRef: null, + }, + { + name: "an automatic base with unrelated history", + failedBaseRef: null, + recovery: "main", + baseRef: "main", + }, +])( + "recovers from $name without leaving the diff panel", + async ({ failedBaseRef, recovery, baseRef }) => { + using context = setup(failedBaseRef); + await using screen = await render( + + + , + ); + await expect.element(screen.getByText(errorMessage, { exact: true })).toBeVisible(); + const selector = screen.getByRole("combobox", { name: /Change comparison target/ }); + await vi.waitFor(() => expect(selector.query()).not.toBeNull()); + await userEvent.click(selector); + await expect.element(page.getByRole("option", { name: "main", exact: true })).toBeVisible(); + await userEvent.click(page.getByRole("option", { name: recovery, exact: true })); + await expect.element(screen.getByText("No net changes in this selection.")).toBeVisible(); + await expect.element(screen.getByText(errorMessage, { exact: true })).not.toBeInTheDocument(); + const key = scopedThreadKey(context.threadRef); + await vi.waitFor(() => { + expect(useDiffPanelStore.getState().byThreadKey[key]).toEqual({ kind: "branch", baseRef }); + expect(useDiffPanelStore.getState().branchBaseRefByThreadKey[key]).toBe(baseRef); + }); + }, +); diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 8e39f7e09e75d..f702ccd8ef220 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -60,6 +60,7 @@ import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./Dif import { DiffStatLabel } from "./chat/DiffStatLabel"; import { AnnotatableCodeView } from "./diffs/AnnotatableCodeView"; import { DiffFileTree } from "./diffs/DiffFileTree"; +import { FileExplorerPane } from "./files/FileExplorerPane"; import { diffFileTreeEntries } from "./diffs/diffFileTree.logic"; import { DiffFileExpansionErrorNotice, @@ -411,6 +412,8 @@ export default function DiffPanel({ ? "commit" : "branch-range"), ); + const comparisonHeadRef = selectedGitSource?.headRef ?? gitStatusQuery.data?.refName ?? "HEAD"; + const comparisonBaseRef = selectedGitSource?.baseRef ?? selectedBaseRef ?? "Automatic"; const selectedCommitSubject = selectedCommitSha !== null && selectedGitSource?.headRef === selectedCommitSha ? selectedGitSource.commitSubject @@ -558,12 +561,14 @@ export default function DiffPanel({ } return currentLoadDiffFiles(fileDiff); }); + const canSelectBranchBase = canReadFiles && canRefreshGitDiff && selectedGitScope === "branch"; + const branchRefsCwd = branchDiffPreview.data?.cwd ?? activeCwd; const localBranchRefs = useEnvironmentQuery( - isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd + canSelectBranchBase && activeThread && branchRefsCwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { - cwd: branchDiffPreview.data.cwd, + cwd: branchRefsCwd, includeMatchingRemoteRefs: true, refKind: "local", ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}), @@ -573,11 +578,11 @@ export default function DiffPanel({ : null, ); const remoteBranchRefs = useEnvironmentQuery( - isGitSelection && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd + canSelectBranchBase && activeThread && branchRefsCwd ? vcsEnvironment.listRefs({ environmentId: activeThread.environmentId, input: { - cwd: branchDiffPreview.data.cwd, + cwd: branchRefsCwd, includeMatchingRemoteRefs: true, refKind: "remote", ...(baseRefQuery.trim().length > 0 ? { query: baseRefQuery.trim() } : {}), @@ -587,7 +592,7 @@ export default function DiffPanel({ : null, ); const baseRefChoices = buildBaseRefChoices( - localBranchRefs.data?.refs.filter((ref) => ref.name !== selectedGitSource?.headRef) ?? [], + localBranchRefs.data?.refs.filter((ref) => ref.name !== comparisonHeadRef) ?? [], remoteBranchRefs.data?.refs ?? [], ); const matchingBaseRefChoices = filterBaseRefChoices(baseRefChoices, baseRefQuery); @@ -974,10 +979,10 @@ export default function DiffPanel({ - {isGitSelection && selectedGitScope === "branch" && selectedGitSource?.baseRef && ( + {canSelectBranchBase && (
} > - - {selectedGitSource.headRef ?? "HEAD"} - + {comparisonHeadRef} - {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`} + {`${comparisonHeadRef} → ${comparisonBaseRef}`} @@ -1003,7 +1006,7 @@ export default function DiffPanel({ vs - {`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`} + {`${comparisonHeadRef} → ${comparisonBaseRef}`} } className="min-w-9 max-w-48 shrink-0" - aria-label={`Change comparison target. Currently ${selectedGitSource.baseRef}`} + aria-label={`Change comparison target. Currently ${comparisonBaseRef}`} > - {selectedGitSource.baseRef} + {comparisonBaseRef}
{fileTreeOpen ? ( - + ) : null}
) : ( diff --git a/apps/web/src/components/ProviderUpdatesAction.tsx b/apps/web/src/components/ProviderUpdatesAction.tsx index dbce5c73bac5d..6e8c03844b3c6 100644 --- a/apps/web/src/components/ProviderUpdatesAction.tsx +++ b/apps/web/src/components/ProviderUpdatesAction.tsx @@ -1,9 +1,10 @@ -import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; +import { AuthProvidersManageScope, PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; import { settlePromise } from "@t3tools/client-runtime/state/runtime"; import { useRef, useState } from "react"; import { useEnvironmentProviders, useEnvironments } from "~/state/environments"; import { serverEnvironment } from "~/state/server"; +import { useEnvironmentsWithScope } from "~/state/session"; import { useAtomCommand } from "~/state/use-atom-command"; import { canOneClickUpdateProviderCandidate, @@ -21,13 +22,17 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; */ export function useProviderUpdates() { const { environments } = useEnvironments(); + const manageableIds = useEnvironmentsWithScope(environments, AuthProvidersManageScope); const providersByEnvironment = useEnvironmentProviders(); const updateProvider = useAtomCommand(serverEnvironment.updateProvider, { reportFailure: false, }); const machines = environments.flatMap((environment) => { const providers = providersByEnvironment.get(environment.environmentId) ?? []; - if (environment.connection.phase !== "connected") { + if ( + environment.connection.phase !== "connected" || + !manageableIds.has(environment.environmentId) + ) { return []; } const candidates = collectProviderUpdateCandidates(providers).filter((candidate) => diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx index 4d2c27270a7ec..90d08b22f0c73 100644 --- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx +++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx @@ -164,4 +164,5 @@ describe("root reopen shortcut", () => { expect(useClosedViewStore.getState().entries).toEqual([]); }, ); + // Coder: no desktop browser page forwards address-bar focus (#22328). }); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index f6e66a1ac6506..fde82414afa79 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -12,6 +12,8 @@ import { getFallbackThreadIdAfterDelete, hasUnseenCompletion, resolveSidebarRowThreadId, + belongsInSidebarWorkingShelf, + isSidebarEnvironmentDisconnected, orderItemsByPreferredIds, pinOrderKeyBetween, resolveProjectStatusIndicator, @@ -1089,6 +1091,38 @@ describe("Working shelf (beta)", () => { ).toBe(false); }); + it.each([ + ["connected", true, false], + ["connected", false, true], + ["connecting", false, false], + ["reconnecting", false, true], + ["offline", false, true], + ["error", false, true], + ["unsupported", false, true], + ["available", false, true], + ] as const)( + "lists threads outside the shelf on a %s environment: %s", + (phase, shellIsLive, disconnected) => { + expect(isSidebarEnvironmentDisconnected(phase, shellIsLive)).toBe(disconnected); + }, + ); + + it("lists a running thread outside the shelf while its environment is disconnected", () => { + const thread = { ...idle, runtime, environmentId: localEnvironmentId }; + const shelve = (disconnected: ReadonlyArray, enabled = true) => + belongsInSidebarWorkingShelf(thread, { + enabled, + disconnectedEnvironmentIds: new Set(disconnected), + isWorking: isSidebarThreadWorking, + }); + + expect(shelve([])).toBe(true); + expect(shelve([localEnvironmentId])).toBe(false); + expect(shelve([])).toBe(true); + expect(shelve([EnvironmentId.make("environment-other")])).toBe(true); + expect(shelve([], false)).toBe(false); + }); + describe("sortInboxThreadsByReturn", () => { const thread = ( id: string, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 550dd575b2057..b60bbf5070488 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -16,6 +16,7 @@ import { type ThreadSearchShell, } from "@t3tools/client-runtime/state/thread-search"; import { foldSearchQuery, rankSearchItems, scoreThreadSearch } from "@t3tools/shared/paletteSearch"; +import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; import { isListedThreadLineage, type EnvironmentId, type ThreadId } from "@t3tools/contracts"; import type { ContextMenuItem } from "../localApiTypes"; import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings"; @@ -180,6 +181,29 @@ export function resolveSidebarThreadSection(input: { return "active"; } +// Keep cached placement on the first connection attempt, matching mobile's threadRouteIsHydrating. +export function isSidebarEnvironmentDisconnected( + phase: EnvironmentConnectionPhase, + shellIsLive: boolean, +): boolean { + return phase !== "connecting" && (phase !== "connected" || !shellIsLive); +} + +export function belongsInSidebarWorkingShelf( + thread: T, + input: { + readonly enabled: boolean; + readonly disconnectedEnvironmentIds: ReadonlySet; + readonly isWorking: (thread: T) => boolean; + }, +): boolean { + return ( + input.enabled && + !input.disconnectedEnvironmentIds.has(thread.environmentId) && + input.isWorking(thread) + ); +} + const SIDEBAR_MARKER_PREFIX = "sidebar-marker-"; export type SidebarListMarker = diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 53475d57c18d9..862c660af4ecf 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1,3 +1,4 @@ +import { liveShellEnvironmentIdsAtom } from "../state/shell"; import { attachSidebarTree, SIDEBAR_TREE_PROPS } from "../lib/sidebarTree"; import { type EnvironmentId, type ScopedProjectRef } from "@t3tools/contracts"; import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; @@ -138,6 +139,7 @@ import { useNowMinute } from "../hooks/useNowMinute"; import { useEnvironmentIdentities, useConnectedEnvironmentIds, + useEnvironmentConnectionSummaries, useEnvironmentMachines, usePrimaryEnvironmentId, } from "../state/environments"; @@ -181,6 +183,8 @@ import { deleteSelectedThreadEntries, filterSidebarProjectScopeItems, firstValidTimestampMs, + belongsInSidebarWorkingShelf, + isSidebarEnvironmentDisconnected, isSidebarNestedLinkClick, isTrailingDoubleClick, orderItemsByPreferredIds, @@ -348,12 +352,17 @@ interface SidebarThreadPartitionInput { readonly workingShelfEnabled: boolean; /** Boring mode: folders list active threads by the user's latest message. */ readonly sortActiveBySend: boolean; + readonly disconnectedEnvironmentIds: ReadonlySet; // Snooze wakes, the queued-turn grace and the Working shelf's exit grace depend // on the clock, so the minute tick, the precise snooze-wake tick and the inbox // tracker's expiry version are inputs: a new key repartitions. readonly clockKey: string; } +function scrollSidebarToTop(content: HTMLElement | null) { + content?.closest("[data-slot=scroll-area-viewport]")?.scrollTo({ top: 0 }); +} + function threadShellKey(thread: Pick): string { return scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); } @@ -429,6 +438,18 @@ function useSidebarThreads(input: { // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; + const environmentConnections = useEnvironmentConnectionSummaries(); + const liveShellEnvironmentIds = useAtomValue(liveShellEnvironmentIdsAtom); + const disconnectedEnvironmentIds = new Set( + environmentConnections + .filter((environment) => + isSidebarEnvironmentDisconnected( + environment.connectionState, + liveShellEnvironmentIds.has(environment.environmentId), + ), + ) + .map((environment) => environment.environmentId), + ); const inboxReturnsVersion = useSyncExternalStore( inboxReturns.subscribe, inboxReturns.getSnapshot, @@ -473,6 +494,7 @@ function useSidebarThreads(input: { optimisticDrop, workingShelfEnabled, sortActiveBySend: folderGroups !== null, + disconnectedEnvironmentIds, clockKey: `${nowMinute}:${snoozeWakeClock}:${inboxReturnsVersion}`, }); @@ -608,6 +630,7 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { optimisticDrop, workingShelfEnabled, sortActiveBySend, + disconnectedEnvironmentIds, } = input; const preciseNow = new Date().toISOString(); const visible = filterSidebarV2VisibleThreads(threads, scopedProjectKeys, delegatedUnderParent); @@ -616,8 +639,11 @@ function partitionSidebarThreads(input: SidebarThreadPartitionInput) { const active: EnvironmentThreadShell[] = []; const working: EnvironmentThreadShell[] = []; const inbox = (thread: EnvironmentThreadShell, manuallyMoved = false) => - workingShelfEnabled && - (manuallyMoved ? isThreadWorking(thread) : inboxObservation.isWorking(thread)) + belongsInSidebarWorkingShelf(thread, { + enabled: workingShelfEnabled, + disconnectedEnvironmentIds, + isWorking: manuallyMoved ? isThreadWorking : inboxObservation.isWorking, + }) ? working : active; const snoozed: EnvironmentThreadShell[] = []; @@ -1029,6 +1055,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const [renamingTitle, setRenamingTitle] = useState(""); const settlingThreadKeysRef = useRef(new Set()); const threadListRef = useRef(null); + const sidebarContentRef = useRef(null); const dragLabelOffsetRef = useRef(0); const listMotionRef = useRef | null>(null); const [dragState, setDragState] = useState<{ @@ -1054,9 +1081,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; // A selection made under one scope can hold threads the next scope hides. + // The viewport outlives the scope and does not anchor, so a new list starts at the top. const setProjectScopeKeys = (keys: readonly string[]) => { clearSelection(); setPersistedProjectScopeKeys(keys); + scrollSidebarToTop(sidebarContentRef.current); }; // A scope whose project is gone reads as all projects once every snapshot has // loaded. The stored keys are left alone, so the scope returns with its project. @@ -1965,10 +1994,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve dragState === null && sidebarListItems.length + visibleDraftSessionCount > 0; // Cache on both fields so layout-key changes trigger the effect even when animate is unchanged. const listMotionPass = { layoutKey: listMotionLayoutKey, animate: listMotionAnimate }; + const shelfExpansionKey = [workingShelfExpanded, snoozedShelfExpanded, settledShelfExpanded].join( + ":", + ); + const previousShelfExpansionKeyRef = useRef(shelfExpansionKey); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the list motion controller to animate or not after each layout-affecting commit useLayoutEffect(() => { - listMotionRef.current?.update(listMotionPass.animate); - }, [listMotionPass]); + // Shelf rows would travel over stationary headers below the bottom-anchored shelf. + const shelvesUnchanged = previousShelfExpansionKeyRef.current === shelfExpansionKey; + previousShelfExpansionKeyRef.current = shelfExpansionKey; + listMotionRef.current?.update(listMotionPass.animate && shelvesUnchanged); + }, [listMotionPass, shelfExpansionKey]); const handleThreadDragOver = (event: DragOverEvent) => { const target = event.over ? resolveSidebarDropTarget(sidebarListItems, String(event.active.id), String(event.over.id)) @@ -2940,6 +2976,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve @@ -3012,10 +3049,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} + {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} closeType === "keyboard"} > ) : status === "approval" ? ( + ) : status === "limited" ? ( + ) : status === "failed" ? ( ) : ( diff --git a/apps/web/src/components/ThreadStatusIndicators.linkedPr.browser.test.tsx b/apps/web/src/components/ThreadStatusIndicators.linkedPr.browser.test.tsx new file mode 100644 index 0000000000000..125777f36ca53 --- /dev/null +++ b/apps/web/src/components/ThreadStatusIndicators.linkedPr.browser.test.tsx @@ -0,0 +1,67 @@ +import { EnvironmentId, type ThreadPullRequestLink } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { AppAtomRegistryProvider } from "../rpc/atomRegistry"; +import { makeThreadFixture } from "../test-fixtures"; +import { ThreadRowLeadingStatus } from "./ThreadStatusIndicators"; + +const environmentId = EnvironmentId.make("environment-test"); + +vi.mock(import("../state/entities"), async (original) => ({ + ...(await original()), + useProject: () => null, + useServerConfigs: (() => + new Map([ + [environmentId, { environment: { capabilities: { threadPullRequests: true } } }], + ])) as never, +})); + +it("updates palette PR status from linked snapshots without a legacy link or branch PR", async () => { + const link: ThreadPullRequestLink = { + host: "github.com", + repository: "example/repo", + number: 7, + url: "https://github.com/example/repo/pull/7", + source: "manual", + linkedAt: "2026-01-01T00:00:00Z", + stack: null, + snapshot: { + state: "merged", + title: "Linked change", + headBranch: "deleted-branch", + baseBranch: "main", + isDraft: false, + updatedAt: null, + syncedAt: "2026-01-03T00:00:00Z", + }, + }; + const row = (pullRequest: ThreadPullRequestLink) => ( + + + + ); + // Coder: the labels use merge request wording. + await using screen = await render(row(link)); + await expect.element(screen.getByLabelText("MR !7 - Merged: Linked change")).toBeVisible(); + await expect.element(screen.getByLabelText("MR !7, status pending")).not.toBeInTheDocument(); + + await screen.rerender(row({ ...link, snapshot: null })); + await expect.element(screen.getByLabelText("MR !7, status pending")).toBeVisible(); + await expect + .element(screen.getByLabelText("MR !7 - Merged: Linked change")) + .not.toBeInTheDocument(); + + await screen.rerender( + row({ ...link, snapshot: { ...link.snapshot!, state: "open", isDraft: true } }), + ); + await expect.element(screen.getByLabelText("MR !7 - Draft: Linked change")).toBeVisible(); + await expect.element(screen.getByLabelText("MR !7, status pending")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 3adb0bb174b34..8385e9beceaed 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -675,6 +675,8 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar thread.environmentId, thread.linkedPullRequest, leaseLiveStatus, + thread.pullRequests, + thread.branchPullRequest, ); const gitStatus = useEnvironmentQuery( leaseLiveStatus && @@ -697,8 +699,11 @@ export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummar linkedPullRequest: thread.linkedPullRequest, linkedPullRequestStatus: linkedPullRequest, }; - const pr = resolveDisplayedThreadPr(displayedPrInput); - const prStatus = prStatusIndicator(pr, resolveDisplayedThreadPrProvider(displayedPrInput)); + const pr = linkedPullRequest?.pr ?? resolveDisplayedThreadPr(displayedPrInput); + const prStatus = prStatusIndicator( + pr, + linkedPullRequest?.sourceControlProvider ?? resolveDisplayedThreadPrProvider(displayedPrInput), + ); const threadStatus = resolveThreadStatusPill({ thread: { ...thread, diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsx index cbe5ad8cddb24..2b90b09f68e77 100644 --- a/apps/web/src/components/chat/AssistantCitationChip.tsx +++ b/apps/web/src/components/chat/AssistantCitationChip.tsx @@ -31,6 +31,7 @@ import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCom import { observeAssistantCitationCommentSource } from "./AssistantCitationSource"; import { composerFloatingLayerProps } from "./composerEventScope"; import { observeResize } from "~/lib/observeResize"; +import { textDirection } from "~/textDirection"; export function AssistantCitationChip({ citation, @@ -130,7 +131,9 @@ export function AssistantCitationChip({ aria-label={`View cited assistant text: ${label}`} >
); } diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx index d9fd60645618e..0a8357bb9baba 100644 --- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx +++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx @@ -1,5 +1,6 @@ import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts"; import { useState, type Ref } from "react"; +import { textDirection } from "~/textDirection"; import { Button } from "../ui/button"; @@ -51,6 +52,7 @@ export function AssistantCitationCommentEditor({ aria-invalid={commentTooLong || undefined} placeholder="Add an optional comment..." rows={2} + dir={textDirection(comment)} className="field-sizing-content block max-h-40 min-h-16 w-full resize-none bg-transparent px-1 py-1.5 text-base outline-none placeholder:text-muted-foreground sm:text-sm" value={comment} onChange={(event) => { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2ab287737a226..94124a0cf97ee 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -877,11 +877,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const selectedProviderSlashCommands = selectedProviderStatus ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd) : NO_PROVIDER_SLASH_COMMANDS; - const refreshWorkspaceSnapshotOnTyping = useProviderWorkspaceSnapshotRefresh({ - environmentId, - gitCwd, - instanceId: selectedProviderEntry?.instanceId, - }); + const { refresh: refreshWorkspaceSnapshotOnTyping, scanning: workspaceSkillsScanning } = + useProviderWorkspaceSnapshotRefresh({ + environmentId, + gitCwd, + instanceId: selectedProviderEntry?.instanceId, + }); const selectedPromptEffort = composerProviderState.promptEffort; const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; @@ -1062,6 +1063,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedProviderSkills, selectedProviderSlashCommands, showSkillsInSlashMenu: settings.showSkillsInSlashMenu, + workspaceSkillsScanning, questionAttachmentTarget, }); @@ -3125,7 +3127,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? isComposerMenuLoading ? composerTriggerKind === "pull-request" ? "Finding merge request..." - : "Searching workspace files..." + : composerTriggerKind === "skill" || composerTriggerKind === "slash-command" + ? "Searching workspace skills..." + : "Searching workspace files..." : composerMenuEmptyState : ""}
diff --git a/apps/web/src/components/chat/ChatHeader.browser.test.tsx b/apps/web/src/components/chat/ChatHeader.browser.test.tsx new file mode 100644 index 0000000000000..e1556f0b54657 --- /dev/null +++ b/apps/web/src/components/chat/ChatHeader.browser.test.tsx @@ -0,0 +1,75 @@ +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +const persisted = vi.hoisted(() => ({ title: "" })); +vi.mock(import("../../state/session"), async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentScope: () => true, + readEnvironmentScope: () => true, +})); +vi.mock(import("../../state/use-orchestration-command"), async (importOriginal) => ({ + ...(await importOriginal()), + useOrchestrationCommand: (() => + async ({ input }: { input: { title: string } }) => { + persisted.title = input.title; + return { _tag: "Success" }; + }) as never, +})); +// Coder: the header's workspace latency badge reads the Coder context the app shell provides. +vi.mock(import("../CoderWorkspaceLatency"), () => ({ CoderWorkspaceLatency: () => null })); +vi.mock(import("~/hooks/useThreadActionMenu"), () => ({ + useThreadActionMenu: () => ({ openMenu: () => {}, closeMenu: () => {} }), +})); + +import { render } from "../../../test/render"; +import { ChatHeader } from "./ChatHeader"; + +function header(title: string) { + return ( + <> + {}} + rightPanelOpen={false} + onNewThreadInProject={() => {}} + /> +
Outside rename
+ + ); +} + +it.each(["blur", "Enter"] as const)( + "preserves a concurrent title update when an untouched rename ends with %s", + async (finish) => { + persisted.title = "New thread"; + await using screen = await render(header(persisted.title)); + await screen.getByRole("button", { name: "Thread actions for New thread" }).dblClick(); + const input = screen.getByRole("textbox", { name: "Thread title" }); + await expect.element(input).toHaveValue("New thread"); + + persisted.title = "Fix login redirect"; + await screen.rerender(header(persisted.title)); + if (finish === "Enter") await userEvent.keyboard("{Enter}"); + else await screen.getByText("Outside rename").click(); + + await expect.element(input).not.toBeInTheDocument(); + expect(persisted.title).toBe("Fix login redirect"); + + await screen.rerender(header(persisted.title)); + await screen.getByRole("button", { name: "Thread actions for Fix login redirect" }).dblClick(); + await screen.getByRole("textbox", { name: "Thread title" }).fill("My edited title"); + persisted.title = "Another concurrent title"; + await screen.rerender(header(persisted.title)); + await userEvent.keyboard("{Enter}"); + await expect + .element(screen.getByRole("textbox", { name: "Thread title" })) + .not.toBeInTheDocument(); + expect(persisted.title).toBe("My edited title"); + }, +); diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 6e5f2f7b5cc60..7c22700452d39 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -172,7 +172,10 @@ export const ChatHeader = memo(function ChatHeader({ const commitRename = (title: string) => { setRenaming(null); if (!readEnvironmentScope(activeThreadEnvironmentId, AuthOrchestrationOperateScope)) return; - const resolution = resolveRenameCommit({ title, originalTitle: activeThreadTitle }); + const resolution = resolveRenameCommit({ + title, + originalTitle: renamingTitle ?? activeThreadTitle, + }); if (resolution.action === "reject-empty") { toastManager.add({ type: "warning", title: "Thread title cannot be empty" }); return; diff --git a/apps/web/src/components/chat/ChildThreadApprovals.browser.test.tsx b/apps/web/src/components/chat/ChildThreadApprovals.browser.test.tsx new file mode 100644 index 0000000000000..ef136a1760137 --- /dev/null +++ b/apps/web/src/components/chat/ChildThreadApprovals.browser.test.tsx @@ -0,0 +1,52 @@ +import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests"; +import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import { AsyncResult, Atom } from "effect/reactivity"; +import { expect, it, vi } from "vite-plus/test"; + +import { render } from "../../../test/render"; + +const state = vi.hoisted(() => ({ respond: vi.fn(), approvalsAtom: null as unknown })); + +vi.mock("../../state/session", () => ({ useEnvironmentScope: () => true })); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => state.respond })); +vi.mock("../../state/threads", () => ({ + childThreadApprovalsAtom: () => state.approvalsAtom, + threadEnvironment: { respondToApproval: {} }, +})); + +import { ChildThreadApprovals } from "./ChildThreadApprovals"; + +function setup() { + state.respond.mockReset(); + state.respond + .mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Child environment offline")))) + .mockResolvedValueOnce(AsyncResult.success(undefined)); + const thread = { + environmentId: EnvironmentId.make("child-env"), + threadId: ThreadId.make("child"), + }; + state.approvalsAtom = Atom.make>([ + { + thread, + title: "Compile task", + approval: { + requestId: RuntimeRequestId.make("approval"), + requestKind: "command", + detail: "Run compiler", + createdAt: "2026-11-01T00:00:00.000Z", + responseCapability: "live", + }, + }, + ]); + return thread; +} + +it("shows a failed decision and clears the error when the user retries", async () => { + const thread = setup(); + await using screen = await render(); + await screen.getByRole("button", { name: "Approve", exact: true }).click(); + await expect.element(screen.getByRole("alert")).toHaveTextContent("Child environment offline"); + await screen.getByRole("button", { name: "Approve", exact: true }).click(); + await expect.element(screen.getByRole("alert")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/chat/ChildThreadApprovals.tsx b/apps/web/src/components/chat/ChildThreadApprovals.tsx new file mode 100644 index 0000000000000..5a7cb3074b4a6 --- /dev/null +++ b/apps/web/src/components/chat/ChildThreadApprovals.tsx @@ -0,0 +1,95 @@ +import { useAtomValue } from "@effect/atom-react"; +import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; +import type { ChildThreadApproval } from "@t3tools/client-runtime/state/thread-requests"; +import { fullAccessOverrideExplanation } from "@t3tools/client-runtime/state/thread-requests"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useState } from "react"; +import { useEnvironmentScope } from "../../state/session"; +import { childThreadApprovalsAtom, threadEnvironment } from "../../state/threads"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions"; + +function ChildApproval({ entry }: { entry: ChildThreadApproval }) { + const canRespond = useEnvironmentScope(entry.thread.environmentId, AuthOrchestrationOperateScope); + const respond = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false }); + const [responding, setResponding] = useState(false); + const [error, setError] = useState(null); + const { approval } = entry; + return ( +
+

Approval needed from {entry.title}

+
+        {approval.detail || approval.requestKind}
+      
+ {approval.appName ?

{approval.appName}

: null} + {approval.responseCapability !== "live" ? ( +

+ Provider process is gone. Interrupt or restart the child thread to respond. +

+ ) : null} + {approval.reason ?

{approval.reason}

: null} + {approval.fullAccessOverride ? ( +

+ {fullAccessOverrideExplanation(approval.fullAccessOverride)} +

+ ) : null} +
+ { + if (!canRespond || responding) return; + setResponding(true); + setError(null); + const result = await respond({ + environmentId: entry.thread.environmentId, + input: { threadId: entry.thread.threadId, requestId, decision }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const failure = squashAtomCommandFailure(result); + setError( + failure instanceof Error ? failure.message : "Failed to submit approval decision.", + ); + } + setResponding(false); + return result; + }} + /> +
+ {error !== null ? ( +

+ {error} +

+ ) : null} +
+ ); +} + +export function ChildThreadApprovals({ threadRef }: { threadRef: ScopedThreadRef | null }) { + const approvals = useAtomValue(childThreadApprovalsAtom(threadRef)); + if (approvals.length === 0) return null; + return ( +
+ {approvals.map((entry) => ( + + ))} +
+ ); +} diff --git a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx index bf83b014b7f6f..4c9702abe5f31 100644 --- a/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerBannerStack.browser.test.tsx @@ -1,6 +1,7 @@ import { InfoIcon } from "lucide-react"; import type { ReactNode } from "react"; import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; @@ -123,3 +124,28 @@ it("shows the details button while text or nested text is cut, until it fits aga await screen.rerender({noticeRow("4rem", "Ready")}); await expect.element(details).not.toBeInTheDocument(); }); + +it("opens the details of a long notice right above its button", async () => { + const viewport = { width: window.innerWidth, height: window.innerHeight }; + await page.viewport(1280, 800); + await using _viewport = { + [Symbol.asyncDispose]: () => page.viewport(viewport.width, viewport.height), + }; + const script = Array.from({ length: 400 }, (_, line) => `echo "line ${line}"`).join("\n"); + const container = document.createElement("div"); + container.style.cssText = "position: fixed; bottom: 4rem; right: 4rem;"; + await using screen = await render(noticeRow("40rem", script), { container }); + const details = screen.getByRole("button", { name: "Show details" }); + await userEvent.hover(details); + const popup = page.getByLabelText("Notice details"); + await expect.element(popup).toBeVisible(); + + // A positioner sized to the unscrolled text flips beside the button and covers it. + await vi.waitFor(() => { + const gap = + details.element().getBoundingClientRect().top - + popup.element().getBoundingClientRect().bottom; + expect(gap).toBeGreaterThanOrEqual(0); + expect(gap).toBeLessThan(8); + }); +}); diff --git a/apps/web/src/components/chat/ComposerBannerStack.tsx b/apps/web/src/components/chat/ComposerBannerStack.tsx index 61778f817dc37..ee602dcdac1eb 100644 --- a/apps/web/src/components/chat/ComposerBannerStack.tsx +++ b/apps/web/src/components/chat/ComposerBannerStack.tsx @@ -155,9 +155,7 @@ export function NoticeText({ side="top" className="max-w-[min(30rem,calc(100vw-2rem))] whitespace-normal wrap-anywhere [--inline-button-text-align:start] [--inline-button-white-space:normal] [&_[data-slot=inline-button]]:max-w-full" > - - {children} - + {children} ) : null} diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index ed093794e64b1..434c2c0358d17 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -152,7 +152,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {

{props.isLoading - ? props.triggerKind === "skill" + ? props.triggerKind === "skill" || props.triggerKind === "slash-command" ? "Searching workspace skills..." : props.triggerKind === "pull-request" ? "Finding merge request..." diff --git a/apps/web/src/components/chat/ComposerControl.tsx b/apps/web/src/components/chat/ComposerControl.tsx index 139e80d081e4e..9c1e92d93641f 100644 --- a/apps/web/src/components/chat/ComposerControl.tsx +++ b/apps/web/src/components/chat/ComposerControl.tsx @@ -12,7 +12,7 @@ function composerControlClassName(size: ComposerControlSize, className?: string) "relative inline-flex shrink-0 cursor-pointer items-center justify-center whitespace-nowrap rounded-(--control-radius) border border-transparent text-base outline-none hover:bg-accent data-pressed:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-64 data-disabled:pointer-events-none data-disabled:opacity-64 pointer-coarse:after:absolute pointer-coarse:after:size-full pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 [&:active:not([aria-haspopup])]:scale-[0.97] [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg]:-mx-0.5 [&_svg[data-composer-control-icon]]:mx-0", "[&_:is([data-composer-control-label],[data-chat-provider-model-picker-label])]:[text-box:trim-both_cap_alphabetic] supports-[text-box:trim-both_cap_alphabetic]:[&_:is([data-composer-control-label],[data-chat-provider-model-picker-label])]:py-1.5", size === "xs" - ? "h-7 gap-1 px-1.75 font-normal text-foreground/70 text-sm hover:text-foreground dark:text-muted-foreground sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5 [&_svg]:mx-0 [&_svg[data-composer-control-chevron]]:ms-0 [&_svg[data-composer-control-chevron]]:-me-1" + ? "h-7 gap-1 has-[[data-composer-label]]:gap-1.5 px-1.75 font-normal text-foreground/70 text-sm hover:text-foreground dark:text-muted-foreground sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5 [&_svg]:mx-0 [&_svg[data-composer-control-chevron]]:ms-0 [&_svg[data-composer-control-chevron]]:-me-1" : "h-7 gap-1.5 px-2 font-medium text-foreground/80 [&_svg:not([class*='text-'])]:text-muted-foreground hover:text-foreground sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4", "aria-pressed:bg-accent aria-pressed:text-accent-foreground aria-pressed:hover:bg-accent/80", className, diff --git a/apps/web/src/components/chat/ComposerControlsBar.tsx b/apps/web/src/components/chat/ComposerControlsBar.tsx index 8523c25927fa4..0002beeaf9fef 100644 --- a/apps/web/src/components/chat/ComposerControlsBar.tsx +++ b/apps/web/src/components/chat/ComposerControlsBar.tsx @@ -193,6 +193,8 @@ export function ComposerControlsBar(props: { environmentId={environmentId} compact={false} isComposerOwned + // The trigger grows away from this edge when its model or effort label changes. + popupAlign={composerControlsCollapsed ? "start" : "end"} disabled={providerCatalogPending || isSendBusy} multipleModelsEnabled={multipleModelsEnabled} multipleModelSelections={multipleModelSelections} diff --git a/apps/web/src/components/chat/ComposerImageThumbnail.tsx b/apps/web/src/components/chat/ComposerImageThumbnail.tsx index e9de2aa93b302..68158c7151b2f 100644 --- a/apps/web/src/components/chat/ComposerImageThumbnail.tsx +++ b/apps/web/src/components/chat/ComposerImageThumbnail.tsx @@ -1,24 +1,15 @@ -import { memo, Suspense, use, type ReactNode } from "react"; +import { memo, useLayoutEffect, useState, type ReactNode } from "react"; + +import { cn } from "~/lib/utils"; import { createComposerImageThumbnail, + isHeicImageFile, + MAX_COMPRESSIBLE_SOURCE_BYTES, readComposerImageThumbnail, } from "../../lib/imageCompression"; -export const ComposerImageThumbnail = memo(function ComposerImageThumbnail(props: { - file: File; - alt: string; - className: string; - fallback: ReactNode; -}) { - return ( - - - - ); -}); - -function ThumbnailImage({ +export const ComposerImageThumbnail = memo(function ComposerImageThumbnail({ file, alt, className, @@ -29,8 +20,63 @@ function ThumbnailImage({ className: string; fallback: ReactNode; }) { - // A settled thumbnail paints synchronously instead of suspending for a tick. - const settled = readComposerImageThumbnail(file); - const src = settled === undefined ? use(createComposerImageThumbnail(file)) : settled; - return src ? {alt} : fallback; -} + const [preview, setPreview] = useState(() => ({ + file, + src: readComposerImageThumbnail(file), + })); + const [loadedSrc, setLoadedSrc] = useState(null); + const [failedSrc, setFailedSrc] = useState(null); + const src = preview.file === file ? preview.src : readComposerImageThumbnail(file); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- owns the local blob URL and decodes its replacement before swapping the visible image + useLayoutEffect(() => { + let disposed = false; + let localUrl: string | undefined; + const cached = readComposerImageThumbnail(file); + if ( + file.size <= MAX_COMPRESSIBLE_SOURCE_BYTES && + !isHeicImageFile(file) && + cached === undefined + ) { + localUrl = URL.createObjectURL(file); + // oxlint-disable-next-line react/set-state-in-effect -- the blob URL is created and revoked by this effect + setPreview({ file, src: localUrl }); + } + if (cached === undefined) { + void createComposerImageThumbnail(file).then(async (thumbnail) => { + if (disposed) return; + if (!thumbnail) { + if (!localUrl) setPreview({ file, src: null }); + return; + } + const image = new Image(); + image.src = thumbnail; + try { + await image.decode(); + if (!disposed) setPreview({ file, src: thumbnail }); + } catch { + // Keep the local preview if the thumbnail cannot be decoded. + } + }); + } + return () => { + disposed = true; + if (localUrl) URL.revokeObjectURL(localUrl); + }; + }, [file]); + + return src && failedSrc !== src ? ( + { + if (image?.complete && image.naturalWidth > 0) setLoadedSrc(src); + }} + src={src} + alt={alt} + onLoad={() => setLoadedSrc(src)} + onError={() => setFailedSrc(src)} + className={cn(className, loadedSrc !== src && "invisible")} + /> + ) : src === undefined ? null : ( + fallback + ); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx new file mode 100644 index 0000000000000..3d704b5209305 --- /dev/null +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -0,0 +1,125 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ProviderOptionSelection, + type ServerProviderModel, +} from "@t3tools/contracts"; +import { createModelCapabilities } from "@t3tools/shared/model"; +import { useState } from "react"; +import { expect, it } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { render } from "../../../test/render"; +import { ComposerEffortColumn, describeComposerEffort } from "./ComposerModelEffort"; +import type { TraitsSelectionInput } from "./TraitsPicker"; + +// Shaped like Devin over ACP: its session mode comes first, and its reasoning id is its own. +const models: ReadonlyArray = [ + { + slug: "fusion", + name: "Fusion (Claude Opus 5.5 Medium + SWE-2 High)", + isCustom: false, + capabilities: createModelCapabilities({ + optionDescriptors: [ + { + id: "mode", + label: "Session Mode", + type: "select", + currentValue: "bypass", + options: [ + { id: "code", label: "Code" }, + { id: "plan", label: "Plan" }, + { id: "bypass", label: "Bypass Permissions" }, + ], + }, + { + id: "thought_level", + label: "Thinking", + type: "select", + role: "reasoning", + currentValue: "medium", + options: [ + { id: "low", label: "Low" }, + { id: "medium", label: "Medium" }, + { id: "high", label: "High" }, + ], + }, + { + id: "speed", + label: "Speed", + type: "select", + currentValue: "standard", + options: [ + { id: "standard", label: "Standard" }, + { id: "fast", label: "Fast" }, + ], + }, + { id: "auto_approve", label: "Auto-approve tools", type: "boolean", currentValue: false }, + ], + }), + }, +]; + +function traitsInput( + modelOptions: ReadonlyArray, + onModelOptionsChange: (next: ReadonlyArray | undefined) => void, +): TraitsSelectionInput { + return { + provider: ProviderDriverKind.make("acpRegistry"), + instanceId: ProviderInstanceId.make("devin"), + models, + model: "fusion", + modelOptions, + planModeEnabled: false, + onModelOptionsChange, + }; +} + +function Column() { + const [options, setOptions] = useState>([]); + const traits = traitsInput(options, (next) => setOptions(next ?? [])); + return ( + <> +

+ +
+

{describeComposerEffort(traits, "bars", "sm").suffix}

+ + ); +} + +it("draws an agent's reasoning as bars and keeps its mode out of the levels", async () => { + await using screen = await render(, { router: false }); // no routes involved + const status = screen.getByRole("status"); + expect(status.element().querySelector("[data-composer-effort-glyph]")).not.toBeNull(); + await expect.element(status).toHaveTextContent(""); + + const levels = screen.getByRole("radiogroup", { name: "Thinking" }); + await expect.element(levels.getByRole("radio")).toHaveLength(3); + await expect.element(screen.getByRole("radio", { name: "Plan" })).not.toBeInTheDocument(); + + // Up and Down walk from the levels through the option rows without opening their menus. + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("{ArrowDown}{ArrowDown}{ArrowDown}"); + const speed = screen.getByRole("button", { name: "Speed: Standard" }); + await expect.element(speed).toHaveFocus(); + await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); + await userEvent.keyboard("{ArrowRight}"); + await expect.element(page.getByRole("menuitemradio", { name: "Standard" })).toHaveFocus(); + await userEvent.keyboard("{ArrowLeft}"); + await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); + await expect.element(speed).toHaveFocus(); + + await userEvent.click(screen.getByText("Auto-approve tools")); + await expect + .element(screen.getByRole("switch", { name: "Auto-approve tools" })) + .toHaveAttribute("aria-checked", "true"); + + await userEvent.click(screen.getByRole("button", { name: "Session Mode: Bypass Permissions" })); + await userEvent.click(page.getByRole("menuitemradio", { name: "Plan" })); + await expect + .element(screen.getByRole("button", { name: "Session Mode: Plan" })) + .toBeInTheDocument(); + await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 5ce77c60b1078..3a863936101b2 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -1,16 +1,25 @@ import { buildTraitsTriggerDisplay, getDescriptorStringValue, - REASONING_SELECT_DESCRIPTOR_IDS, + isReasoningControl, selectableProviderOptionChoices, } from "@t3tools/client-runtime/model-traits"; import type { ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts"; import type { EffortDisplay } from "@t3tools/contracts/settings"; -import { CheckIcon, ChevronUpIcon } from "lucide-react"; -import { type KeyboardEvent, type ReactNode, use, useRef } from "react"; +import { getProviderOptionCurrentLabel } from "@t3tools/shared/model"; +import { CheckIcon, ChevronRightIcon, ChevronUpIcon } from "lucide-react"; +import { type KeyboardEvent, type ReactNode, use, useRef, useState } from "react"; import { cn } from "~/lib/utils"; -import { Menu, MenuPopup, MenuTrigger } from "../ui/menu"; +import { + Menu, + MenuPopup, + MenuRadioGroup, + MenuRadioItem, + MenuRadioItemIndicator, + MenuTrigger, +} from "../ui/menu"; +import { Switch } from "../ui/switch"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ComposerControlSize } from "./ComposerControl"; import { ComposerPermissionsSection, type RuntimeModeOption } from "./ComposerFooterControls"; @@ -51,8 +60,8 @@ type ColumnControl = | { kind: "boolean"; descriptor: BooleanDescriptor }; /** - * The column lists the model's reasoning control first, under the header that names it, then - * its other options. + * The column lists the model's reasoning levels under the header that names it. Other options, + * such as an agent's session mode, sit below as one row each. */ function columnControls( provider: TraitsSelectionInput["provider"], @@ -64,8 +73,7 @@ function columnControls( ...columnSelects.map((descriptor) => ({ kind: "select" as const, descriptor })), ...columnToggles.map((descriptor) => ({ kind: "boolean" as const, descriptor })), ]; - const effort = - controls.find((control) => REASONING_SELECT_DESCRIPTOR_IDS.has(control.descriptor.id)) ?? null; + const effort = controls.find((control) => isReasoningControl(control.descriptor)) ?? null; return { effort, others: controls.filter((control) => control !== effort) }; } @@ -94,20 +102,40 @@ export function describeComposerEffort( modelSelection, reportedModelSelection: traits.reportedModelSelection, }); + // The same reasoning control the column lists, wherever the agent put it among its options. + const reasoning = + columnControls(traits.provider, visibility.selectDescriptors, visibility.booleanDescriptors) + .effort?.descriptor ?? null; + const ultrathink = visibility.ultrathinkPromptControlled && reasoning === primary; const glyph = - primary && REASONING_SELECT_DESCRIPTOR_IDS.has(primary.id) + reasoning?.type === "select" ? resolveEffortGlyph( - primary, - visibility.ultrathinkPromptControlled + reasoning, + ultrathink ? "ultrathink" - : getDescriptorStringValue(primary, modelSelection, traits.reportedModelSelection), + : getDescriptorStringValue(reasoning, modelSelection, traits.reportedModelSelection), ) : null; - // Without a reasoning select the whole label is the word; it already names speed and the rest. // Workflow levels such as Ultracode always show their name; the setting names every level. const word = glyph ? (glyph.special ?? (effortDisplay === "label" ? glyph.label : null)) - : display.label; + : !reasoning + ? null + : reasoning.type === "boolean" + ? `${reasoning.label} ${reasoning.currentValue === true ? "On" : "Off"}` + : ultrathink + ? "Ultrathink" + : getProviderOptionCurrentLabel(reasoning, modelSelection, traits.reportedModelSelection); + const fast = display.speedLabel === "Fast" || display.speedLabel === "Ultrafast"; + // Agent options such as modes live in the picker; the trigger adds only the context window. + const contextWindow = + visibility.contextWindowDescriptor && + getProviderOptionCurrentLabel( + visibility.contextWindowDescriptor, + modelSelection, + traits.reportedModelSelection, + ); + if (!word && !glyph && !fast && !contextWindow) return { suffix: null, detail: display.label }; return { detail: display.label, suffix: ( @@ -118,22 +146,22 @@ export function describeComposerEffort( size === "sm" && "-ms-0.5", )} > - {word !== null ? ( - {word} + {word ? ( + + {word} + ) : glyph ? ( ) : null} - {glyph && (display.speedLabel === "Fast" || display.speedLabel === "Ultrafast") ? ( - - ) : null} - {glyph && display.otherLabels.length > 0 ? ( + {fast ? : null} + {contextWindow ? ( - {display.otherLabels.join(" · ")} + {contextWindow} ) : null} @@ -150,10 +178,10 @@ function ColumnRow(props: { /** Shown on hover; the column is too narrow to print it under the label. */ description?: string | undefined; selected: boolean; + /** The column's one tab stop: the selected level, else the first when none shows as selected. */ + tabStop: boolean; isDefault?: boolean | undefined; disabled?: boolean; - /** A level of the reasoning control, where focus lands after a model pick. */ - level: boolean; onPick: () => void; }) { const rowProps = { @@ -162,9 +190,10 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - "data-effort-level": props.level || undefined, - // The reasoning control holds the column's one tab stop; Up and Down move between rows. - tabIndex: props.selected && props.level ? 0 : -1, + // Focus lands on a level after a model pick. + "data-effort-level": true, + // Up and Down move between rows. + tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, onClick: props.onPick, } as const; @@ -194,6 +223,8 @@ function ColumnRow(props: { function moveBetweenRows(event: KeyboardEvent) { if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + // An option's side menu is a React child here, but it moves through its own items. + if (!event.currentTarget.contains(event.target as Node)) return; const rows = Array.from( event.currentTarget.querySelectorAll("[data-effort-row]:not(:disabled)"), ); @@ -230,66 +261,222 @@ function EffortLevels(props: { traits: TraitsSelectionInput }) { ); } if (!effort && others.length === 0) return ; - const renderControl = (control: ColumnControl) => { - const isEffort = control === effort; - const { descriptor } = control; - if (control.kind === "boolean") { - return ( + // Ultrathink in the prompt locks the levels; the first option then holds the tab stop. + const locked = + effort?.descriptor.id === traits.primarySelectDescriptor?.id && traits.ultrathinkInBodyText; + return ( + <> + {effort ? : null} + {others.length > 0 ? (
- {isEffort ? null :
{descriptor.label}
} - {([true, false] as const).map((value) => ( - traits.changeBoolean(descriptor.id, value)} - /> - ))} + {others.map((control, index) => + control.kind === "boolean" ? ( + + ) : ( + + ), + )}
- ); - } - const locked = - descriptor.id === traits.primarySelectDescriptor?.id && traits.ultrathinkInBodyText; - const value = traits.selectValue(control.descriptor); + ) : null} + + ); +} + +type TraitsSelection = ReturnType; + +function EffortRows(props: { control: ColumnControl; traits: TraitsSelection; locked: boolean }) { + const { control, traits } = props; + const { descriptor } = control; + if (control.kind === "boolean") { return ( -
- {isEffort ? null :
{descriptor.label}
} - {locked ? ( -
- {ULTRATHINK_IN_BODY_NOTE} -
- ) : null} - {selectableProviderOptionChoices(control.descriptor).map((option) => ( +
+ {([true, false] as const).map((value) => ( traits.changeSelect(control.descriptor, option.id)} + key={String(value)} + label={value ? "On" : "Off"} + selected={(control.descriptor.currentValue === true) === value} + tabStop={(control.descriptor.currentValue === true) === value} + onPick={() => traits.changeBoolean(descriptor.id, value)} /> ))}
); - }; + } + const { locked } = props; + const value = traits.selectValue(control.descriptor); + const choices = selectableProviderOptionChoices(control.descriptor); + // An "Ultrathink:" prefix selects a level the column does not offer. + const shown = choices.some((option) => option.id === value); return ( - <> - {effort ? renderControl(effort) : null} - {others.map(renderControl)} - +
+ {locked ? ( +
+ {ULTRATHINK_IN_BODY_NOTE} +
+ ) : null} + {choices.map((option, index) => ( + traits.changeSelect(control.descriptor, option.id)} + /> + ))} +
+ ); +} + +const OPTION_ROW = cn(COLUMN_ROW, "h-auto py-1"); + +/** An option's name over its current value. */ +function OptionRowText(props: { label: string; value: string }) { + return ( + + {props.label} + {props.value} + + ); +} + +/** + * One select besides reasoning, such as an agent's session mode. It names the current choice and + * opens the rest beside the column, so any number of options leaves the levels in place. + */ +function OptionMenuRow(props: { + descriptor: SelectDescriptor; + traits: TraitsSelection; + /** Holds the column's tab stop when the model has no levels. */ + tabStop: boolean; +}) { + const { descriptor, traits } = props; + const [open, setOpen] = useState(false); + const popupRef = useRef(null); + const choices = selectableProviderOptionChoices(descriptor); + const value = traits.selectValue(descriptor); + const current = choices.find((choice) => choice.id === value)?.label ?? ""; + return ( + { + if (!isOpen) return; + const checked = popupRef.current?.querySelector( + '[role="menuitemradio"][aria-checked="true"]', + ); + checked?.focus({ preventScroll: true }); + checked?.scrollIntoView({ block: "nearest" }); + }} + > + {/* No hover opening: an opened menu takes focus, which would steal typing from search. */} + { + if (event.key !== "ArrowRight") return; + event.preventDefault(); + event.stopPropagation(); + setOpen(true); + }} + /> + } + > + + + { + if (event.key !== "ArrowLeft") return; + event.preventDefault(); + event.stopPropagation(); + setOpen(false); + }} + > + { + if (next !== value) traits.changeSelect(descriptor, next); + }} + > + {choices.map((choice) => ( + + + + {choice.label} + {choice.description ? ( + + {choice.description} + + ) : null} + + {choice.isDefault ? ( + Default + ) : null} + + + + ))} + + + + ); +} + +/** A two-state option toggles in place; a menu would add a click for nothing. */ +function OptionSwitchRow(props: { + descriptor: BooleanDescriptor; + traits: TraitsSelection; + tabStop: boolean; +}) { + const { descriptor, traits } = props; + const checked = descriptor.currentValue === true; + return ( + ); } @@ -303,20 +490,22 @@ function NoEffortRow() { export function ComposerEffortColumn(props: { traits: TraitsSelectionInput | null }) { const picker = use(DockedPickerContext); const visibility = props.traits ? getTraitsSectionVisibility(props.traits) : null; - const effort = + const controls = props.traits && visibility ? columnControls( props.traits.provider, visibility.selectDescriptors, visibility.booleanDescriptors, - ).effort + ) : null; return ( <> {/* Matches the search row's box, so one rule runs across the top of the popup. */}
- {effort?.descriptor.label ?? "Effort"} + + {controls?.effort?.descriptor.label ?? (controls?.others.length ? "Options" : "Effort")} + {picker.modelLabel} @@ -325,7 +514,8 @@ export function ComposerEffortColumn(props: { traits: TraitsSelectionInput | nul {/* pt-2.5 puts the first level on the same line as the first model. */}
{props.traits ? : }
diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsx new file mode 100644 index 0000000000000..6e1b387a7412f --- /dev/null +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.direction.browser.test.tsx @@ -0,0 +1,100 @@ +import { EnvironmentId, RuntimeRequestId, ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +vi.mock(import("../ChatMarkdown"), () => ({ + default: (({ text }: { text: string }) =>

{text}

) as never, +})); + +import { render } from "../../../test/render"; +import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; + +type Question = { + header: string; + question: string; + options: { label: string; description: string }[]; +}; + +const renderPanel = (questions: Question[], questionIndex = 0) => + render( + ({ + ...question, + id: `question-${index}`, + multiSelect: false, + })), + }, + ]} + cwd={undefined} + threadRef={{ environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }} + respondingRequestIds={[]} + answers={{}} + questionIndex={questionIndex} + onToggleOption={() => {}} + onAdvance={() => {}} + onDismiss={() => {}} + />, + ); + +it("reads a mostly Hebrew question set right to left", async () => { + await using screen = await renderPanel([ + { + header: "גישה", + question: "איך לבצע את המיגרציה?", + options: [ + { + label: "React Server Components בכל המסכים של האפליקציה", + description: "מסך אחד בכל פעם", + }, + { label: "Keep it on React 18", description: "English only" }, + ], + }, + ]); + + const text = (value: string) => screen.getByText(value, { exact: true }); + await expect.element(text("גישה")).toHaveStyle({ direction: "rtl" }); + await expect + .element(text("React Server Components בכל המסכים של האפליקציה")) + .toHaveStyle({ direction: "rtl" }); + await expect.element(text("מסך אחד בכל פעם")).toHaveStyle({ direction: "rtl" }); + await expect + .element(screen.getByRole("button", { name: /React Server/ })) + .toHaveStyle({ direction: "rtl" }); + await expect.element(text("Keep it on React 18")).toHaveStyle({ direction: "ltr" }); + + await screen.getByTitle("Hide the question and its options").click(); + await expect.element(text("איך לבצע את המיגרציה?")).toHaveStyle({ direction: "rtl" }); +}); + +it("keeps one direction for the whole set when a single question is Hebrew", async () => { + await using screen = await renderPanel( + [ + { + header: "Migration", + question: "How should we move to React Server Components?", + options: [ + { label: "Screen by screen", description: "Lower risk, each step tested alone." }, + { label: "Server Actions for all forms first", description: "Then the rest." }, + ], + }, + { + header: "גרסה", + question: "בחר גרסה", + options: [{ label: "גרסה 3 (חדשה!)", description: "!!!" }], + }, + ], + 1, + ); + + await expect + .element(screen.getByRole("button", { name: /גרסה 3/ })) + .toHaveStyle({ direction: "ltr" }); + await expect + .element(screen.getByText("גרסה 3 (חדשה!)", { exact: true })) + .toHaveStyle({ direction: "rtl" }); +}); diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx index 58ad8e8c0900d..777238f7635e8 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.navigation.browser.test.tsx @@ -17,7 +17,9 @@ vi.mock(import("../ChatMarkdown"), async (importOriginal) => ({ })); import { act, fakeTimers, render } from "../../../test/render"; +import { useComposerDraftStore } from "../../composerDraftStore"; import { makeThreadProjectionFixture } from "../../test-fixtures"; +import { toastManager } from "../ui/toast"; import { usePendingThreadRequests } from "./usePendingThreadRequests"; const threadRef = { environmentId: EnvironmentId.make("env"), threadId: ThreadId.make("thread") }; @@ -89,7 +91,8 @@ function useProbeRequests({ environmentId, projection, loading = false }: ProbeP serverProjection: loading ? null : projection, supportsQuestionAttachments: false, composerDraftTarget: { environmentId, threadId: projection.thread.id }, - setComposerDraftPrompt: () => {}, + setComposerDraftPrompt: (target, prompt) => + useComposerDraftStore.getState().setPrompt(target, prompt), promptRef, composerRef, setThreadError: () => {}, @@ -141,6 +144,43 @@ it("retains answers, selections and question position after leaving chat, includ expect(requests).toMatchObject(expected); }); +it("tells the user when an option click moves their typed answer into the hidden composer draft", async () => { + using _timers = fakeTimers(); + const environmentId = EnvironmentId.make("displaced-environment"); + const draftTarget = { environmentId, threadId: threadRef.threadId }; + const draftPrompt = () => useComposerDraftStore.getState().getComposerDraft(draftTarget)?.prompt; + using toast = vi.spyOn(toastManager, "add"); + await using _screen = await render( + , + ); + + await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental")); + expect(toast).not.toHaveBeenCalled(); + + await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "first try")); + await act(() => requests.onSelectActivePendingUserInputOption("question-0", "Incremental")); + expect(draftPrompt()).toBe("first try"); + expect(toast).toHaveBeenCalledTimes(1); + expect(toast).toHaveBeenCalledWith( + expect.objectContaining({ + type: "info", + title: "Your typed text was set aside", + description: "It will be back in the composer once the question is answered.", + data: { threadRef: draftTarget }, + }), + ); + + await act(() => requests.onChangeActivePendingUserInputCustomAnswer("question-0", "second try")); + expect(draftPrompt()).toBe("first try"); + expect(requests.activePendingDraftAnswers["question-0"]).toMatchObject({ + customAnswer: "second try", + }); + expect(toast).toHaveBeenCalledTimes(1); +}); + function QuestionPositionProbe(props: ProbeProps) { const state = useProbeRequests(props); return ( diff --git a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx index 37a002e2c2708..a19e7f205cef9 100644 --- a/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx +++ b/apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx @@ -1,4 +1,5 @@ import { type RuntimeRequestId, type ScopedThreadRef } from "@t3tools/contracts"; +import { markdownProseDirection, textDirection } from "~/textDirection"; import { memo, use, useEffect, useEffectEvent, useRef, useState } from "react"; import { BackgroundThreadContext } from "./backgroundThread"; import { useStableCallback } from "~/hooks/useStableCallback"; @@ -179,8 +180,20 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( return null; } + const promptDirection = markdownProseDirection( + prompt.questions + .flatMap((question) => [ + question.header, + question.question, + ...question.options.flatMap((option) => [option.label, option.description ?? ""]), + ]) + .join(" "), + ); + const questionTextAlign = promptDirection === "rtl" ? "text-right" : "text-left"; + return ( { setCollapsedQuestionId(open ? null : activeQuestion.id); @@ -197,13 +210,17 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( {activeQuestion.header} {isCollapsed ? ( <> - + {activeQuestion.question} @@ -245,7 +262,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( text={activeQuestion.question} cwd={cwd} threadRef={threadRef} - className="pt-2 text-foreground/85" + className={cn("pt-2 text-foreground/85", questionTextAlign)} /> {/* Rows span the header row's width so the radios align with the question text and the shortcut column sits under the dismiss button. */}
@@ -257,7 +274,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( const isSelected = isOptimisticallySelected || draftSelectedOptions?.[index] === true; const className = cn( - "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 text-left sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25", + questionTextAlign, + "group flex w-full items-start gap-2.5 rounded-md bg-transparent py-1.5 ps-2 sm:ps-1.5 outline-none transition-colors duration-150 focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-primary/25", isSelected ? "text-foreground" : "text-foreground/70 hover:bg-muted/30", (disabled || isResponding) && "opacity-50 cursor-not-allowed", !disabled && !isResponding && "cursor-pointer", @@ -273,9 +291,16 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard( )}
- {option.label} + + {option.label} + {option.description && option.description !== option.label ? ( - {option.description} + + {option.description} + ) : null}
{index < 9 ? ( diff --git a/apps/web/src/components/chat/EffortGlyph.test.ts b/apps/web/src/components/chat/EffortGlyph.test.ts index 712e4b796ba61..0b73e89e4f833 100644 --- a/apps/web/src/components/chat/EffortGlyph.test.ts +++ b/apps/web/src/components/chat/EffortGlyph.test.ts @@ -45,9 +45,11 @@ describe("resolveEffortGlyph", () => { }); }); - it("falls back to the word when the value is unknown or the scale has one level", () => { + it("falls back to the word when the value is unknown or the scale is too short or long", () => { expect(resolveEffortGlyph(claude, "unknown")).toBeNull(); expect(resolveEffortGlyph(descriptor(["high"]), "high")).toBeNull(); + const levels = Array.from({ length: 8 }, (_, index) => `level${index}`); + expect(resolveEffortGlyph(descriptor(levels), "level0")).toBeNull(); }); }); diff --git a/apps/web/src/components/chat/EffortGlyph.tsx b/apps/web/src/components/chat/EffortGlyph.tsx index 39a46d2564901..7614e41c496a6 100644 --- a/apps/web/src/components/chat/EffortGlyph.tsx +++ b/apps/web/src/components/chat/EffortGlyph.tsx @@ -14,6 +14,8 @@ type SelectDescriptor = Extract; // Max is named too, so the full scale stops short of it. const NAMED_LEVELS = new Set(["ultracode", "max"]); 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 @@ -22,7 +24,7 @@ const OFF_LEVELS = new Set(["off", "none"]); export function resolveEffortGlyph(descriptor: SelectDescriptor, current: string | null) { const special = new Set([...(descriptor.promptInjectedValues ?? []), ...NAMED_LEVELS]); const levels = descriptor.options.filter((option) => !special.has(option.id)); - if (levels.length < 2 || current === null) return null; + if (levels.length < 2 || levels.length > MAX_BARS || current === null) return null; const startsAtOff = OFF_LEVELS.has(levels[0]!.id); const count = startsAtOff ? levels.length - 1 : levels.length; if (special.has(current)) { diff --git a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx new file mode 100644 index 0000000000000..220cebad12f3c --- /dev/null +++ b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx @@ -0,0 +1,47 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import { ExpandedImageDialog } from "./ExpandedImageDialog"; + +const D2_SVG = + ''; + +describe("ExpandedImageDialog", () => { + it.each(["/work/pipeline.svg", "/work/diagram#v2.svg", "/work/diagram?v2.svg"])( + "fits a markdown SVG without intrinsic size to the viewer: %s", + async (path) => { + const src = URL.createObjectURL(new Blob([D2_SVG], { type: "image/svg+xml" })); + using _src = { [Symbol.dispose]: () => URL.revokeObjectURL(src) }; + await using screen = await render( + , + // The dialog renders no links and reads no route. + { router: false }, + ); + + const viewer = screen.getByRole("region", { name: "Pipeline, zoomable image" }); + const availableWidth = window.innerWidth * 0.92 - (window.innerWidth >= 640 ? 96 : 0); + await vi.waitFor(() => + expect(viewer.element().getBoundingClientRect().width).toBeCloseTo(availableWidth, 0), + ); + }, + ); + // Coder: the SnapShot accessibility popup case is cut; SnapShot sources are not carried. +}); diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 4758f70f0f106..08f47ba1ae355 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -17,6 +17,8 @@ import { Atom } from "effect/reactivity"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { expandedImageKey } from "./ExpandedImagePreview"; import { registerThreadOverlay } from "./threadOverlayRetention"; +import { mediaReferenceFileName } from "@t3tools/client-runtime/media-reference"; +import { mediaMimeType, mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview"; interface ExpandedImageDialogProps { preview: ExpandedImagePreview; @@ -34,6 +36,16 @@ function ExpandedMediaFailure({ children }: { children: ReactNode }) { ); } +function itemMimeType(item: ExpandedImageItem): string | undefined { + if (item.mimeType) return item.mimeType; + const reference = item.actionsSource?.reference; + const fileName = reference && mediaReferenceFileName(reference); + if (fileName) { + return mediaMimeTypeFromExtension(fileName.slice(fileName.lastIndexOf("."))) ?? undefined; + } + return mediaMimeType(item.src ?? "") ?? undefined; +} + function ExpandedVideo({ item }: { readonly item: ExpandedImageItem }) { const asset = item.actionsSource?.asset; const assetUrl = useAssetUrlState(asset?.environmentId ?? null, asset?.resource ?? null); @@ -199,7 +211,7 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ key={`${index}:${item.src}`} src={item.src} name={item.name} - mimeType={item.mimeType} + mimeType={itemMimeType(item)} onError={() => setFailedImageSrc(item.src)} /> )} diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index 6b1822aac14a7..301843c4ebe36 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -65,7 +65,7 @@ export function MarkdownCodeBlockFrame({ return ( diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 7fd73739d9195..2fcaa596a5b6c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -859,7 +859,7 @@ describe("MessagesTimeline attachments", () => { onOpen={onOpen} /> ); - await using screen = await renderElement(preview()); + await using screen = await renderElement(
{preview()}
); const audio = screen.container.querySelector("audio")!; const duration = vi.spyOn(audio, "duration", "get").mockReturnValue(Infinity); const play = vi.spyOn(audio, "play").mockResolvedValue(); @@ -884,6 +884,10 @@ describe("MessagesTimeline attachments", () => { audio.dispatchEvent(new Event("durationchange")); }); expect(screen.text()).toContain("0:03 / 0:10"); + expect( + getComputedStyle(screen.container.querySelector("audio")!.previousElementSibling!) + .direction, + ).toBe("ltr"); expect(progress.style.width).toBe("30%"); await act(() => { duration.mockReturnValue(NaN); diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 9928530b97f2a..e70c32b064a3e 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -67,7 +67,14 @@ export const ModelListRow = memo(function ModelListRow(props: { badgeClassName="right-[-0.125rem] bottom-[-0.125rem] h-3 min-w-3 px-0.5 text-5xs" />
-
+
{ + const name = event.currentTarget; + name.title = name.scrollWidth > name.clientWidth ? getDisplayModelName(model) : ""; + }} + > {getDisplayModelName(model)} {/* The logo is decorative, so name the provider for screen readers. */} , {props.providerDisplayName} diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 742a7cf6b09fd..f040df764cda9 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -366,6 +366,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { docked?: boolean; /** Right at the end of the search text moves into the popup's effort column. */ onFocusEffort?: () => void; + /** Closes the list column, inside the popup's fixed height. */ + listFooter?: ReactNode; }) { const { searchInputRef, @@ -838,16 +840,17 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { ref={pickerContentRef} className={cn( "relative flex w-screen max-w-90 flex-row overflow-hidden", - props.docked - ? "max-sm:h-56 max-sm:min-h-0! max-sm:w-full max-sm:max-w-none" - : "max-h-86.5", + props.docked ? "max-sm:h-56 max-sm:w-full max-sm:max-w-none" : "max-h-86.5", )} + // Docked, the popup sets the height; a minimum here would overflow short windows. style={ - isSearching - ? { height: searchHeight } - : { - minHeight: `min(calc(var(--spacing) * ${tallestTabUnits + LIST_CHROME_UNITS} + 1px), calc(var(--spacing) * 86.5))`, - } + props.docked + ? undefined + : isSearching + ? { height: searchHeight } + : { + minHeight: `min(calc(var(--spacing) * ${tallestTabUnits + LIST_CHROME_UNITS} + 1px), calc(var(--spacing) * 86.5))`, + } } data-model-picker-content="true" > @@ -1072,6 +1075,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { onRequestClose={onRequestClose} onOpenProviderSetup={onOpenProviderSetup} /> + {props.listFooter}
diff --git a/apps/web/src/components/chat/PanelLayoutControls.tsx b/apps/web/src/components/chat/PanelLayoutControls.tsx index 6750298402942..56d93123d7d67 100644 --- a/apps/web/src/components/chat/PanelLayoutControls.tsx +++ b/apps/web/src/components/chat/PanelLayoutControls.tsx @@ -190,9 +190,11 @@ export function WorkspaceTitlebarControls(props: { {props.showMaximizeControl ? ( { return ( target instanceof Element && - target.closest("[data-model-picker-content], [data-model-picker-effort]") + target.closest( + "[data-model-picker-content], [data-model-picker-effort], [data-model-picker-option-menu]", + ) ); }; const preventBackgroundWheel = (event: WheelEvent) => { @@ -89,6 +91,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { disabled?: boolean; terminalOpen?: boolean; open?: boolean; + popupAlign?: "start" | "end"; triggerClassName?: string; triggerLabel?: string; triggerAriaLabel?: string; @@ -152,16 +155,22 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { /** * Focuses the selected reasoning level, else the first level. With `rows: "any"` it falls back - * to the column's other options. False when nothing took focus. + * to the column's first enabled option. False when nothing took focus. */ const focusEffort = (rows: "levels" | "any") => { const column = popupRef.current?.querySelector("[data-model-picker-effort]"); - const first = (selector: string) => - column?.querySelector(`${selector}[aria-checked="true"]:not(:disabled)`) ?? - column?.querySelector(`${selector}:not(:disabled)`); + const level = + column?.querySelector( + '[data-effort-level][aria-checked="true"]:not(:disabled)', + ) ?? column?.querySelector("[data-effort-level]:not(:disabled)"); + // No aria-checked here: an On switch is checked but is not where focus belongs. const row = - first("[data-effort-level]") ?? (rows === "any" ? first("[data-effort-row]") : null); + level ?? + (rows === "any" + ? column?.querySelector("[data-effort-row]:not(:disabled)") + : null); row?.focus({ preventScroll: true }); + row?.scrollIntoView({ block: "nearest" }); return row != null; }; const openTarget = (target: "effort" | "permissions") => { @@ -228,7 +237,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { const triggerText = props.triggerLabel ?? multipleLabel ?? triggerTitle; const triggerTextProps = { - className: "min-w-0 flex-1 overflow-hidden truncate", + className: cn( + "min-w-0 flex-1 overflow-hidden truncate", + // Long names such as "Fusion (Claude Opus 5.5 Medium + SWE-2 High)" would push the composer. + props.isComposerOwned && "max-w-56", + ), "data-chat-provider-model-picker-label": "true", } as const; @@ -260,6 +273,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { : (props.getModelDisabledReason?.(instanceId, model) ?? null) } onInstanceModelChange={handleInstanceModelChange} + // Coder: no ChatGPT sharing footer; subscription plans are out of scope. {...(docked ? { docked, onFocusEffort: () => void focusEffort("any") } : {})} /> ); @@ -391,19 +405,22 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { }; }} initialFocus={searchInputRef} - align="start" + align={props.popupAlign ?? "start"} + collisionAvoidance={docked ? { align: "shift", fallbackAxisSide: "none" } : undefined} className="before:hidden" padding="none" touchBackdrop > {props.effortColumn ? ( -
-
+
+ {/* One fixed height, so a model with more options never resizes the popup. Short + windows shrink it and keep the footer. */} +
{picker}
{ if (event.key !== "ArrowLeft" || event.altKey || event.ctrlKey || event.metaKey) return; diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index d243c4f1c0524..36e41ae89b10f 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -65,7 +65,7 @@ export function RightPanelSurfaceContent(props: { readonly files: RightPanelFileProps; readonly sideChatParentPanel: SideChatParentPanel; }) { - const { surface, threadRef, visible } = props; + const { surface, threadRef, visible, onCloseSurface } = props; if (surface === null) return null; switch (surface.kind) { // Coder: there is no in-app browser or device preview. @@ -153,7 +153,7 @@ export function RightPanelSurfaceContent(props: { parentRef={threadRef} threadId={surface.threadId} parentPanel={props.sideChatParentPanel} - onClose={() => props.onCloseSurface(surface)} + onClose={() => onCloseSurface(surface)} /> ); case "files": diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index 4c0af2d3472c0..5342bd09b3ca9 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -191,7 +191,14 @@ export function backgroundWorkNowItem(input: { icon: rows.every(isCommand) ? : , title: only ? ( <> - {verb} {only.task.label} + {verb}{" "} + + {only.task.label} + ) : ( presentation.title diff --git a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx index 32635f85dc173..854b5166c11b6 100644 --- a/apps/web/src/components/chat/ThreadDetailsPrRow.tsx +++ b/apps/web/src/components/chat/ThreadDetailsPrRow.tsx @@ -439,7 +439,7 @@ export function ThreadDetailsPrRow({ {detail !== null && (showChecks || trailingAction !== null || watching) ? (
{openRow(detail.title, "row", true)} -
+
!{number} {showChecks && checksRollup !== null ? ( | undefined; + providerEntries: ReadonlyArray; driver: ProviderDriverKind | undefined; onOpen: (threadId: string) => void; }) { @@ -78,7 +81,12 @@ function WorkflowMemberRow({ /> } > - + {member.title} {member.status} {member.startedAt ? ( @@ -113,6 +121,7 @@ export function ThreadLineageWorkflowRow({ providerInstanceId, provider, providers, + providerEntries, driver, onOpenThread, onStop, @@ -124,6 +133,7 @@ export function ThreadLineageWorkflowRow({ readonly providerInstanceId: ProviderInstanceId; readonly provider: ServerProvider | undefined; readonly providers: ReadonlyArray | undefined; + readonly providerEntries: ReadonlyArray; readonly driver: ProviderDriverKind | undefined; readonly onOpenThread: (threadId: string) => void; readonly onStop?: (() => void) | undefined; @@ -221,6 +231,7 @@ export function ThreadLineageWorkflowRow({ providerInstanceId={providerInstanceId} provider={provider} providers={providers} + providerEntries={providerEntries} driver={driver} onOpen={onOpenThread} /> @@ -237,6 +248,7 @@ export function ThreadLineageWorkflowRow({ providerInstanceId={providerInstanceId} provider={provider} providers={providers} + providerEntries={providerEntries} driver={driver} onOpen={onOpenThread} /> diff --git a/apps/web/src/components/chat/ThreadRelationshipIcon.tsx b/apps/web/src/components/chat/ThreadRelationshipIcon.tsx index 6b6b322159335..c007ac03c2c44 100644 --- a/apps/web/src/components/chat/ThreadRelationshipIcon.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipIcon.tsx @@ -1,6 +1,7 @@ import type { ProviderDriverKind, ServerProvider } from "@t3tools/contracts"; import { BotIcon, type LucideIcon } from "lucide-react"; import { cn } from "../../lib/utils"; +import { shouldShowInstanceBadge, type ProviderInstanceEntry } from "../../providerInstances"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; export function threadRelationshipStatusLabel(status: string | null): string { @@ -45,22 +46,32 @@ export function threadRelationshipStatusLabel(status: string | null): string { export function ThreadRelationshipIcon({ driver, provider, + providerEntries = [], status, fallbackIcon: FallbackIcon = BotIcon, }: { driver?: ProviderDriverKind | undefined; provider?: ServerProvider | undefined; + providerEntries?: ReadonlyArray; status: string | null; fallbackIcon?: LucideIcon; }) { const iconClassName = "size-4 shrink-0 text-muted-foreground"; + const entry = driver + ? providerEntries.find((candidate) => candidate.instanceId === provider?.instanceId) + : undefined; + const showInstanceBadge = entry !== undefined && shouldShowInstanceBadge(entry, providerEntries); return ( {driver ? ( @@ -69,7 +80,8 @@ export function ThreadRelationshipIcon({ )} (null); // Derive graphs after hooks to preserve their compiler cache. const providers = providersByEnvironment.get(props.environmentId); + const derivedProviderEntries = deriveProviderInstanceEntries(providers ?? []); + const providerEntries = settings + ? applyProviderInstanceSettings( + derivedProviderEntries, + settings, + currentThread?.projectId ?? null, + ) + : derivedProviderEntries; const projects = allProjects.filter((project) => project.environmentId === props.environmentId); const parentNativeStatus = parentProjection ? deriveProviderSubagentStatus(parentProjection)?.status @@ -673,6 +687,7 @@ export function ThreadRelationshipsPanel(props: { @@ -729,6 +744,7 @@ export function ThreadRelationshipsPanel(props: { providerInstanceId={agent.providerInstanceId} provider={provider} providers={providers} + providerEntries={providerEntries} driver={providerDriver} onOpenThread={(memberThreadId) => openThread(memberThreadId as ThreadId)} onStop={canStopWorkflow ? () => void stopWorkflow(agent.id) : undefined} diff --git a/apps/web/src/components/chat/TimelineMinimap.tsx b/apps/web/src/components/chat/TimelineMinimap.tsx index 4e87edfe59495..742657ba68c0d 100644 --- a/apps/web/src/components/chat/TimelineMinimap.tsx +++ b/apps/web/src/components/chat/TimelineMinimap.tsx @@ -217,7 +217,7 @@ export function TimelineMinimap({
{fileTreeOpen ? ( - + ) : null}
{unstructured} diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx new file mode 100644 index 0000000000000..e7422e74ac07e --- /dev/null +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.browser.test.tsx @@ -0,0 +1,70 @@ +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; +import { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +const state = vi.hoisted(() => ({ detail: "" })); + +vi.mock(import("~/state/use-atom-command"), async () => { + const { PullRequestOperationError } = await import("@t3tools/contracts"); + const { Cause } = await import("effect"); + const { AsyncResult } = await import("effect/reactivity"); + return { + useAtomCommand: (() => async () => + AsyncResult.failure( + Cause.fail(new PullRequestOperationError({ operation: "runAction", detail: state.detail })), + )) as never, + }; +}); + +import "~/index.css"; +import { render } from "../../../test/render"; +import { ToastProvider } from "../ui/toast"; +import { PullRequestStackMenu } from "./PullRequestStackMenu"; + +function setup(detail: string) { + state.detail = detail; +} + +const HEAD_MOVED = "The stack head moved. Refresh the stack before trying again."; + +it.each([ + { label: "Merge stack", detail: HEAD_MOVED, description: HEAD_MOVED }, + { label: "Rebase stack", detail: HEAD_MOVED, description: HEAD_MOVED }, + // Coder: the GitHub CLI refusal case is cut; GitHub's client is not registered. +])("$label refused with $detail shows $description", async (row) => { + setup(row.detail); + await using screen = await render( + + {}} + /> + , + ); + if (row.label === "Rebase stack") { + await screen.getByRole("button", { name: "Stack 1, layer 1 of 1" }).click(); + await page.getByRole("menuitem", { name: row.label }).click(); + } else { + await screen.getByRole("button", { name: row.label, exact: true }).click(); + } + await page.getByRole("dialog").getByRole("button", { name: row.label, exact: true }).click(); + await expect.element(page.getByText(row.description, { exact: true })).toBeInTheDocument(); +}); diff --git a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx index 9a8a2c0f71bef..af2f438a98c0d 100644 --- a/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx +++ b/apps/web/src/components/pullRequest/PullRequestStackMenu.tsx @@ -27,6 +27,7 @@ import { PullRequestStackLayers } from "./PullRequestStackLayers"; import { PullRequestStackHeader } from "./PullRequestStackHeader"; import { PullRequestStackLayerContent } from "./PullRequestStackLayerContent"; import { PullRequestGlyph } from "./pullRequestIcons"; +import { readableFailure } from "./pullRequestDetail.logic"; export function PullRequestStackMenu({ hostLabel, @@ -114,7 +115,12 @@ export function PullRequestStackMenu({ toastManager.update(toastId, { type: "error", title: action === "merge" ? "Could not merge the stack" : "Could not rebase the stack", - description: String(squashAtomCommandFailure(result)), + description: readableFailure( + squashAtomCommandFailure(result), + action === "merge" + ? "The host refused the merge. Check that you have write access, that the checks it requires have passed, and that the branch is not conflicting." + : "The host refused the rebase. A rebase stops at the first commit that does not apply cleanly.", + ), }); } else { toastManager.update(toastId, { diff --git a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts index a6e20a6c8c835..899aff44f1934 100644 --- a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.test.ts @@ -118,4 +118,24 @@ describe("orderDiffFiles", () => { "src/orphan.spec.ts", ]); }); + + it("pairs a test with the source whose name carries its own dotted suffix", () => { + expect( + order([ + file("src/c.browser.test.tsx"), + file("src/b.test.ts"), + file("src/a.logic.test.ts"), + file("src/c.tsx"), + file("src/b.ts"), + file("src/a.logic.ts"), + ]), + ).toEqual([ + "src/a.logic.ts", + "src/b.ts", + "src/c.tsx", + "src/a.logic.test.ts", + "src/b.test.ts", + "src/c.browser.test.tsx", + ]); + }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts index 738b372585a65..737206d96e508 100644 --- a/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestFileOrder.logic.ts @@ -117,8 +117,17 @@ function orderByImports( return ordered; } -function testedBaseName(path: string): string { - return (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, "").replace(/\.[^.]+$/, ""); +// `a.logic.test.ts` covers `a.logic.ts` while `a.browser.test.ts` covers `a.ts`, so the longest +// dotted prefix that names a source file wins. +function testedSourcePosition(path: string, sourcePositions: ReadonlyMap): number { + let name = (path.split("/").at(-1) ?? "").replace(/\.(?:test|spec)\..*$/, ""); + while (true) { + const position = sourcePositions.get(name); + if (position !== undefined) return position; + const dot = name.lastIndexOf("."); + if (dot <= 0) return Number.MAX_SAFE_INTEGER; + name = name.slice(0, dot); + } } export function orderDiffFiles( @@ -159,9 +168,10 @@ export function orderDiffFiles( const orderedTests = [...byPath.keys()] .filter((path) => tiers.get(path) === "test") .sort((left, right) => { - const leftPosition = sourcePositions.get(testedBaseName(left)) ?? Number.MAX_SAFE_INTEGER; - const rightPosition = sourcePositions.get(testedBaseName(right)) ?? Number.MAX_SAFE_INTEGER; - return leftPosition - rightPosition || left.localeCompare(right); + return ( + testedSourcePosition(left, sourcePositions) - + testedSourcePosition(right, sourcePositions) || left.localeCompare(right) + ); }); const orderedGenerated = [...byPath.keys()] diff --git a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx index 1c5812a2bda0d..00783b085d609 100644 --- a/apps/web/src/components/settings/AppearanceSettingsPanel.tsx +++ b/apps/web/src/components/settings/AppearanceSettingsPanel.tsx @@ -19,6 +19,7 @@ import { useEnvironmentStageLabel, } from "../SidebarStageBackdrop"; import { useCustomThemes } from "../../hooks/useCustomThemes"; +import { useEnvironmentIdentificationMode } from "../../hooks/useSettings"; import { useTheme } from "../../hooks/useTheme"; import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; @@ -106,6 +107,20 @@ export function AppearanceSettingsPanel() { environmentIdentificationOptionList.find( ([value]) => value === settings.environmentIdentificationMode, )?.[1] ?? ENVIRONMENT_IDENTIFICATION_LABELS[settings.environmentIdentificationMode]; + const effectiveEnvironmentIdentificationMode = useEnvironmentIdentificationMode(); + const themeHidesEnvironmentArtwork = + effectiveEnvironmentIdentificationMode === "pill" && + resolveSidebarStageBackdropVariant( + environmentStageLabel, + settings.environmentIdentificationMode, + ) !== null; + const environmentIdentificationDescription = themeHidesEnvironmentArtwork + ? environmentStageVariant + ? "Only built-in themes show artwork, so this theme shows the version pill." + : "Only built-in themes show artwork." + : environmentStageVariant + ? "Choose how Dev and Nightly environments are identified." + : "Show Dev or Nightly artwork in the sidebar header."; const glassOpacityRatio = (settings.glassOpacity - MIN_GLASS_OPACITY) / (MAX_GLASS_OPACITY - MIN_GLASS_OPACITY); const glassOpacitySliderStyle = { @@ -395,11 +410,7 @@ export function AppearanceSettingsPanel() { /> ({ + ...(await original()), + useEnvironmentScope: () => true, + useEnvironmentsWithScope: ((environments: ReadonlyArray<{ environmentId: string }>) => + new Set(environments.map(({ environmentId }) => environmentId))) as never, + readEnvironmentScope: () => true, +})); +vi.mock(import("../../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: (() => vi.fn()) as never, +})); vi.mock(import("./SettingsScopeContext"), async (original) => ({ ...(await original()), useSettingsScope: (() => { @@ -22,16 +33,78 @@ vi.mock(import("./SettingsScopeContext"), async (original) => ({ }; }) as never, })); -vi.mock(import("../../state/session"), async (original) => ({ - ...(await original()), - useEnvironmentScope: () => true, - useEnvironmentsWithScope: ((environments: ReadonlyArray<{ environmentId: string }>) => - new Set(environments.map((environment) => environment.environmentId))) as never, - readEnvironmentScope: () => true, -})); +import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import { KeybindingsSettingsPanel } from "./KeybindingsSettings"; +// The modal dialog's inert layer swallows pointer events in this harness, so drive the DOM. +async function activate(locator: Locator, action: "click" | "focus") { + await expect.element(locator).toBeVisible(); + (locator.element() as HTMLElement)[action](); +} + +const existingField = page.getByRole("textbox", { name: "Keybinding for Sidebar: Toggle" }); +const existingPill = page.getByRole("button", { name: /^Edit shortcut for Sidebar: Toggle:/ }); +const newField = page.getByRole("textbox", { name: "Keybinding for new keybinding" }); + +describe("Esc in a shortcut recorder", () => { + it.each<{ + name: string; + field: Locator; + open: () => Promise; + expectReset: () => Promise; + }>([ + { + name: "existing binding", + field: existingField, + open: () => activate(existingPill, "click"), + expectReset: async () => { + await expect.element(existingField).not.toBeInTheDocument(); + await expect.element(existingPill).toHaveFocus(); + await expect.element(page.getByRole("button", { name: "Save" })).not.toBeInTheDocument(); + }, + }, + { + name: "new binding", + field: newField, + open: async () => { + await activate(page.getByRole("button", { name: "Add keybinding" }), "click"); + await activate(newField, "focus"); + }, + expectReset: async () => { + await expect.element(newField).toHaveValue(""); + await expect.element(newField).toHaveAttribute("placeholder", "Unassigned"); + }, + }, + ])("leaves the $name field without closing Settings", async ({ field, open, expectReset }) => { + const onOpenChange = vi.fn(); + await using _screen = await render( + + + Settings + + + , + ); + + await open(); + await userEvent.keyboard("{Control>}k{/Control}"); + await expect.element(field).not.toHaveValue(""); + await userEvent.tab(); + await activate(field, "focus"); + await expect.element(field).toHaveAttribute("placeholder", "Press shortcut"); + + await userEvent.keyboard("{Escape}"); + + expect(onOpenChange).not.toHaveBeenCalled(); + expect(document.activeElement?.matches("[data-keybinding-capture]")).toBe(false); + await expectReset(); + + await userEvent.keyboard("{Escape}"); + expect(onOpenChange).toHaveBeenCalledWith(false, expect.anything()); + }); +}); + it("re-enables Save when a When editor closes on an expression it could not parse", async () => { await using screen = await render( diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 5b2ec1362e7c8..61e4854585d71 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -18,6 +18,7 @@ import { useRef, useState, } from "react"; +import { flushSync } from "react-dom"; import { AuthSettingsWriteScope, type KeybindingCommand, @@ -712,6 +713,7 @@ function useKeybindingRowEditor({ onSave: (input: ServerUpsertKeybindingInput) => void; }) { const [draft, setDraft] = useReducer(keybindingRowDraftReducer, row, createKeybindingRowDraft); + const pillRef = useRef(null); const { keyDraft, whenDraft, isRecording, isWhenDraftValid } = draft; const whenDraftExpression = whenAstToExpression(whenDraft); const isDirty = keyDraft !== row.key || whenDraftExpression !== row.when; @@ -734,7 +736,13 @@ function useKeybindingRowEditor({ if (event.key === "Tab" && !isRecording) return; event.preventDefault(); if (event.key === "Escape") { - setDraft({ keyDraft: row.key, isRecording: false }); + // An unhandled Escape closes the settings page. + event.stopPropagation(); + const field = event.currentTarget; + flushSync(() => setDraft({ keyDraft: row.key, isRecording: false })); + // The field may unmount for the pill; focus would otherwise drop to the page. + if (pillRef.current) pillRef.current.focus(); + else field.blur(); return; } const next = keybindingFromKeyboardEvent(event.nativeEvent, navigator.platform, { @@ -755,6 +763,7 @@ function useKeybindingRowEditor({ setDraft, save, captureKeybinding, + pillRef, }; } @@ -785,8 +794,16 @@ function KeybindingKeyControl({ isSaving: boolean; pillClassName?: string | undefined; }) { - const { keyDraft, isRecording, isDirty, isWhenDraftValid, setDraft, save, captureKeybinding } = - editor; + const { + keyDraft, + isRecording, + isDirty, + isWhenDraftValid, + setDraft, + save, + captureKeybinding, + pillRef, + } = editor; const showPill = !isRecording && keyDraft === row.key && row.key.length > 0 && !isDirty; return ( @@ -802,6 +819,7 @@ function KeybindingKeyControl({ ) : null} {showPill ? (
@@ -1192,6 +1231,20 @@ function ScheduledTaskEditorForm({ This task runs on webhook requests, which T3 Coder does not receive. Choose a time or interval to schedule it.

+ ) : draft.scheduleMode === "once" ? ( +
+ + + setDraft((current) => ({ ...current, runAt: event.target.value })) + } + /> +
) : draft.scheduleMode === "fixed" ? (
diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 441b9b27f5295..6b1ddb8a0e8b6 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -216,7 +216,7 @@ export function useSettingsRestore(onRestored?: () => void) { : []), ...(settings.diffLayout !== DEFAULT_UNIFIED_SETTINGS.diffLayout ? ["Diff layout"] : []), ...(settings.proactivePanelsEnabled !== DEFAULT_UNIFIED_SETTINGS.proactivePanelsEnabled - ? ["Proactive panels"] + ? ["Open merge requests and changes panels proactively"] : []), ...(settings.showSkillsInSlashMenu !== DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu ? ["Show skills in slash menu"] @@ -1079,7 +1079,7 @@ export function DiffsSettingsPanel() { onCheckedChange={(checked) => updateSettings({ proactivePanelsEnabled: Boolean(checked) }) } - aria-label="Proactive panels" + aria-label="Open merge requests and changes panels proactively" /> } /> @@ -1288,7 +1288,7 @@ export function ThreadsSettingsPanel() { { if (targetId) - void navigate({ to: pathname, search: () => choice.search, hash: targetId }); + void navigate({ + to: pathname, + search: () => ({ + project: undefined, + machine: undefined, + checkout: undefined, + ...choice.search, + }), + hash: targetId, + }); else selectScope(choice.search); }} > diff --git a/apps/web/src/components/settings/SourceControlWritingSettings.tsx b/apps/web/src/components/settings/SourceControlWritingSettings.tsx index 70556ecc08000..6ce73712d817d 100644 --- a/apps/web/src/components/settings/SourceControlWritingSettings.tsx +++ b/apps/web/src/components/settings/SourceControlWritingSettings.tsx @@ -295,7 +295,7 @@ export function SourceControlWritingSettingsSection() { settingKeys={["reviewGuidesEnabled"]} mixed={mixedReviewGuidesEnabled} {...searchableSetting("review-guides")} - description="Adds a Guide tab to merge requests: an agent writes a tour of the change, stop by stop, with the calls a maintainer should make." + description="Add a Guide tab to merge requests. An agent explains the changes and points out decisions that need review." control={ diff --git a/apps/web/src/components/settings/ThemeColorPicker.tsx b/apps/web/src/components/settings/ThemeColorPicker.tsx index e8210026370e2..dead434dc08d4 100644 --- a/apps/web/src/components/settings/ThemeColorPicker.tsx +++ b/apps/web/src/components/settings/ThemeColorPicker.tsx @@ -1,4 +1,4 @@ -import { memo, useEffect, useState } from "react"; +import { memo, useEffect, useRef, useState } from "react"; import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette"; import { cn } from "../../lib/utils"; import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color"; @@ -240,21 +240,34 @@ function ThemeColorPicker({ label, value, onChange, + onEditStart, + onEditCancel, onInteract, }: { label: string; value: string; onChange: (value: string) => void; + onEditStart?: () => void; + onEditCancel?: () => void; onInteract?: () => void; }) { const [committer] = useState(createFrameCommitter); + // Escape reverts the edit, so commits after it (the pending frame flushed on close, or a drag + // still firing through the exit animation) are dropped instead of landing on the restored colors. + const cancelledRef = useRef(false); // Unmounting with the popover open (the editor closes mid-drag) never fires onOpenChange. // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- flushes the frame committer on unmount, since an open popover never fires onOpenChange useEffect(() => committer.flush, [committer]); return ( { - if (!open) committer.flush(); + onOpenChange={(open, eventDetails) => { + cancelledRef.current = !open && eventDetails.reason === "escape-key"; + if (open) { + onEditStart?.(); + return; + } + committer.flush(); + if (cancelledRef.current) onEditCancel?.(); }} > @@ -290,7 +303,9 @@ function ThemeColorPicker({ { + if (!cancelledRef.current) onChange(nextValue); + }} value={value} /> @@ -302,6 +317,8 @@ export const ThemeColorField = memo(function ThemeColorField({ role, value, onChange, + onEditStart, + onEditCancel, onSelect, onToggleSelected, selected = false, @@ -310,6 +327,8 @@ export const ThemeColorField = memo(function ThemeColorField({ role: ThemeColorRole; value: string; onChange: (role: ThemeColorRole, value: string) => void; + onEditStart?: (role: ThemeColorRole) => void; + onEditCancel?: (role: ThemeColorRole) => void; onSelect?: (role: ThemeColorRole) => void; onToggleSelected?: (role: ThemeColorRole) => void; selected?: boolean; @@ -350,6 +369,8 @@ export const ThemeColorField = memo(function ThemeColorField({ onChange(role, nextValue)} + onEditCancel={() => onEditCancel?.(role)} + onEditStart={() => onEditStart?.(role)} onInteract={() => onSelect?.(role)} value={swatchValue} /> diff --git a/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx b/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx index a2802f544f22e..881c27cc22a37 100644 --- a/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeEditorPanel.browser.test.tsx @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; -import { render } from "../../../test/render"; +import { act, render } from "../../../test/render"; import { ThemeEditorPanel } from "./ThemeEditorPanel"; function dragHeader(panel: HTMLElement, toX: number, toY: number) { @@ -32,6 +32,19 @@ function dragResizeHandle(panel: HTMLElement, byX: number) { handle.dispatchEvent(new PointerEvent("pointerup", init)); } +function pointerAt(target: HTMLElement, type: string, xFraction: number) { + const rect = target.getBoundingClientRect(); + target.dispatchEvent( + new PointerEvent(type, { + bubbles: true, + button: 0, + pointerId: 3, + clientX: rect.left + rect.width * xFraction, + clientY: rect.top + rect.height / 2, + }), + ); +} + async function renderPanel() { await page.viewport(1280, 900); const stack = new AsyncDisposableStack(); @@ -110,4 +123,29 @@ describe("ThemeEditorPanel", () => { await page.viewport(1280, 900); await expect.poll(() => (panel.element() as HTMLElement).style.left).toBe("700px"); }); + + it("restores the colors from before the picker opened when Escape closes it", async () => { + await using _view = await renderPanel(); + const hex = page.getByRole("textbox", { name: "Accent hex value" }); + const original = (hex.element() as HTMLInputElement).value; + await userEvent.click(page.getByRole("button", { name: "Choose Accent color" })); + const hue = page.getByRole("slider", { name: "Accent hue" }); + await expect.element(hue).toBeInTheDocument(); + const hueSlider = hue.element() as HTMLElement; + + await act(async () => { + pointerAt(hueSlider, "pointerdown", 0.5); + pointerAt(hueSlider, "pointerup", 0.5); + }); + await expect.element(hex).not.toHaveValue(original); + + await act(async () => { + pointerAt(hueSlider, "pointerdown", 0.25); + hueSlider.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, key: "Escape" })); + // The drag keeps going while the picker animates out. + pointerAt(hueSlider, "pointermove", 0.75); + pointerAt(hueSlider, "pointerup", 0.75); + }); + expect((hex.element() as HTMLInputElement).value).toBe(original); + }); }); diff --git a/apps/web/src/components/settings/ThemeEditorPanel.tsx b/apps/web/src/components/settings/ThemeEditorPanel.tsx index f6992e1f7ec02..7b10dab109966 100644 --- a/apps/web/src/components/settings/ThemeEditorPanel.tsx +++ b/apps/web/src/components/settings/ThemeEditorPanel.tsx @@ -354,6 +354,11 @@ export function ThemeEditorPanel({ const [position, setPosition] = useState<{ x: number; y: number; width: number } | null>(null); const [size, setSize] = useState<{ width: number; height: number } | null>(null); const panelRef = useRef(null); + const colorEditSnapshotRef = useRef<{ + colorsByAppearance: ThemeEditorColorsByAppearance; + simpleColorsDirtyByAppearance: Record; + shouldRegenerateGuidedColors: boolean; + } | null>(null); const dragOffsetRef = useRef<{ dx: number; dy: number; width: number } | null>(null); const resizeStartRef = useRef<{ pointerX: number; @@ -472,6 +477,25 @@ export function ThemeEditorPanel({ if (isAdvanced) setShouldRegenerateGuidedColors(true); }; + // A color edit also rewrites derived roles, so cancelling restores the whole snapshot rather than + // replaying the previous value through updateColor. + const startColorEdit = () => { + colorEditSnapshotRef.current = { + colorsByAppearance, + simpleColorsDirtyByAppearance, + shouldRegenerateGuidedColors, + }; + }; + + const cancelColorEdit = () => { + const snapshot = colorEditSnapshotRef.current; + colorEditSnapshotRef.current = null; + if (!snapshot) return; + setColorsByAppearance(snapshot.colorsByAppearance); + setSimpleColorsDirtyByAppearance(snapshot.simpleColorsDirtyByAppearance); + setShouldRegenerateGuidedColors(snapshot.shouldRegenerateGuidedColors); + }; + const selectThemeRole = (role: ThemeColorRole, reveal = false) => { const visibleRole = getThemeEditorColorFamily(role)?.role ?? role; setSelectedRole(visibleRole); @@ -947,6 +971,8 @@ export function ThemeEditorPanel({ key={family.id} label={family.label} onChange={updateColor} + onEditCancel={cancelColorEdit} + onEditStart={startColorEdit} onSelect={selectThemeRole} onToggleSelected={toggleThemeRole} role={family.role} @@ -986,6 +1012,8 @@ export function ThemeEditorPanel({ existing.id === theme.id)) { setError(null); setConflicts([theme]); diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index 7d13e1edc4e36..c4c66c1cfbae0 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -7,7 +7,7 @@ import { ScheduledTaskId, type ScheduledTask, } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import type { SidebarProjectGroupMember, @@ -170,6 +170,42 @@ describe("editing scheduled task branch settings", () => { }); }); +describe("one-time scheduled tasks", () => { + afterEach(() => vi.unstubAllEnvs()); + + it("round-trips the run time through the local date-time input", () => { + const runAt = "2026-11-03T17:00:42.000Z"; + const draft = taskToDraft({ ...legacyTask, schedule: { type: "once", runAt } }); + expect(draft.scheduleMode).toBe("once"); + expect(scheduleFromDraft(draft)).toEqual({ type: "once", runAt }); + const moved = scheduleFromDraft({ ...draft, runAt: "2026-11-04T09:30" }); + expect(moved).toEqual({ type: "once", runAt: new Date("2026-11-04T09:30").toISOString() }); + expect(scheduleFromDraft({ ...draft, runAt: "" })).toBeNull(); + }); + + it("rejects a time skipped by daylight saving", () => { + vi.stubEnv("TZ", "America/Los_Angeles"); + const draft = taskToDraft({ + ...legacyTask, + schedule: { type: "once", runAt: "2027-03-14T18:00:00.000Z" }, + }); + expect(scheduleFromDraft({ ...draft, runAt: "2027-03-14T02:30" })).toBeNull(); + }); + + it("keeps the saved offset when an edit stays in an hour that repeats", () => { + vi.stubEnv("TZ", "America/Los_Angeles"); + // 01:30 PST, the second 01:30 on 2026-11-01. + const draft = taskToDraft({ + ...legacyTask, + schedule: { type: "once", runAt: "2026-11-01T09:30:00.000Z" }, + }); + expect(scheduleFromDraft({ ...draft, runAt: "2026-11-01T01:35" })).toEqual({ + type: "once", + runAt: "2026-11-01T09:35:00.000Z", + }); + }); +}); + describe("webhook scheduled tasks", () => { const signature = { header: "x-signature", encoding: "base64", prefix: "" } as const; const webhookTask: ScheduledTask = { diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index 27ddc59f84c7d..9e0d0dad27cb9 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -52,7 +52,7 @@ export function validateScheduledTasksSearch(raw: Record) { }; } -export type ScheduleMode = "fixed" | "interval" | "webhook"; +export type ScheduleMode = "fixed" | "once" | "interval" | "webhook"; export type WorkspaceMode = "root" | "worktree" | "existing_worktree"; export interface DraftState { @@ -63,6 +63,10 @@ export interface DraftState { readonly scheduleMode: ScheduleMode; readonly intervalMinutes: string; readonly timeOfDay: string; + /** Local date and time as a `datetime-local` input value, such as 2026-11-02T15:00. */ + readonly runAt: string; + /** The stored ISO run time, sent back unchanged when the field was not edited. */ + readonly savedRunAt: string; readonly weekdays: ReadonlySet; readonly projectId: string; readonly threadId: string; @@ -96,7 +100,24 @@ export const WEBHOOK_SIGNATURE_DEFAULTS = { signaturePrefix: "sha256=", } as const; -export function webhookDraftErrors(draft: DraftState) { +/** Formats a date as a `datetime-local` input value in the browser's time zone. */ +export function toDateTimeLocalValue(date: Date): string { + const pad = (value: number) => String(value).padStart(2, "0"); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`; +} + +export function scheduleDraftErrors(draft: DraftState) { + if (draft.scheduleMode === "once") { + const runAt = new Date(draft.runAt); + if (Number.isNaN(runAt.getTime())) + return [{ title: "Invalid run time", description: "Pick a date and time." }]; + // A time skipped by a daylight saving change parses to a different clock time. + if (toDateTimeLocalValue(runAt) !== draft.runAt) + return [ + { title: "Invalid run time", description: "That time does not exist in your time zone." }, + ]; + return []; + } if (draft.scheduleMode !== "webhook") return []; if (parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes) === undefined) return [ @@ -107,7 +128,7 @@ export function webhookDraftErrors(draft: DraftState) { ]; const errors: Array<{ title: string; description: string }> = []; for (const [label, value] of [ - ["Replay key", draft.replayKey], + ["Duplicate request key", draft.replayKey], ["Coalesce key", draft.coalesceKey], ] as const) { if (value.trim() && !isWebhookDedupeTemplate(value.trim())) @@ -144,8 +165,26 @@ export function webhookDeliveryLabel(delivery: { } export function scheduleFromDraft(draft: DraftState): ScheduledTaskUpsertSchedule | null { + if (scheduleDraftErrors(draft).length > 0) return null; + if (draft.scheduleMode === "once") { + const saved = draft.savedRunAt ? new Date(draft.savedRunAt) : null; + if (saved !== null && toDateTimeLocalValue(saved) === draft.runAt) + return { type: "once", runAt: draft.savedRunAt }; + // A `datetime-local` value has no offset. In an hour that repeats when clocks go + // back, keep the saved time's offset; otherwise Date reads it as local time. + const withSavedOffset = + saved === null + ? null + : new Date(Date.parse(`${draft.runAt}Z`) + saved.getTimezoneOffset() * 60_000); + return { + type: "once", + runAt: + withSavedOffset !== null && toDateTimeLocalValue(withSavedOffset) === draft.runAt + ? withSavedOffset.toISOString() + : new Date(draft.runAt).toISOString(), + }; + } if (draft.scheduleMode === "webhook") { - if (webhookDraftErrors(draft).length > 0) return null; const maxDeliveryAgeMinutes = parseMaxDeliveryAge(draft.maxDeliveryAgeMinutes); const replayKey = draft.replayKey.trim(); const coalesceKey = draft.coalesceKey.trim(); @@ -206,11 +245,12 @@ export function taskToDraft(task: ScheduledTask): DraftState { title: task.title, prompt: task.prompt, enabled: task.enabled, - scheduleMode: - schedule.type === "interval" ? "interval" : schedule.type === "webhook" ? "webhook" : "fixed", + scheduleMode: schedule.type === "fixed_time" ? "fixed" : schedule.type, intervalMinutes: schedule.type === "interval" ? String(Math.max(1, schedule.everyMs / 60_000)) : "15", timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00", + runAt: schedule.type === "once" ? toDateTimeLocalValue(new Date(schedule.runAt)) : "", + savedRunAt: schedule.type === "once" ? schedule.runAt : "", weekdays, projectId: task.projectId, threadId: task.threadId ?? "", diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index 1450aea5fcc3e..c488a56e21c13 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -61,6 +61,7 @@ describe("searchSettings", () => { ]); expect(searchSettings("claude", ITEMS).map((item) => item.id)).toEqual(["providers"]); expect(searchSettings("long lines", ITEMS).map((item) => item.id)).toEqual(["word-wrap"]); + // Coder: no "Fallback model" item; the out-of-usage fallback is not carried. }); it("matches normalized title substrings", () => { @@ -146,7 +147,7 @@ describe("searchSettings", () => { }); describe("settings search targets", () => { - // Coder: no OpenTelemetry export settings, so there is no telemetry export target to resolve. + // Coder: no OpenTelemetry export settings or fallback model, so neither target is resolved. it("keeps environment-wide settings out of project scopes", () => { const updates = getSettingsSearchTargetScope("background-activity")!; expect(updates.scope).toBe("environment-defaults"); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 34602c566dbef..73170871c0f6d 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -245,6 +245,7 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "project-defaults", searchTerms: ["new thread project provider reasoning effort"], }, + // Coder: no "Fallback model" row; upstream's out-of-usage fallback is not carried. { id: "default-permissions", title: "Permissions", @@ -519,9 +520,11 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "proactive-panels", - title: "Proactive panels", + title: "Open merge requests and changes panels proactively", to: "/settings/diffs", - searchTerms: ["automatically open diff merge request mr right panel agent completion"], + searchTerms: [ + "proactive automatically open diff merge request mr right panel agent completion", + ], }, { id: "pull-request-links-open-in-app", diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx new file mode 100644 index 0000000000000..c29932f5757e1 --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -0,0 +1,68 @@ +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { Profiler } from "react"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; +import { SidebarDraftBlock } from "./SidebarDraftBlock"; + +it("keeps draft previews current through edits, promotion and removal", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-preview-environment"); + const projectRef = scopeProjectRef(environmentId, ProjectId.make("draft-preview-project")); + const draftId = DraftId.make("draft-preview"); + const threadId = ThreadId.make("draft-preview-thread"); + const onRender = vi.fn(); + await using screen = await render( + +
    + +
+
, + ); + const row = screen.getByTestId("sidebar-draft-row"); + await expect.element(row).not.toBeInTheDocument(); + + await act(() => { + initial.setProjectDraftThreadId(projectRef, draftId, { threadId }); + initial.setPrompt(draftId, "First draft preview"); + }); + await expect.element(row).toHaveAccessibleName("First draft preview, Unsent draft"); + + const rendersBeforeOtherComposer = onRender.mock.calls.length; + await act(() => + initial.setPrompt(scopeThreadRef(environmentId, ThreadId.make("other")), "Other composer"), + ); + expect(onRender).toHaveBeenCalledTimes(rendersBeforeOtherComposer); + await act(() => initial.setPrompt(draftId, "Updated draft preview")); + await expect.element(row).toHaveAccessibleName("Updated draft preview, Unsent draft"); + + await act(() => initial.markDraftThreadPromoting(draftId)); + await expect.element(row).not.toBeInTheDocument(); + await act(() => initial.clearDraftThread(draftId)); + + const nextDraftId = DraftId.make("next-draft-preview"); + await act(() => { + initial.setProjectDraftThreadId(projectRef, nextDraftId, { threadId: ThreadId.make("next") }); + initial.setPrompt(nextDraftId, "Next draft preview"); + }); + await expect.element(row).toHaveAccessibleName("Next draft preview, Unsent draft"); + await act(() => initial.clearDraftThread(nextDraftId)); + await expect.element(row).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 4e1d56213a66f..a2fc539ff58ba 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -8,6 +8,7 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; @@ -147,7 +148,15 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { onDraftContextMenu: (draftId: DraftId, position: { x: number; y: number }) => void; }) { const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey); - const draftsByThreadKey = useComposerDraftStore((store) => store.draftsByThreadKey); + const draftsByThreadKey = useComposerDraftStore( + useShallow((store) => + Object.fromEntries( + Object.keys(store.draftThreadsByThreadKey).map( + (key) => [key, store.draftsByThreadKey[key]] as const, + ), + ), + ), + ); const [frozenActive, setFrozenActive] = useState<{ routeDraftId: string | null; row: SidebarDraftRowData | null; diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index e7f5545c887e6..55bc8e996d61c 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -108,6 +108,7 @@ import { getTriggerDisplayModelName } from "../chat/providerIconUtils"; import { shouldShowInstanceBadge, type ProviderInstanceEntry } from "../../providerInstances"; import { useThreadRunningTerminalIds } from "../../state/terminalSessions"; import { InlineButton } from "../ui/button"; +import { Kbd } from "../ui/kbd"; import { Menu, MenuItem, MenuPopup, MenuSeparator, MenuShortcut, MenuTrigger } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { MiddleTruncate } from "../ui/middle-truncate"; @@ -149,15 +150,15 @@ function threadTimeTimestamp(thread: SidebarThreadSummary): string { function JumpHintBadge(props: { label: string }) { return ( - + {props.label} - + ); } +const JUMP_HINT_SLOT_CLASS_NAME = + "[&>:not([data-jump-hint])]:invisible [&>:not([data-jump-hint])]:absolute"; + function WorkingDuration(props: { startedAt: string | null }) { const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN; if (Number.isNaN(startedMs)) return null; @@ -925,6 +926,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP // Closing here, not just masking, keeps the menu from reopening when the button returns. if (snoozeMenuOpenRaw && !showSnoozeButton) setSnoozeMenuOpen(false); const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton; + const jumpHintLabel = snoozeMenuOpen ? null : props.jumpLabel; const handlePrClick = (event: ReactMouseEvent, targetUrl?: string) => { const url = targetUrl ?? pr?.url ?? currentLinkedPr?.url; if (!url) return; @@ -1256,6 +1258,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn( "relative ml-auto flex h-6 min-w-8 shrink-0 items-center justify-end", props.sweepAction !== null && "hidden", + jumpHintLabel && JUMP_HINT_SLOT_CLASS_NAME, )} > Settle thread
)} + {jumpHintLabel ? : null} )} {props.sweepAction !== null ? dragDestination : null}
{multiline ? metaLine : null} - {props.jumpLabel ? : null} {detailsTooltip} @@ -1442,6 +1445,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP className={cn( "group/sidebar-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs", props.sweepAction !== null && "hidden", + jumpHintLabel && JUMP_HINT_SLOT_CLASS_NAME, )} > ) : null} + {jumpHintLabel ? : null} )} {props.sweepAction !== null ? dragDestination : null} @@ -1572,7 +1577,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
{metaLine}
- {props.jumpLabel ? : null} {detailsTooltip} diff --git a/apps/web/src/components/ui/menu.tsx b/apps/web/src/components/ui/menu.tsx index 47ae92c241e15..1c199afe446f5 100644 --- a/apps/web/src/components/ui/menu.tsx +++ b/apps/web/src/components/ui/menu.tsx @@ -25,6 +25,7 @@ function MenuPopup({ align = "center", alignOffset, side = "bottom", + collisionAvoidance, anchor, keepMounted = false, width = "default", @@ -34,6 +35,7 @@ function MenuPopup({ sideOffset?: MenuPrimitive.Positioner.Props["sideOffset"]; alignOffset?: MenuPrimitive.Positioner.Props["alignOffset"]; side?: MenuPrimitive.Positioner.Props["side"]; + collisionAvoidance?: MenuPrimitive.Positioner.Props["collisionAvoidance"]; anchor?: MenuPrimitive.Positioner.Props["anchor"]; keepMounted?: boolean; width?: "default" | "content"; @@ -44,6 +46,7 @@ function MenuPopup({ align={align} alignOffset={alignOffset} anchor={anchor} + collisionAvoidance={collisionAvoidance} className="z-[130]" data-slot="menu-positioner" render={renderClosingPositioner} diff --git a/apps/web/src/composer-list-split.browser.test.ts b/apps/web/src/composer-list-split.browser.test.ts index a1d09bccab5e3..632bb1ff4d3ef 100644 --- a/apps/web/src/composer-list-split.browser.test.ts +++ b/apps/web/src/composer-list-split.browser.test.ts @@ -68,6 +68,25 @@ describe("Backspace at the start of a line", () => { editor.commands.keyboardShortcut("Backspace"); expect(storedDraft(editor)).toBe(expected); }); + + // Neither item has a list of its own kind one level up to lift into. + it.each([ + ["- a\n - [ ] x\n - [ ] y", "- a\n - [ ] xy"], + ["- [ ] a\n - x\n - y", "- [ ] a\n - xy"], + ["- a\n - [ ] y\n - [ ] q", "- ay\n - [ ] q"], + ])("joins y in %j onto the line above", (value, expected) => { + using editor = makeEditor(value); + placeCaret(editor, "y"); + editor.commands.keyboardShortcut("Backspace"); + expect(storedDraft(editor)).toBe(expected); + }); + + it("removes an empty checkbox under a bullet", () => { + using editor = makeEditor("- a\n - [ ] x\n - [ ]"); + editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc))); + editor.commands.keyboardShortcut("Backspace"); + expect(storedDraft(editor)).toBe("- a\n - [ ] x"); + }); }); describe("blocks that a list item or quote cannot hold", () => { diff --git a/apps/web/src/composer-rich-text-doc.test.ts b/apps/web/src/composer-rich-text-doc.test.ts index 3ad569e4b8a40..ab7f2c542a19f 100644 --- a/apps/web/src/composer-rich-text-doc.test.ts +++ b/apps/web/src/composer-rich-text-doc.test.ts @@ -20,7 +20,10 @@ import { ComposerBlockExtensions, ComposerCodeBlockExtension, ComposerListExtensions, + ComposerBoldExtension, ComposerCodeExtension, + ComposerItalicExtension, + ComposerStrikeExtension, ComposerTaskItemExtension, flatToMarkdown, flatToPm, @@ -1003,7 +1006,17 @@ describe("inline code entry", () => { const editor = new Editor({ element: null, extensions: [ - StarterKit.configure({ code: false, codeBlock: false, trailingNode: false }), + StarterKit.configure({ + bold: false, + code: false, + codeBlock: false, + italic: false, + strike: false, + trailingNode: false, + }), + ComposerBoldExtension, + ComposerItalicExtension, + ComposerStrikeExtension, ComposerCodeExtension, ComposerCodeBlockExtension, stubAtom("composer-mention", { path: { default: "" }, source: { default: "" } }), @@ -1028,6 +1041,56 @@ describe("inline code entry", () => { } } + it.each(["", "this is a "])( + "formats code after %j when the opening backtick is typed last", + (prefix) => { + const editor = editorFor(); + type(editor, `${prefix}test\` after`); + editor.commands.setTextSelection(prefix.length + 1); + type(editor, "`"); + + expect(editor.state.doc.textContent).toBe(`${prefix}test after`); + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`test\` after`); + expect(editor.state.selection.from).toBe(prefix.length + 1); + type(editor, "new "); + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`new test\` after`); + editor.commands.setTextSelection(editor.state.doc.content.size - 1); + type(editor, " plain"); + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${prefix}\`new test\` after plain`); + const formatted = editor.state.doc.toJSON(); + let undos = 0; + while (editor.commands.undo()) undos += 1; + expect(undos).toBeGreaterThan(0); + expect(editor.state.doc.textContent).toBe(""); + for (let i = 0; i < undos; i += 1) expect(editor.commands.redo()).toBe(true); + expect(editor.state.doc.toJSON()).toEqual(formatted); + }, + ); + + it.each([ + { name: "doubled closing ticks", text: "test``" }, + { name: "a code block", text: "test`", block: "codeBlock" }, + { name: "bold text", text: "test`", mark: "bold" }, + { name: "existing inline code", text: "test`", mark: "code" }, + ])("keeps an opening tick literal before $name", ({ text, block, mark }) => { + const editor = editorFor(block, mark); + type(editor, text); + editor.commands.setTextSelection(1); + type(editor, "`"); + expect(editor.state.doc.textContent).toBe(`\`${text}`); + }); + + it.each(["hardBreak", "composer-mention"])("does not pair ticks across a %s", (nodeType) => { + const editor = editorFor(); + type(editor, "before"); + editor.commands.insertContent({ type: nodeType }); + type(editor, "after`"); + editor.commands.setTextSelection(1); + type(editor, "`"); + expect(editor.state.doc.firstChild?.firstChild?.marks).toEqual([]); + expect(editor.state.doc.textContent).toBe("`beforeafter`"); + }); + it.each(["", "prefix ", "@README.md"])( "formats a filled pair after %j, leaves following text plain, and keeps the normal input rule", (prefix) => { @@ -1115,4 +1178,70 @@ describe("inline code entry", () => { editor.commands.setTextSelection(editor.state.doc.content.size - 1); expect(editor.state.doc.toJSON()).toEqual(before); }); + + function marked(editor: Editor, name: string) { + const text: string[] = []; + editor.state.doc.descendants((node) => { + if (node.isText && node.marks.some((mark) => mark.type.name === name)) { + text.push(node.text ?? ""); + } + }); + return text; + } + + /** Types `text` into a backtick pair and steps the caret out so it formats. */ + function typeCode(editor: Editor, text: string) { + const offset = editor.state.selection.from; + type(editor, "``"); + editor.commands.setTextSelection(offset + 1); + type(editor, text); + editor.commands.setTextSelection(offset + text.length + 2); + expect(marked(editor, "code")).toContain(text); + } + + it.each([ + { mark: "italic", open: "*" }, + { mark: "bold", open: "**" }, + { mark: "strike", open: "~~" }, + ])("keeps a $mark delimiter inside an earlier code span literal", ({ mark, open }) => { + const editor = editorFor(); + typeCode(editor, `${open}foo`); + type(editor, ` bar \`${open}`); + expect(serializeEditorDoc(editor.state.doc).value).toBe(`\`${open}foo\` bar \`${open}`); + expect(marked(editor, mark)).toEqual([]); + expect(marked(editor, "code")).toEqual([`${open}foo`]); + }); + + it.each([ + { mark: "italic", open: "*" }, + { mark: "bold", open: "**" }, + { mark: "strike", open: "~~" }, + ])("still wraps a code span in $mark when both delimiters are outside it", ({ mark, open }) => { + const editor = editorFor(); + type(editor, open); + typeCode(editor, "foo"); + type(editor, ` bar${open}`); + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${open}\`foo\` bar${open}`); + expect(marked(editor, mark)).toEqual(["foo", " bar"]); + + editor.commands.setContent({ + type: "doc", + content: [ + { + type: "paragraph", + content: [ + { type: "text", text: `${open}foo tail ` }, + { type: "text", text: "x", marks: [{ type: "code" }] }, + ], + }, + ], + }); + editor.commands.setTextSelection({ + from: open.length + 4, + to: editor.state.doc.content.size - 1, + }); + type(editor, open); + expect(serializeEditorDoc(editor.state.doc).value).toBe(`${open}foo${open}`); + expect(marked(editor, mark)).toEqual(["foo"]); + }); }); diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.ts index c0e0a653016e3..7025b687850da 100644 --- a/apps/web/src/composer-rich-text-doc.ts +++ b/apps/web/src/composer-rich-text-doc.ts @@ -1,4 +1,4 @@ -import { joinBackward, joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands"; +import { joinTextblockBackward, joinTextblockForward } from "@tiptap/pm/commands"; import { Fragment, Mark, @@ -6,6 +6,11 @@ import { type Node as ProseMirrorNode, type ResolvedPos, } from "@tiptap/pm/model"; +import { + Bold, + starInputRegex as boldStarInputRegex, + underscoreInputRegex as boldUnderscoreInputRegex, +} from "@tiptap/extension-bold"; import { Code } from "@tiptap/extension-code"; import { Blockquote } from "@tiptap/extension-blockquote"; import { CodeBlock } from "@tiptap/extension-code-block"; @@ -16,11 +21,13 @@ import { type Command, type Editor, Extension, + InputRule, markInputRule, markPasteRule, mergeAttributes, } from "@tiptap/core"; import { BulletList, ListItem, OrderedList } from "@tiptap/extension-list"; +import { Strike, inputRegex as strikeInputRegex } from "@tiptap/extension-strike"; import { TaskItem } from "@tiptap/extension-task-item"; import { TaskList } from "@tiptap/extension-task-list"; import { @@ -81,14 +88,37 @@ function codePairCaretPlugin(type: MarkType) { handleTextInput(view, from, to, text, insert) { if (view.composing || from !== to || text !== "`") return false; const $from = view.state.doc.resolve(from); - if ( - !$from.parent.isTextblock || - $from.parent.type.spec.code || - !/(^|[^`])`$/.test($from.nodeBefore?.text ?? "") - ) { - return false; + if (!$from.parent.isTextblock || $from.parent.type.spec.code) return false; + const before = $from.nodeBefore?.text ?? ""; + if (/(^|[^`])`$/.test(before)) { + view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 })); + return true; } - view.dispatch(insert().setMeta(codePairKey, { from: from - 1, to: from + 1 })); + if (before.endsWith("`")) return false; + + // The opening tick can be typed after the closing one. Input rules + // cannot recognize that pair because they only read before the caret. + const after = $from.parent.textBetween( + $from.parentOffset, + $from.parent.content.size, + "\n", + "\n", + ); + const match = /^([^`\n]+)`(?!`)/.exec(after); + if (!match) return false; + const end = from + match[1]!.length; + let plain = true; + view.state.doc.nodesBetween(from, end + 1, (node) => { + if (node.isInline && (!node.isText || node.marks.length > 0)) plain = false; + }); + if (!plain) return false; + const tr = insert() + .delete(end + 1, end + 2) + .delete(from, from + 1); + tr.addMark(from, end, type.create()); + tr.setSelection(TextSelection.create(tr.doc, from)); + tr.addStoredMark(type.create()); + view.dispatch(tr); return true; }, }, @@ -140,6 +170,29 @@ export const ComposerCodeExtension = Code.extend({ }, }); +// Code permits nested emphasis, so Tiptap's exclusion check cannot protect literal delimiters. +function markInputRuleOutsideCode(find: RegExp, type: MarkType) { + const rule = markInputRule({ find, type }); + return new InputRule({ + find, + handler: (props) => { + const { state, range, match } = props; + const code = state.schema.marks.code; + const content = match[match.length - 1] ?? ""; + const textStart = range.from + match[0].indexOf(content); + const textEnd = textStart + content.length; + if ( + code && + (state.doc.rangeHasMark(range.from + match[0].search(/\S/), textStart, code) || + state.doc.rangeHasMark(textEnd, state.selection.from, code)) + ) { + return null; + } + return rule.handler(props); + }, + }); +} + /** * The composer writes italic as `*text*`, so it keeps only the `*` shortcuts. * Tiptap's `_text_` rules fire on the `_` in names like `node_modules` and @@ -147,13 +200,28 @@ export const ComposerCodeExtension = Code.extend({ */ export const ComposerItalicExtension = Italic.extend({ addInputRules() { - return [markInputRule({ find: starInputRegex, type: this.type })]; + return [markInputRuleOutsideCode(starInputRegex, this.type)]; }, addPasteRules() { return [markPasteRule({ find: starPasteRegex, type: this.type })]; }, }); +export const ComposerBoldExtension = Bold.extend({ + addInputRules() { + return [ + markInputRuleOutsideCode(boldStarInputRegex, this.type), + markInputRuleOutsideCode(boldUnderscoreInputRegex, this.type), + ]; + }, +}); + +export const ComposerStrikeExtension = Strike.extend({ + addInputRules() { + return [markInputRuleOutsideCode(strikeInputRegex, this.type)]; + }, +}); + /** * Mod+B bolds selected text only. Without a selection Tiptap would toggle bold * for the next typed text, which users hit by accident when they mean the @@ -1135,7 +1203,8 @@ function backspaceAcrossList(editor: Editor): boolean { return moved; }; // can() skips the schema check and can accept tasks with no parent list to lift into. - return editor.chain().command(lift).run() || joinBackward(state, editor.view.dispatch); + // Those join the line above; joinBackward would re-nest them or select the parent line. + return editor.chain().command(lift).run() || joinTextblockBackward(state, editor.view.dispatch); } const before = $from.depth === 1 ? $from.node(0).maybeChild($from.index(0) - 1) : null; if (before && LIST_NODE_NAMES.has(before.type.name) && $from.parent.type.name !== "codeBlock") { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 3e0ff3bb1967d..d506e2a7a53e2 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -47,7 +47,11 @@ import type { } from "@t3tools/client-runtime/state/shell"; import { waitForDraftHeroTransition } from "./components/chat/draftHeroTransition"; import { getLocalStorageItem } from "./hooks/useLocalStorage"; -import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection"; +import { + readInstanceCustomModels, + resolveAppModelSelection, + resolveAppModelSelectionForInstance, +} from "./modelSelection"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, @@ -1098,8 +1102,12 @@ export function deriveEffectiveComposerModelState(input: { const instanceSelection = input.selectedInstanceId ? input.draft?.modelSelectionByProvider?.[input.selectedInstanceId] : undefined; + // Legacy driver-keyed drafts belong to the default instance. const legacySelection = - input.draft?.modelSelectionByProvider?.[ProviderInstanceId.make(input.selectedProvider)]; + input.selectedInstanceId && + input.selectedInstanceId !== defaultInstanceIdForDriver(input.selectedProvider) + ? undefined + : input.draft?.modelSelectionByProvider?.[ProviderInstanceId.make(input.selectedProvider)]; const activeSelection = instanceSelection ?? legacySelection; const activeSelectionInstanceId = instanceSelection ? (input.selectedInstanceId ?? ProviderInstanceId.make(input.selectedProvider)) @@ -1153,6 +1161,7 @@ function withFallbackInstanceOptions(input: { readonly selectedProvider: ProviderDriverKind; readonly selectedInstanceId?: ProviderInstanceId | null | undefined; readonly requestedInstanceId?: ProviderInstanceId | null | undefined; + readonly settings: UnifiedSettings; }): ProviderOptionSelectionsByProvider | null { const { modelOptions, selectedInstanceId, requestedInstanceId } = input; if ( @@ -1165,16 +1174,26 @@ function withFallbackInstanceOptions(input: { return modelOptions; } const requestedOptions = modelOptions[requestedInstanceId]; - const requestedDriver = input.providers.find( + const requestedProvider = input.providers.find( (provider) => provider.instanceId === requestedInstanceId, - )?.driver; - // The model of the selection the options came from, which can differ from the shown model's source. + ); const requestedModel = input.optionSelections?.[requestedInstanceId]?.model; - if ( - !requestedOptions || - requestedDriver !== input.selectedProvider || - requestedModel !== input.selectedModel - ) { + // Static aliases are shared across instances; exact custom slugs and catalog aliases are not. + const modelIdentity = (instanceId: ProviderInstanceId, model: string | undefined) => { + const isCustom = + input.providers + .find((provider) => provider.instanceId === instanceId) + ?.models.some((entry) => entry.slug === model && entry.isCustom) || + readInstanceCustomModels(input.settings, instanceId, input.selectedProvider).some( + (entry) => entry.slug === model, + ); + return isCustom ? model : normalizeModelSlug(model, input.selectedProvider); + }; + const sameModel = + requestedModel === input.selectedModel || + modelIdentity(requestedInstanceId, requestedModel) === + modelIdentity(selectedInstanceId, input.selectedModel); + if (!requestedOptions || requestedProvider?.driver !== input.selectedProvider || !sameModel) { return modelOptions; } return { ...modelOptions, [selectedInstanceId]: requestedOptions }; diff --git a/apps/web/src/hooks/useResizableWidth.browser.test.tsx b/apps/web/src/hooks/useResizableWidth.browser.test.tsx new file mode 100644 index 0000000000000..a34c985f8c128 --- /dev/null +++ b/apps/web/src/hooks/useResizableWidth.browser.test.tsx @@ -0,0 +1,85 @@ +import { describe, expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../test/render"; +import { RESIZABLE_WIDTH_PROPERTY, useResizableWidth } from "./useResizableWidth"; + +const STORAGE_KEY = "test:responsive-panel-width"; + +function Panel({ defaultWidth }: { defaultWidth: number }) { + const { width, setWidth, handlers } = useResizableWidth({ + storageKey: STORAGE_KEY, + defaultWidth, + minWidth: 160, + maxWidth: 560, + edge: "left", + }); + return ( + <> + +
+ + ); +} + +describe("useResizableWidth", () => { + it("follows a responsive default until the user saves a width", async () => { + const previous = localStorage.getItem(STORAGE_KEY); + localStorage.removeItem(STORAGE_KEY); + try { + // This hook only needs browser storage and React; no navigation is involved. + await using screen = await render(, { router: false }); + expect(screen.container.textContent).toBe("320"); + await screen.rerender(); + expect(screen.container.textContent).toBe("200"); + + await act(() => screen.container.querySelector("button")!.click()); + await screen.rerender(); + expect(screen.container.textContent).toBe("350"); + + await screen.unmount(); + await using restored = await render(, { router: false }); + expect(restored.container.textContent).toBe("350"); + } finally { + if (previous === null) localStorage.removeItem(STORAGE_KEY); + else localStorage.setItem(STORAGE_KEY, previous); + } + }); + + it("keeps the default responsive after a stationary click and persists an actual drag", async () => { + const previous = localStorage.getItem(STORAGE_KEY); + localStorage.removeItem(STORAGE_KEY); + try { + // This hook only needs browser storage and React; no navigation is involved. + await using screen = await render(, { router: false }); + await screen.getByRole("separator").click(); + expect(localStorage.getItem(STORAGE_KEY)).toBeNull(); + await screen.rerender(); + expect(screen.container.textContent).toBe("256"); + + const handle = screen.container.querySelector('[role="separator"]')!; + // Synthetic drag events have no active browser pointer to capture. + using _capture = vi.spyOn(handle, "setPointerCapture").mockImplementation(() => {}); + const pointer = { bubbles: true, pointerId: 1, button: 0 }; + await act(() => { + handle.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientX: 500 })); + }); + await screen.rerender(); + await act(() => { + handle.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: 500 })); + }); + expect(localStorage.getItem(STORAGE_KEY)).toBeNull(); + expect(screen.container.style.getPropertyValue(RESIZABLE_WIDTH_PROPERTY)).toBe("280px"); + + await act(() => { + handle.dispatchEvent(new PointerEvent("pointerdown", { ...pointer, clientX: 500 })); + handle.dispatchEvent(new PointerEvent("pointerup", { ...pointer, clientX: 450 })); + }); + expect(localStorage.getItem(STORAGE_KEY)).toBe("330"); + await screen.rerender(); + expect(screen.container.textContent).toBe("330"); + } finally { + if (previous === null) localStorage.removeItem(STORAGE_KEY); + else localStorage.setItem(STORAGE_KEY, previous); + } + }); +}); diff --git a/apps/web/src/hooks/useResizableWidth.ts b/apps/web/src/hooks/useResizableWidth.ts index 50fdba38a9fc5..dc5fe8569d03e 100644 --- a/apps/web/src/hooks/useResizableWidth.ts +++ b/apps/web/src/hooks/useResizableWidth.ts @@ -3,6 +3,7 @@ import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useState } fro import { getLocalStorageItem, setLocalStorageItem } from "./useLocalStorage"; import { useResizeDrag } from "./useResizeDrag"; +import { useStableCallback } from "./useStableCallback"; const WidthSchema = Schema.Finite; @@ -26,7 +27,7 @@ export interface ResizableWidthHandlers { readonly onLostPointerCapture: (event: ReactPointerEvent) => void; } -/** Persist on drag end to avoid a storage write on every animation frame. */ +/** Uses the current default until a width is chosen; persists on drag end, not every frame. */ export function useResizableWidth(options: UseResizableWidthOptions): { readonly width: number; readonly setWidth: (width: number) => void; @@ -39,14 +40,14 @@ export function useResizableWidth(options: UseResizableWidthOptions): { return Math.max(minWidth, Math.min(maxWidth, value)); }; - const readWidth = () => { - if (typeof window === "undefined") return defaultWidth; + const readWidth = (): number | null => { + if (typeof window === "undefined") return null; try { const stored = getLocalStorageItem(storageKey, WidthSchema); - return clamp(stored ?? defaultWidth); + return stored === null ? null : clamp(stored); } catch (error) { console.error("Could not read persisted panel width.", error); - return defaultWidth; + return null; } }; const [widthState, setWidthState] = useState(() => ({ storageKey, width: readWidth() })); @@ -54,7 +55,10 @@ export function useResizableWidth(options: UseResizableWidthOptions): { setWidthState({ storageKey, width: readWidth() }); } - const clampedWidth = clamp(widthState.width); + const clampedWidth = clamp(widthState.width ?? defaultWidth); + const restoreWidth = useStableCallback((host: HTMLElement | null) => { + host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${clampedWidth}px`); + }); const commitWidth = (nextStorageKey: string, nextWidth: number) => { // Resizing remains usable for this session when browser storage is unavailable. @@ -82,8 +86,9 @@ export function useResizableWidth(options: UseResizableWidthOptions): { host?.style.setProperty(RESIZABLE_WIDTH_PROPERTY, `${nextWidth}px`); return nextWidth; }, - finish(finalWidth) { - commitWidth(startStorageKey, finalWidth); + finish(finalWidth, moved) { + if (moved) commitWidth(startStorageKey, finalWidth); + else restoreWidth(host); }, cleanup(committed) { host?.style.removeProperty("transition-property"); diff --git a/apps/web/src/hooks/useThreadVisitedMigration.test.ts b/apps/web/src/hooks/useThreadVisitedMigration.test.ts new file mode 100644 index 0000000000000..e0bd84855cc33 --- /dev/null +++ b/apps/web/src/hooks/useThreadVisitedMigration.test.ts @@ -0,0 +1,103 @@ +import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { EnvironmentId } from "@t3tools/contracts"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { environmentThreadShells } from "../state/threads"; +import { makeThreadFixture } from "../test-fixtures"; +import { startThreadVisitedMigration } from "./useThreadVisitedMigration"; + +const state = vi.hoisted(() => ({ + localVisits: {} as Record, +})); + +vi.mock("@t3tools/client-runtime/state/runtime", () => ({ runAtomCommand: vi.fn() })); +vi.mock("../uiStateStore", () => ({ + useUiStateStore: { getState: () => ({ threadLastVisitedAtById: state.localVisits }) }, +})); +vi.mock("../state/threads", async () => { + const { Atom } = await import("effect/reactivity"); + return { + environmentThreadShells: { + threadShellsAtom: Atom.make>([]), + }, + threadEnvironment: { visit: {} }, + }; +}); + +const localVisit = "2026-10-27T10:00:00.000Z"; + +function setup(threads: ReadonlyArray, local = localVisit) { + state.localVisits = Object.fromEntries( + threads.map((thread) => [ + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + local, + ]), + ); + vi.mocked(runAtomCommand).mockReset().mockResolvedValue(AsyncResult.success(undefined)); + const tasks: Array<() => void> = []; + const registry = AtomRegistry.make({ + scheduleTask: (task) => { + tasks.push(task); + return () => {}; + }, + }); + const shells = environmentThreadShells.threadShellsAtom; + if (!Atom.isWritable(shells)) throw new Error("Expected writable test shell state"); + registry.set(shells, threads); + const stop = startThreadVisitedMigration(registry); + return { + setThreads(next: ReadonlyArray) { + registry.set(shells, next); + for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task(); + }, + [Symbol.dispose]() { + stop(); + registry.dispose(); + }, + }; +} + +describe("startThreadVisitedMigration", () => { + it("preserves mark unread when a client with a newer local visit reloads", () => { + using _migration = setup([makeThreadFixture({ lastVisitedAt: "2026-10-27T09:59:59.999Z" })]); + + expect(runAtomCommand).not.toHaveBeenCalled(); + }); + + it("seeds unset visits once per environment and thread", () => { + const thread = makeThreadFixture({ lastVisitedAt: null }); + const remote = { ...thread, environmentId: EnvironmentId.make("remote") }; + using migration = setup([thread, remote]); + + expect(vi.mocked(runAtomCommand).mock.calls.map((call) => call[2])).toEqual([ + { + environmentId: thread.environmentId, + input: { threadId: thread.id, visitedAt: localVisit }, + }, + { + environmentId: remote.environmentId, + input: { threadId: remote.id, visitedAt: localVisit }, + }, + ]); + migration.setThreads([{ ...thread }, { ...remote }]); + expect(runAtomCommand).toHaveBeenCalledTimes(2); + }); + + it("waits for older servers to support visits before migrating", () => { + const thread = makeThreadFixture(); + expect(thread.lastVisitedAt).toBeUndefined(); + using migration = setup([thread]); + expect(runAtomCommand).not.toHaveBeenCalled(); + + migration.setThreads([{ ...thread, lastVisitedAt: null }]); + expect(runAtomCommand).toHaveBeenCalledTimes(1); + }); + + it.each(["", "not-a-date"])("ignores invalid local visits: %s", (local) => { + using _migration = setup([makeThreadFixture({ lastVisitedAt: null })], local); + expect(runAtomCommand).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/hooks/useThreadVisitedMigration.ts b/apps/web/src/hooks/useThreadVisitedMigration.ts index 2d01d800360ea..fb90b6d4f2e1d 100644 --- a/apps/web/src/hooks/useThreadVisitedMigration.ts +++ b/apps/web/src/hooks/useThreadVisitedMigration.ts @@ -15,8 +15,8 @@ export function startThreadVisitedMigration(registry: AtomRegistry.AtomRegistry) const migratedThreadKeys = new Set(); const migrate = (threads: ReadonlyArray) => { for (const thread of threads) { - // Missing means unsupported; retain the local value until the server upgrades. - if (thread.lastVisitedAt === undefined) continue; + // An established server watermark may be deliberately older after Mark unread. + if (thread.lastVisitedAt !== null) continue; const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); if (migratedThreadKeys.has(threadKey)) continue; migratedThreadKeys.add(threadKey); @@ -24,8 +24,6 @@ export function startThreadVisitedMigration(registry: AtomRegistry.AtomRegistry) if (!local) continue; const localMs = Date.parse(local); if (!Number.isFinite(localMs)) continue; - const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt); - if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue; void runAtomCommand( registry, threadEnvironment.visit, diff --git a/apps/web/src/index.css b/apps/web/src/index.css index d182ea224e9ad..7c5236cb5082f 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1559,6 +1559,7 @@ html[data-theme-id] [data-app-sidebar] { --accent-foreground: var(--app-theme-accent-surface-foreground); --muted: var(--app-theme-muted); --muted-foreground: var(--app-theme-muted-foreground); + --secondary-label: var(--app-theme-secondary-label); --border: var(--app-theme-border); --input: var(--app-theme-input); --sidebar: var(--app-theme-sidebar); diff --git a/apps/web/src/modelSelection.test.ts b/apps/web/src/modelSelection.test.ts index 464d01da6068f..c7e88f4ac9d69 100644 --- a/apps/web/src/modelSelection.test.ts +++ b/apps/web/src/modelSelection.test.ts @@ -1,10 +1,16 @@ import { DEFAULT_TEXT_GENERATION_MODEL, + DEFAULT_SERVER_SETTINGS, + ProjectId, ProviderDriverKind, ProviderInstanceId, type ServerProvider, } from "@t3tools/contracts"; -import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts/settings"; +import { + DEFAULT_CLIENT_SETTINGS, + DEFAULT_UNIFIED_SETTINGS, + type UnifiedSettings, +} from "@t3tools/contracts/settings"; import { describe, expect, it } from "vite-plus/test"; import { createModelSelection } from "@t3tools/shared/model"; import { deriveEffectiveComposerModelState } from "./composerDraftStore"; @@ -17,6 +23,7 @@ import { } from "./providerInstances"; import { getCustomModelOptionsByInstance, + defaultModelSelectionsAreMixed, getAppModelOptionsForInstance, resolveAppModelSelectionForInstance, resolveAppModelSelectionState, @@ -73,6 +80,142 @@ function settingsWithProviderInstances(): UnifiedSettings { }; } +describe("scoped default model selections", () => { + // regression: #27997 equal automatic defaults can resolve to different providers + it("compares automatic defaults using each environment's models", () => { + const codex = { + projectId: null, + settings: DEFAULT_UNIFIED_SETTINGS, + providers: [provider({ instanceId: "codex", models: ["gpt-6-astra"] })], + }; + const claude = { + projectId: null, + settings: DEFAULT_UNIFIED_SETTINGS, + providers: [ + provider({ + instanceId: "claudeAgent", + provider: ProviderDriverKind.make("claudeAgent"), + models: ["claude-sonnet-4-6"], + }), + ], + }; + + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [codex, claude])).toBe(true); + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [claude, codex])).toBe(true); + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [codex, codex])).toBe(false); + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [claude])).toBe(false); + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [])).toBe(false); + expect( + defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [codex, { ...codex, providers: [] }]), + ).toBe(true); + expect( + defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [ + codex, + { ...codex, providers: [provider({ instanceId: "codex", models: ["gpt-6-sol"] })] }, + ]), + ).toBe(true); + + const projectId = ProjectId.make("claude-only"); + const project = { + projectId, + settings: { + ...DEFAULT_SERVER_SETTINGS, + projectSettingsOverrides: { + [projectId]: { + providerInstances: { [ProviderInstanceId.make("codex")]: { enabled: false } }, + }, + }, + }, + providers: [...codex.providers, ...claude.providers], + }; + const remoteProject = { ...claude, projectId: ProjectId.make("remote-project") }; + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [project, remoteProject])).toBe( + false, + ); + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [remoteProject, project])).toBe( + false, + ); + expect( + defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [ + project, + { ...project, projectId: ProjectId.make("other-project") }, + ]), + ).toBe(true); + + const configured = { + projectId: null, + settings: { + ...DEFAULT_SERVER_SETTINGS, + providerModelPreferences: { + [ProviderInstanceId.make("codex")]: { + hiddenModels: ["gpt-6-astra"], + modelOrder: [], + }, + }, + }, + providers: [provider({ instanceId: "codex", models: ["gpt-6-astra", "gpt-6-sol"] })], + }; + const inherited = { ...configured, settings: DEFAULT_SERVER_SETTINGS }; + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [configured, inherited])).toBe( + true, + ); + expect(defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [inherited, configured])).toBe( + true, + ); + const clientSettings = { + ...DEFAULT_CLIENT_SETTINGS, + providerModelPreferences: configured.settings.providerModelPreferences, + }; + expect(defaultModelSelectionsAreMixed(clientSettings, [configured, inherited])).toBe(false); + expect(defaultModelSelectionsAreMixed(clientSettings, [inherited, configured])).toBe(false); + expect( + defaultModelSelectionsAreMixed(clientSettings, [ + { ...inherited, settings: { ...DEFAULT_SERVER_SETTINGS, providerModelPreferences: {} } }, + inherited, + ]), + ).toBe(true); + }); + + it("keeps automatic, explicit, and different saved options distinct", () => { + const providers = [provider({ instanceId: "codex", models: ["gpt-6-astra"] })]; + const selected = { + projectId: null, + providers, + settings: { + ...DEFAULT_UNIFIED_SETTINGS, + defaultModelSelection: createModelSelection( + ProviderInstanceId.make("codex"), + "gpt-6-astra", + ), + }, + }; + expect( + defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [selected, { ...selected }]), + ).toBe(false); + expect( + defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [ + selected, + { projectId: null, providers, settings: DEFAULT_UNIFIED_SETTINGS }, + ]), + ).toBe(true); + expect( + defaultModelSelectionsAreMixed(DEFAULT_CLIENT_SETTINGS, [ + selected, + { + ...selected, + settings: { + ...selected.settings, + defaultModelSelection: { + ...selected.settings.defaultModelSelection, + options: [{ id: "reasoningEffort", value: "xhigh" }], + }, + }, + }, + ]), + ).toBe(true); + }); +}); + // Coder: OpenCode and Antigravity catalog cases are omitted; those drivers are never offered. describe("instance-scoped model selection", () => { it("keeps custom models on the provider instance that declared them", () => { @@ -428,6 +571,38 @@ describe("instance-scoped model selection", () => { ).toEqual(createModelSelection(instanceId, "openai/gpt-5.5")); }); + // Coder: upstream's OpenCode instances become Claude ones; OpenCode is never offered. + it("keeps the default instance's draft model off a custom instance of the same driver", () => { + const driver = ProviderDriverKind.make("claudeAgent"); + const defaultInstanceId = ProviderInstanceId.make("claudeAgent"); + const kimiInstanceId = ProviderInstanceId.make("claude_work"); + const kimiModel = "claude-opus-4-1"; + const providers = [ + provider({ + provider: driver, + instanceId: defaultInstanceId, + models: ["claude-sonnet-4-6"], + }), + provider({ provider: driver, instanceId: kimiInstanceId, models: [kimiModel] }), + ]; + const state = deriveEffectiveComposerModelState({ + draft: { + activeProvider: kimiInstanceId, + modelSelectionByProvider: { + [defaultInstanceId]: createModelSelection(defaultInstanceId, "claude-sonnet-4-6"), + }, + }, + providers, + selectedProvider: driver, + selectedInstanceId: kimiInstanceId, + threadModelSelection: null, + projectModelSelection: null, + settings: DEFAULT_UNIFIED_SETTINGS, + }); + + expect(state.selectedModel).toBe(kimiModel); + }); + it("self-heals a persisted selection pointing at a text-generation-incapable instance", () => { const providers = [ provider({ @@ -626,6 +801,7 @@ describe("composer fallback to another instance of the same driver", () => { readonly providers: ReadonlyArray; readonly draft?: Parameters[0]["draft"]; readonly threadModelSelection: ReturnType; + readonly customModels?: Partial>>; }) { const settings = { ...DEFAULT_UNIFIED_SETTINGS, @@ -635,7 +811,13 @@ describe("composer fallback to another instance of the same driver", () => { { driver: provider.driver, enabled: provider.enabled, - config: {}, + config: { + customModels: (input.customModels?.[provider.instanceId] ?? []).map((slug) => ({ + slug, + name: slug, + capabilities: null, + })), + }, }, ]), ), @@ -720,6 +902,114 @@ describe("composer fallback to another instance of the same driver", () => { expect(traits.modelOptionsForDispatch).toBeUndefined(); }); + describe("with model aliases", () => { + const reasoningModel = ( + slug: string, + id: string, + extra: Partial = {}, + ): ServerProvider["models"][number] => ({ + slug, + name: slug, + isCustom: false, + ...extra, + capabilities: { + optionDescriptors: [ + { + id, + label: id, + type: "select", + options: ["medium", "high", "xhigh"].map((value) => ({ + id: value, + label: value, + isDefault: value === "medium", + })), + }, + ], + }, + }); + + it.each([ + ["5.4", "gpt-5.4"], + ["gpt-5-codex", "gpt-5.4"], + ["gpt-5.4", "5.4"], + ])("keeps the effort from %s on fallback %s", (savedModel, fallbackModel) => { + const disabledCodex = ProviderInstanceId.make("codex"); + const fallbackCodex = ProviderInstanceId.make("codex_team"); + const models = [reasoningModel(fallbackModel, "reasoningEffort")]; + const { selectedInstanceId, state, traits } = composerFor({ + providers: [ + { ...provider({ provider: codex, instanceId: disabledCodex }), enabled: false, models }, + { ...provider({ provider: codex, instanceId: fallbackCodex }), models }, + ], + threadModelSelection: createModelSelection(disabledCodex, savedModel, [ + { id: "reasoningEffort", value: "xhigh" }, + ]), + }); + + expect(selectedInstanceId).toBe(fallbackCodex); + expect(state.selectedModel).toBe(fallbackModel); + expect(traits.promptEffort).toBe("xhigh"); + }); + + it.each([ + { + // A disabled Codex instance reports only its custom models. + state: "disabled", + requested: { + enabled: false, + models: [reasoningModel("5.4", "reasoningEffort", { isCustom: true })], + }, + }, + { + // An unavailable instance reports no models; its custom models are only in settings. + state: "unavailable", + requested: { enabled: false, availability: "unavailable" as const, models: [] }, + }, + ])( + "does not alias-expand a custom model named 5.4 when the requested instance is $state", + ({ requested }) => { + const disabledCodex = ProviderInstanceId.make("codex"); + const { state, traits } = composerFor({ + providers: [ + { ...provider({ provider: codex, instanceId: disabledCodex }), ...requested }, + { + ...provider({ provider: codex, instanceId: "codex_team" }), + models: [reasoningModel("gpt-5.4", "reasoningEffort")], + }, + ], + customModels: { [disabledCodex]: ["5.4"] }, + threadModelSelection: createModelSelection(disabledCodex, "5.4", [ + { id: "reasoningEffort", value: "xhigh" }, + ]), + }); + + expect(state.selectedModel).toBe("gpt-5.4"); + expect(traits.modelOptionsForDispatch).toBeUndefined(); + }, + ); + + it("does not alias-expand the fallback instance's custom model", () => { + const { state, traits } = composerFor({ + providers: [ + { ...provider({ provider: codex, instanceId: "codex" }), enabled: false }, + { + ...provider({ provider: codex, instanceId: "codex_team" }), + models: [reasoningModel("5.4", "reasoningEffort", { isCustom: true })], + }, + ], + customModels: { codex_team: ["5.4"] }, + threadModelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [ + { id: "reasoningEffort", value: "xhigh" }, + ]), + }); + + expect(state.selectedModel).toBe("5.4"); + expect(traits.modelOptionsForDispatch).toBeUndefined(); + }); + + // Coder: upstream's Antigravity alias case (#27859) is cut; Antigravity is never offered. + }); + it("does not carry options to another driver", () => { const codexOnly: ReadonlyArray = [ { diff --git a/apps/web/src/modelSelection.ts b/apps/web/src/modelSelection.ts index dd75f9b43c4e6..c80d9cac45402 100644 --- a/apps/web/src/modelSelection.ts +++ b/apps/web/src/modelSelection.ts @@ -4,9 +4,11 @@ import { DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, defaultInstanceIdForDriver, type ModelSelection, + type ProjectId, ProviderDriverKind, ProviderInstanceId, type ServerProvider, + type ServerSettings, } from "@t3tools/contracts"; import { type CustomModelDefinition, @@ -16,8 +18,10 @@ import { resolveSelectableModel, } from "@t3tools/shared/model"; import { getComposerProviderState } from "./components/chat/composerProviderState"; -import { UnifiedSettings } from "@t3tools/contracts/settings"; +import { type ClientSettings, UnifiedSettings } from "@t3tools/contracts/settings"; +import { resolveModelPreferences } from "@t3tools/shared/serverSettings"; import * as Arr from "effect/Array"; +import * as Equal from "effect/Equal"; import * as Result from "effect/Result"; import { getDefaultServerModel, @@ -30,6 +34,8 @@ import { // Coder: pickers and fallbacks only offer Codex, Claude, and Pi instances. deriveCoderProviderInstanceEntries, NO_PROVIDER_MODEL_SELECTION, + resolveDefaultProviderModelSelection, + resolveProjectDefaultProviderModelSelection, } from "./providerInstances"; import { sortModelsForProviderInstance } from "./modelOrdering"; import { resolveModelShortName } from "@t3tools/client-runtime/provider-clients"; @@ -38,7 +44,7 @@ export const MAX_CUSTOM_MODEL_LENGTH = 256; const DEFAULT_TEXT_GENERATION_INSTANCE_ID = ProviderInstanceId.make("codex"); // Legacy per-driver buckets would leak custom-instance models into stock instances. -function readInstanceCustomModels( +export function readInstanceCustomModels( settings: UnifiedSettings, instanceId: ProviderInstanceId, driverKind: ProviderDriverKind, @@ -309,6 +315,38 @@ export function resolveEffectiveDefaultModelSelection( return model === null || model === selection.model ? selection : { ...selection, model }; } +export function defaultModelSelectionsAreMixed( + clientSettings: ClientSettings, + targets: ReadonlyArray<{ + projectId: ProjectId | null; + settings: ServerSettings; + providers: ReadonlyArray; + }>, +): boolean { + const selections = targets.map(({ projectId, settings, providers }) => { + const stored = settings.defaultModelSelection; + const selection = + stored === null + ? resolveProjectDefaultProviderModelSelection(providers, settings, projectId) + : resolveDefaultProviderModelSelection(providers, stored); + return { + stored, + effective: selection + ? resolveEffectiveDefaultModelSelection( + { + ...clientSettings, + ...settings, + ...resolveModelPreferences(settings, clientSettings), + }, + providers, + selection, + ) + : null, + }; + }); + return selections.some((selection) => !Equal.equals(selection, selections[0])); +} + export function getCustomModelOptionsByInstance( settings: UnifiedSettings, providers: ReadonlyArray, diff --git a/apps/web/src/providerInstances.test.ts b/apps/web/src/providerInstances.test.ts index 8ea0102bd9495..c44c7d53316ab 100644 --- a/apps/web/src/providerInstances.test.ts +++ b/apps/web/src/providerInstances.test.ts @@ -8,6 +8,7 @@ import { import { describe, expect, it } from "vite-plus/test"; import { applyProviderInstanceSettings, + brandProviderInstanceEntries, deriveProviderEntriesByEnvironment, deriveProviderInstanceEntries, getDefaultProviderInstanceModel, @@ -254,6 +255,32 @@ describe("deriveProviderEntriesByEnvironment", () => { }); }); +describe("brandProviderInstanceEntries", () => { + it("keeps an instance a project turns on as a sibling for the instance badge", () => { + const codex = ProviderDriverKind.make("codex"); + const settings = { + providerInstances: { + [ProviderInstanceId.make("codex_work")]: { driver: codex, enabled: false }, + }, + projectSettingsOverrides: { + [ProjectId.make("project-work")]: { + providerInstances: { [ProviderInstanceId.make("codex_work")]: { enabled: true } }, + }, + }, + }; + const entries = brandProviderInstanceEntries( + deriveProviderInstanceEntries([ + provider({ provider: codex, instanceId: "codex" }), + provider({ provider: codex, instanceId: "codex_work" }), + ]), + settings, + ); + const personal = entries.find((entry) => entry.instanceId === "codex"); + + expect(personal && shouldShowInstanceBadge(personal, entries)).toBe(true); + }); +}); + describe("resolveSelectableProviderInstance", () => { it("falls back to the first enabled and available instance", () => { const disabled = ProviderInstanceId.make("codex"); diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index 0b0483d467ad8..4b0b4ae434f7c 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -107,10 +107,7 @@ export function deriveProviderEntriesByEnvironment( const byEnvironment = new Map>(); for (const [environmentId, providers, settings] of providersByEnvironment) { const derived = deriveProviderInstanceEntries(providers); - // The snapshot includes instances enabled by any project; machine settings alone do not. - const entries = settings - ? derived.map((entry) => applyProviderInstanceBranding(entry, settings)) - : derived; + const entries = settings ? brandProviderInstanceEntries(derived, settings) : derived; byEnvironment.set( environmentId, new Map(entries.map((entry) => [entry.instanceId as string, entry] as const)), @@ -119,6 +116,14 @@ export function deriveProviderEntriesByEnvironment( return byEnvironment; } +// The snapshot includes instances enabled by any project; machine settings alone do not. +export function brandProviderInstanceEntries( + entries: ReadonlyArray, + settings: Pick, +): ReadonlyArray { + return entries.map((entry) => applyProviderInstanceBranding(entry, settings)); +} + /** projectId applies project overrides; explicit null uses machine settings. */ export function applyProviderInstanceSettings( entries: ReadonlyArray, @@ -254,3 +259,19 @@ export function resolveDefaultProviderModelSelection( const model = getDefaultProviderInstanceModel(providers, instanceId); return model ? { instanceId, model } : null; } + +export function resolveProjectDefaultProviderModelSelection( + providers: ReadonlyArray, + settings: ServerSettings, + projectId: ProjectId | null, +): ModelSelection | null { + const entries = providerInstanceEntriesFor(providers, settings, projectId); + // Matches resolveComposerProviderSelection: the first driver group wins before any other. + const entry = + resolveSelectableProviderInstanceEntry( + entries.filter((candidate) => candidate.driverKind === entries[0]?.driverKind), + undefined, + ) ?? resolveSelectableProviderInstanceEntry(entries, undefined); + const model = entry ? getDefaultProviderInstanceModel(providers, entry.instanceId) : undefined; + return entry && model ? { instanceId: entry.instanceId, model } : null; +} diff --git a/apps/web/src/state/environments.ts b/apps/web/src/state/environments.ts index 1719e00f38395..f5ddb556c783b 100644 --- a/apps/web/src/state/environments.ts +++ b/apps/web/src/state/environments.ts @@ -98,3 +98,7 @@ export function useEnvironmentMachines() { export function useConnectedEnvironmentIds() { return useAtomValue(environmentSummaries.connectedEnvironmentIdsAtom); } + +export function useEnvironmentConnectionSummaries() { + return useAtomValue(environmentSummaries.environmentsAtom); +} diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index c7919d658ccf6..9d7aae58033f1 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -1,3 +1,4 @@ +import { createChildThreadApprovalsAtom } from "@t3tools/client-runtime/state/thread-requests"; import { useAtomValue } from "@effect/atom-react"; import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections"; import { arrayElementsEqual } from "@t3tools/client-runtime/state/entities"; @@ -39,6 +40,10 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, }); +export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ + childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, + pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom, +}); const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe( Atom.withLabel("web-environment-thread:empty"), diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index f6df5912ecdd1..dafb07f354437 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -187,6 +187,25 @@ describe("extractTerminalLinks", () => { ]); }); + it.each([ + "connected to redis://127.0.0.1:6379/0", + "connected to postgres://localhost:5432/app", + "uploaded s3://bucket/reports/today.csv", + " at main (file:///Users/jane/app/src/index.mjs:3:7)", + "+redis://localhost:6379/0", + "-redis://localhost:6379/0", + ])("does not turn part of a non-web URL into an editor link: %s", (line) => { + expect(extractTerminalLinks(line)).toEqual([]); + }); + + it("keeps file links beside a non-web URL", () => { + const line = "src/db.ts:4 redis://localhost:6379/0 C:/app/src/db.ts:9"; + expect(extractTerminalLinks(line)).toEqual([ + { kind: "path", text: "src/db.ts:4", start: 0, end: 11 }, + { kind: "path", text: "C:/app/src/db.ts:9", start: 37, end: 55 }, + ]); + }); + it("keeps a question mark inside a filesystem path", () => { const path = "/tmp/report?draft"; expect(extractTerminalLinks(`wrote ${path}`)).toEqual([ diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index 1c078d86cd20f..68bd4c8d5a835 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -41,6 +41,9 @@ const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/; // A question mark is legal in filenames; only exclude query-bearing request targets. const REQUEST_ROUTE_PATTERN = /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g; +// The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives, +// a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix. +const SCHEME_URL_PATTERN = /(?]+/gu; function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string { let output = value.replace( @@ -110,10 +113,10 @@ export function extractTerminalLinks(line: string): TerminalLinkMatch[] { const promptMatches: TerminalLinkMatch[] = promptPath ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }] : []; - const requestRoutes = Array.from(line.matchAll(REQUEST_ROUTE_PATTERN), (match) => ({ - start: match.index, - end: match.index + match[0].length, - })); + const nonPathRanges = Array.from( + [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)], + (match) => ({ start: match.index, end: match.index + match[0].length }), + ); const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches); const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [ ...promptMatches, @@ -126,7 +129,7 @@ export function extractTerminalLinks(line: string): TerminalLinkMatch[] { ]); return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches] .filter( - (match) => match.kind === "url" || !requestRoutes.some((route) => overlaps(match, route)), + (match) => match.kind === "url" || !nonPathRanges.some((range) => overlaps(match, range)), ) .toSorted((a, b) => a.start - b.start); } diff --git a/apps/web/src/terminal/ghostty/core.ts b/apps/web/src/terminal/ghostty/core.ts index dcae81b4fb9ff..b8ca5a624636f 100644 --- a/apps/web/src/terminal/ghostty/core.ts +++ b/apps/web/src/terminal/ghostty/core.ts @@ -177,15 +177,19 @@ function sameColor(left: GhosttyColor, right: GhosttyColor): boolean { } /** Bounds String.fromCodePoint arguments for cells with enormous combining-mark sequences. */ -export function ghosttyCellText(codepointView: DataView, graphemeLength: number): string { - if (graphemeLength === 1) return String.fromCodePoint(codepointView.getUint32(0, true)); +export function ghosttyCellText( + codepointView: DataView, + graphemeLength: number, + byteOffset = 0, +): string { + if (graphemeLength === 1) return String.fromCodePoint(codepointView.getUint32(byteOffset, true)); const CHUNK_SIZE = 4_096; let text = ""; for (let start = 0; start < graphemeLength; start += CHUNK_SIZE) { const count = Math.min(CHUNK_SIZE, graphemeLength - start); const codes = new Array(count); for (let index = 0; index < count; index += 1) { - codes[index] = codepointView.getUint32((start + index) * 4, true); + codes[index] = codepointView.getUint32(byteOffset + (start + index) * 4, true); } text += String.fromCodePoint(...codes); } @@ -853,12 +857,12 @@ export class GhosttyTerminalCore { if (rowDirty) { this.rows[rowIndex] = this.readRow(iterator, cols, foreground, background); dirtyRows.add(rowIndex); - this.runtime.bytes(this.scratch, 1)[0] = 0; + this.runtime.memoryBytes()[this.scratch] = 0; this.runtime.call("ghostty_render_state_row_set", iterator, 0, this.scratch); } rowIndex += 1; } - this.runtime.view(this.scratch, 4).setUint32(0, 0, true); + this.runtime.memoryDataView().setUint32(this.scratch, 0, true); this.runtime.call("ghostty_render_state_set", this.renderState, 0, this.scratch); } @@ -1009,19 +1013,19 @@ export class GhosttyTerminalCore { "ghostty_render_state_row_get(raw)", this.runtime.call("ghostty_render_state_row_get", iterator, ROW_DATA.raw, this.scratch), ); - const rawRow = this.runtime.view(this.scratch, 8).getBigUint64(0, true); - this.runtime.bytes(this.scratch + 8, 1)[0] = 0; + const rawRow = this.runtime.memoryDataView().getBigUint64(this.scratch, true); + this.runtime.memoryBytes()[this.scratch + 8] = 0; this.assertSuccess( "ghostty_row_get(wrap continuation)", this.runtime.call("ghostty_row_get", rawRow, 2, this.scratch + 8), ); - const isWrapContinuation = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0; - this.runtime.bytes(this.scratch + 8, 1)[0] = 0; + const isWrapContinuation = this.runtime.memoryBytes()[this.scratch + 8] !== 0; + this.runtime.memoryBytes()[this.scratch + 8] = 0; this.assertSuccess( "ghostty_row_get(wrap)", this.runtime.call("ghostty_row_get", rawRow, 1, this.scratch + 8), ); - const wrapsToNext = this.runtime.bytes(this.scratch + 8, 1)[0] !== 0; + const wrapsToNext = this.runtime.memoryBytes()[this.scratch + 8] !== 0; this.assertSuccess( "ghostty_render_state_row_get(cells)", @@ -1034,15 +1038,13 @@ export class GhosttyTerminalCore { ); const cellsIterator = this.runtime.readPointer(this.rowCellsSlot); const { size: styleSize, fields: styleFields } = this.runtime.layout("GhosttyStyle"); + const cellsNext = this.runtime.fn("ghostty_render_state_row_cells_next"); + const cellsGetMulti = this.runtime.fn("ghostty_render_state_row_cells_get_multi"); const cells: GhosttyCell[] = []; - while ( - cells.length < cols && - this.runtime.call("ghostty_render_state_row_cells_next", cellsIterator) !== 0 - ) { - this.runtime.bytes(this.style, styleSize).fill(0); + while (cells.length < cols && cellsNext(cellsIterator) !== 0) { + this.runtime.memoryBytes().fill(0, this.style, this.style + styleSize); this.runtime.setField(this.style, "GhosttyStyle", "size", styleSize); - const result = this.runtime.call( - "ghostty_render_state_row_cells_get_multi", + const result = cellsGetMulti( cellsIterator, 5, this.cellQuery + CELL_QUERY.keys, @@ -1081,8 +1083,7 @@ export class GhosttyTerminalCore { ) === GHOSTTY_SUCCESS ) { // Byte allocations need not be 4-byte aligned; use DataView instead of Uint32Array. - const codepointView = this.runtime.view(this.graphemes, bufferSize); - text = ghosttyCellText(codepointView, graphemeLength); + text = ghosttyCellText(this.runtime.memoryDataView(), graphemeLength, this.graphemes); } } let wide = 0; @@ -1097,13 +1098,13 @@ export class GhosttyTerminalCore { this.scratch, ), ); - const rawCell = this.runtime.view(this.scratch, 8).getBigUint64(0, true); - this.runtime.view(this.scratch + 8, 4).setUint32(0, 0, true); + const rawCell = this.runtime.memoryDataView().getBigUint64(this.scratch, true); + this.runtime.memoryDataView().setUint32(this.scratch + 8, 0, true); this.assertSuccess( "ghostty_cell_get(wide)", this.runtime.call("ghostty_cell_get", rawCell, RAW_CELL_DATA.wide, this.scratch + 8), ); - wide = this.runtime.view(this.scratch + 8, 4).getUint32(0, true); + wide = this.runtime.memoryDataView().getUint32(this.scratch + 8, true); } // Read the style after allocation and ABI calls, which can grow WASM memory. const styleView = this.runtime.memoryDataView(); @@ -1228,34 +1229,34 @@ export class GhosttyTerminalCore { } private getU16(data: number): number { - this.runtime.bytes(this.scratch, 2).fill(0); + this.runtime.memoryDataView().setUint16(this.scratch, 0, true); this.assertSuccess( "ghostty_render_state_get", this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch), ); - return this.runtime.view(this.scratch, 2).getUint16(0, true); + return this.runtime.memoryDataView().getUint16(this.scratch, true); } private getU32(data: number): number { - this.runtime.bytes(this.scratch, 4).fill(0); + this.runtime.memoryDataView().setUint32(this.scratch, 0, true); this.assertSuccess( "ghostty_render_state_get", this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch), ); - return this.runtime.view(this.scratch, 4).getUint32(0, true); + return this.runtime.memoryDataView().getUint32(this.scratch, true); } private getBool(data: number): boolean { - this.runtime.bytes(this.scratch, 1)[0] = 0; + this.runtime.memoryBytes()[this.scratch] = 0; this.assertSuccess( "ghostty_render_state_get", this.runtime.call("ghostty_render_state_get", this.renderState, data, this.scratch), ); - return this.runtime.bytes(this.scratch, 1)[0] !== 0; + return this.runtime.memoryBytes()[this.scratch] !== 0; } private getColor(data: number, fallback: GhosttyColor): GhosttyColor { - this.runtime.bytes(this.scratch, 3).fill(0); + this.runtime.memoryBytes().fill(0, this.scratch, this.scratch + 3); const result = this.runtime.call( "ghostty_render_state_get", this.renderState, @@ -1266,15 +1267,15 @@ export class GhosttyTerminalCore { } private getRowBool(iterator: number, data: number): boolean { - this.runtime.bytes(this.scratch, 1)[0] = 0; + this.runtime.memoryBytes()[this.scratch] = 0; return ( this.runtime.call("ghostty_render_state_row_get", iterator, data, this.scratch) === - GHOSTTY_SUCCESS && this.runtime.bytes(this.scratch, 1)[0] !== 0 + GHOSTTY_SUCCESS && this.runtime.memoryBytes()[this.scratch] !== 0 ); } private getCellColor(iterator: number, data: number, fallback: GhosttyColor): GhosttyColor { - this.runtime.bytes(this.scratch, 3).fill(0); + this.runtime.memoryBytes().fill(0, this.scratch, this.scratch + 3); const result = this.runtime.call( "ghostty_render_state_row_cells_get", iterator, diff --git a/apps/web/src/terminal/ghostty/runtime.ts b/apps/web/src/terminal/ghostty/runtime.ts index 22c9c13e50722..762fb0f6ef13d 100644 --- a/apps/web/src/terminal/ghostty/runtime.ts +++ b/apps/web/src/terminal/ghostty/runtime.ts @@ -24,6 +24,7 @@ export class GhosttyRuntime { readonly layouts: TypeLayouts; private readonly exports: WebAssembly.Exports; private memoryView: DataView; + private memoryU8: Uint8Array; private readonly ptyWriters = new Map void>(); private nextPtyWriterId = 1; private writePtyFunctionIndex = 0; @@ -36,6 +37,7 @@ export class GhosttyRuntime { } this.memory = memory; this.memoryView = new DataView(memory.buffer); + this.memoryU8 = new Uint8Array(memory.buffer); const jsonPointer = this.call("ghostty_type_json"); const bytes = new Uint8Array(memory.buffer); let end = jsonPointer; @@ -68,11 +70,15 @@ export class GhosttyRuntime { } call(name: string, ...args: Array): number { + return this.fn(name)(...args); + } + + fn(name: string): WasmFunction { const fn = this.exports[name]; if (typeof fn !== "function") { throw new Error(`libghostty-vt export is unavailable: ${name}`); } - return (fn as WasmFunction)(...args); + return fn as WasmFunction; } layout(name: string): TypeLayout { @@ -126,18 +132,29 @@ export class GhosttyRuntime { } view(pointer: number, size?: number): DataView { - return new DataView(this.memory.buffer, pointer, size); + return new DataView(this.memoryDataView().buffer, pointer, size); } bytes(pointer: number, size: number): Uint8Array { - return new Uint8Array(this.memory.buffer, pointer, size); + return new Uint8Array(this.memoryDataView().buffer, pointer, size); } memoryDataView(): DataView { - if (this.memoryView.buffer !== this.memory.buffer) { + this.refreshMemoryViews(); + return this.memoryView; + } + + memoryBytes(): Uint8Array { + this.refreshMemoryViews(); + return this.memoryU8; + } + + private refreshMemoryViews(): void { + // Growing memory detaches the old buffer. Reading `memory.buffer` costs far more than this check. + if (this.memoryU8.byteLength === 0) { this.memoryView = new DataView(this.memory.buffer); + this.memoryU8 = new Uint8Array(this.memory.buffer); } - return this.memoryView; } setField(pointer: number, structName: string, fieldName: string, value: number): void { diff --git a/apps/web/src/textDirection.test.ts b/apps/web/src/textDirection.test.ts index a104133799c52..3cc618e525f07 100644 --- a/apps/web/src/textDirection.test.ts +++ b/apps/web/src/textDirection.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { textDirection } from "./textDirection"; +import { markdownProseDirection, textDirection } from "./textDirection"; describe("textDirection", () => { it.each([ @@ -24,3 +24,39 @@ describe("textDirection", () => { expect(textDirection("42 — 7 ✓")).toBeUndefined(); }); }); + +describe("markdownProseDirection", () => { + it.each([ + [ + "Hebrew around a code block", + "תתקן את זה:\n```ts\nexport function useCheckout(props: CheckoutProps) {\n return props.items.length;\n}\n```\nותריץ שוב", + "rtl", + ], + ["Hebrew around inline code", "לערוך את `apps/web/src/chat.tsx` או להשאיר `useMemo`?", "rtl"], + ["Hebrew around double-backtick code", "תבדוק ``const a = `b c d e` + f`` עכשיו", "rtl"], + [ + "Hebrew after a four-backtick fence", + "````md\none two three four five six\n````\nשלום עולם, זה עובד", + "rtl", + ], + [ + "Hebrew after a tilde fence", + "~~~\nnpm run build --filter web --force\n~~~\nזה נכשל אצלי", + "rtl", + ], + [ + "Hebrew before an unclosed fence", + "שלום, הנה השגיאה:\n```\nError: cannot find module react dom client", + "rtl", + ], + ["Hebrew around a URL", "ראה https://github.com/pingdotgg/t3code/pull/24050 לפני", "rtl"], + ["English around inline code", "Should I edit `useMemo` or keep it?", "ltr"], + ["English quoting one Hebrew word", "Please check the שלום label before the release", "ltr"], + ])("reads %s", (_, markdown, direction) => { + expect(markdownProseDirection(markdown)).toBe(direction); + }); + + it("leaves markdown without prose letters to its surroundings", () => { + expect(markdownProseDirection("```\nconst a = 1;\n```")).toBeUndefined(); + }); +}); diff --git a/apps/web/src/textDirection.ts b/apps/web/src/textDirection.ts index 9f0adedd30e3c..8b1a9e8c2a357 100644 --- a/apps/web/src/textDirection.ts +++ b/apps/web/src/textDirection.ts @@ -1,27 +1 @@ -export type TextDirection = "ltr" | "rtl"; - -// Hebrew through Arabic Extended-A, their presentation forms, and the -// supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; - -/** - * `dir="auto"` misreads Arabic prose that opens with an English term. - * Count words so mixed prose follows its main language; break ties with the first word. - */ -export function textDirection(text: string): TextDirection | undefined { - if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined; - let rtlWords = 0; - let ltrWords = 0; - let first: TextDirection | undefined; - for (const word of text.split(/\s+/)) { - const letter = LETTER.exec(word)?.[0]; - if (!letter) continue; - const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr"; - first ??= direction; - if (direction === "rtl") rtlWords += 1; - else ltrWords += 1; - } - if (rtlWords === ltrWords) return first; - return rtlWords > ltrWords ? "rtl" : "ltr"; -} +export * from "@t3tools/shared/textDirection"; diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.ts index dc27fed47e5c3..a1aae7ae276ba 100644 --- a/apps/web/src/themePalette.test.ts +++ b/apps/web/src/themePalette.test.ts @@ -60,6 +60,17 @@ function contrastRatio(first: string, second: string): number { } describe("theme files", () => { + it("gives non-Latin theme names distinct stable ids", () => { + const file = { + version: THEME_FILE_VERSION, + appearance: "dark", + colors: { canvas: "#101820" }, + }; + const night = parseThemeFile({ ...file, name: "夜" }); + expect(parseThemeFile({ ...file, name: "朝" }).id).not.toBe(night.id); + expect(parseThemeFile({ ...file, name: " 夜 " }).id).toBe(night.id); + }); + it("keeps built-in and standard search pairs readable and distinct from inline code", () => { const toOklab = converter("oklab"); const distance = (first: string, second: string) => { diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts index dd863acc6e2d3..2d46a05f17489 100644 --- a/apps/web/src/themePalette.ts +++ b/apps/web/src/themePalette.ts @@ -1220,13 +1220,20 @@ export function getThemePreferenceMode(theme: ThemePreference): ThemeAppearance } export function themeIdFromName(name: string): string { - const normalized = name - .trim() - .toLowerCase() + const label = name.trim().toLowerCase(); + const normalized = label .replace(/[^a-z0-9]+/g, "-") .replace(/^-+|-+$/g, "") .slice(0, 48); - return normalized || "custom-theme"; + if (normalized || !label) return normalized || "custom-theme"; + + // Names without ASCII letters or digits still need independent, stable ids. + let hash = 2_166_136_261; + for (let index = 0; index < label.length; index += 1) { + hash ^= label.charCodeAt(index); + hash = Math.imul(hash, 16_777_619); + } + return `theme-${(hash >>> 0).toString(36)}`; } export class ThemeLibraryStorageError extends Schema.TaggedError()( diff --git a/apps/web/src/vscodeThemeImport.test.ts b/apps/web/src/vscodeThemeImport.test.ts index 93792b815d852..f0172c2354d03 100644 --- a/apps/web/src/vscodeThemeImport.test.ts +++ b/apps/web/src/vscodeThemeImport.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test"; import { getThemeColorsForMode, + parseThemeFile, themeColorToHex, THEME_FILE_VERSION, toCanonicalThemeColor, @@ -9,6 +10,7 @@ import { import { isVsCodeThemeFile, pairVsCodeThemes, + parseThemeImport, parseVsCodeThemeFile, resolveThemeLabelCollisions, } from "./vscodeThemeImport"; @@ -63,6 +65,59 @@ const VSCODE_DARK = { tokenColors: [], }; +describe("theme import text", () => { + it("preserves conversion of ordinary VS Code JSON", () => { + expect(parseThemeImport(JSON.stringify(VSCODE_DARK))).toEqual( + parseVsCodeThemeFile(VSCODE_DARK), + ); + }); + + it.each([ + '{ // line comment\n "name": "Test", "colors": { "editor.background": "#002b36" } }', + '{ /* block comment */ "name": "Test", "colors": { "editor.background": "#002b36" } }', + '{ "name": "Test", "colors": { "editor.background": "#002b36", }, "tokenColors": [ { "scope": ["comment",], "settings": {}, }, ], }', + ])("imports VS Code JSONC without changing conversion: %s", (source) => { + const theme = parseThemeImport(source); + expect(theme.label).toBe("Test"); + expect(theme.appearance).toBe("dark"); + expect(asHex(theme.colors.canvas)).toBe("#002b36"); + }); + + it.each([ + "", + '{ "name": "Test", "colors": { "editor.background": "#002b36" }', + '{ "name": "Test" "colors": { "editor.background": "#002b36" } }', + '{ "name": "Test", "colors": { "editor.background": "#002b36" } } /* unterminated', + '{ "name": "Test", "colors": { "editor.background": "#002b36" } } extra', + ])("rejects malformed input rather than using parser recovery: %s", (source) => { + expect(() => parseThemeImport(source)).toThrow("That theme file is not valid JSON."); + }); + + it("preserves native T3 theme parsing and strict JSON syntax", () => { + const nativeTheme = { + version: THEME_FILE_VERSION, + name: "Native theme", + appearance: "dark", + colors: { canvas: "#002b36" }, + }; + const source = JSON.stringify(nativeTheme); + expect(parseThemeImport(source)).toEqual(parseThemeFile(nativeTheme)); + expect(() => parseThemeImport(source.replace("{", "{ /* native theme */"))).toThrow(); + expect(() => parseThemeImport(source.slice(0, -1) + ",}")).toThrow(); + }); + + it("still validates theme structure after parsing JSONC", () => { + expect(() => + parseThemeImport('{ /* not a theme */ "colors": { "editor.foreground": "#fff" } }'), + ).toThrow('no "editor.background"'); + expect(() => + parseThemeImport( + '{ "version": 1, "name": "Bad native", "appearance": "dark", "colors": { "unknown": "#fff" } }', + ), + ).toThrow('"unknown" is not a supported theme color role.'); + }); +}); + describe("VS Code theme import", () => { it("recognises workbench themes and rejects our own files", () => { expect(isVsCodeThemeFile(VSCODE_DARK)).toBe(true); diff --git a/apps/web/src/vscodeThemeImport.ts b/apps/web/src/vscodeThemeImport.ts index 57e3d245b212b..416351b16edfb 100644 --- a/apps/web/src/vscodeThemeImport.ts +++ b/apps/web/src/vscodeThemeImport.ts @@ -1,3 +1,5 @@ +import { parse, type ParseError } from "jsonc-parser"; + import { createVividThemeColors, getStandardThemeColors, @@ -133,6 +135,15 @@ export function isVsCodeThemeFile(value: unknown): boolean { return hasWorkbenchColors || Array.isArray(value.tokenColors); } +export function parseThemeImport(source: string): ThemeDefinition { + const errors: ParseError[] = []; + const value: unknown = parse(source, errors, { allowTrailingComma: true }); + if (errors.length > 0) throw new Error("That theme file is not valid JSON."); + return isVsCodeThemeFile(value) + ? parseVsCodeThemeFile(value) + : parseThemeFile(JSON.parse(source)); +} + function resolveAppearance(value: Record, canvas: VsCodeRgb): ThemeAppearance { const type = typeof value.type === "string" ? value.type.toLowerCase() : null; if (type === "light" || type === "hc-light") return "light"; diff --git a/docs/internals/coder-only.md b/docs/internals/coder-only.md index 3c0dc9f49327a..fb372b47a2828 100644 --- a/docs/internals/coder-only.md +++ b/docs/internals/coder-only.md @@ -710,7 +710,7 @@ checks that every name here still exists and that every modified upstream file i (`server/GitLabMediaFetch.ts`) reads with `glab api` in the minted `cwd` (no `--hostname`), buffering at most `GITLAB_MEDIA_MAX_BYTES`. The package also exports `server/GitLabCli`, which `ws.projects.test.ts` stubs. -- `GitLabCli.ts` fixes bugs still in upstream (checked against upstream `main` 15fe283272): merge +- `GitLabCli.ts` fixes bugs still in upstream (checked against upstream `main` 8760d063e9): merge requests between projects post to the source project with a numeric `target_project_id`; merge request URLs reach `glab` as `--repo … -- `. `glab auth status` lines with a token label or `glpat-` token are never surfaced; clones accept only GitLab URLs without credentials, @@ -787,7 +787,8 @@ checks that every name here still exists and that every modified upstream file i on a disconnect. `connection/registry.ts` starts every registered supervisor desired, applies every reconcile (no #26511 skip), carries no cached unsupported-host rejection, and has no `assertKnownAddress` or `knownAddressOnly`; `connection/resolver.ts` has no remote HTTP prepare - path. `state/shell.ts` treats every workspace as remote. + path. `state/shell.ts` treats every workspace as remote, so upstream's `shell.test.ts`, which tests + its primary-environment factory, is not carried. - client-runtime's `threadSnapshotHttp.ts`, `shellSnapshotHttp.ts`, and `threadHistoryHttp.ts` keep upstream's paths but load over helper stdio; shell snapshots use upstream's socket fallback. - client-runtime's `rpc/protocol.ts` builds its client from `CoderWsRpcGroup`, and `rpc/index.ts` @@ -948,6 +949,8 @@ checks that every name here still exists and that every modified upstream file i `environmentTransportLabel` names every workspace "Coder workspace", so `useEnvironmentTransportLabel` ignores the prepared connection; older links naming one checkout resolve to its group. +- `ProviderModelPicker.tsx` has no `ChatGptSharingControl`, inline or in the docked list footer + (subscription plans are out of scope). - Providers lists only the four drivers, without sign-in, setup, managed install, per-instance environment variables, ACP registry, or usage-limit sources; Source Control appends GitLab workspace status; update checks and the health interval do not mention model catalog updates. @@ -1039,11 +1042,12 @@ checks that every name here still exists and that every modified upstream file i with a branded exit code; `ProviderInstanceRegistry.test.ts` runs the Claude one-probe fallback against the CLI `query`; `ProviderRegistry.test.ts` runs without the Antigravity and OpenCode layers; `SourceControlProviderRegistry.test.ts`, `SourceControlRepositoryService.test.ts`, and - `RepositoryIdentityResolver.test.ts` run upstream's cases on GitLab remotes with the fork's mocks; + `RepositoryIdentityResolver.test.ts` run upstream's cases on GitLab remotes with the fork's mocks + (the resolver's folder checks, #27980, read a FileSystem that reports every path as a folder); `PullRequestService.test.ts` passes branded GitLab kinds; `chatCanvasLayout.test.ts` and `canvasStore.test.ts` carry no preview cases; the ACP Registry replay harness - (`AcpRegistryAdapterV2.testkit.ts`, `AcpAdapterV2.testkit.ts`) runs without registry, Devin, and - session-management cases, plus a Coder test that the bridge command reaches the prompt; + (`AcpRegistryAdapterV2.testkit.ts`, `AcpAdapterV2.testkit.ts`) runs without registry, Devin, + Copilot lost-session (#26651), and session-management cases, plus a Coder test that the bridge command reaches the prompt; `AgentScope.test.ts` drops the launcher check (`agentScopeLauncherScript` is cut); `GitLabPullRequestCli.legacy.test.ts` expects `DIFF_MAX_OUTPUT_BYTES`; `ProviderReplayFixtures.ts` lists only the carried drivers. @@ -1057,7 +1061,8 @@ checks that every name here still exists and that every modified upstream file i `CommandPalette.composition` mocks `useCoder` and picks the workspace first, `StorageSettings` keys on the saved-image-artifacts title, `useComposerContextImport` drops linked environments, images, and annotations, `FilePreviewPanel` has no remote-open mock, `PullRequestMarkdown` runs on - the GitLab-only registry, `ProjectSettingsPanel` keeps `projects.getConfig` pending, and + the GitLab-only registry, `ProjectSettingsPanel` keeps `projects.getConfig` pending and drops the + fallback-model search target, `ExpandedImageDialog` drops the SnapShot accessibility case, and `ProviderSettingsForm`, `ProviderModelPicker.composition`, and `ReopenClosedViewShortcut` drop secret-source, provider, and preview cases. The fork-only `hooks/useThreadActionMenu.test.tsx` keeps upstream's deleted hook test. @@ -1090,7 +1095,8 @@ them, the file is named here. `lastEventLoopStall`), usage page or dashboard (`shared/usageLimits.ts`, provider-core and provider-pi `usage.ts`; `ProviderDriver.usage` is `never`), the thread details usage-limit rows (`ThreadDetailsUsage`'s limit windows), `useUsageLimitsPanel`, or upstream's out-of-usage fallback (#26164; - `fallbackModelSelection` stays in the schema only). Without the usage page, `timestampFormat.ts` + `fallbackModelSelection` stays in the schema only; `ProjectDefaultsSettings.tsx` has no fallback + row or effort picker and `settingsSearch.ts` no "Fallback model" item). Without the usage page, `timestampFormat.ts` has no `resolveHour12`. - **Server self-update and CLI.** No npm release check (`cloud/npmRelease.ts`), "Update everything", update tracks, `t3 doctor` storage status (`DatabaseStorageNotice`, client-runtime's @@ -1155,7 +1161,8 @@ them, the file is named here. `artifacts` are not shown, as on upstream. - Shared helpers only cut surfaces used: `shared/projectFavicon.ts` keeps `PROJECT_FAVICON_EXTENSIONS` private, `shared/t3ProjectFile.ts` drops - `buildT3ProjectFileJsonSchema`, shared `AgentScope.ts` drops `agentScopeLauncherScript`, and + `buildT3ProjectFileJsonSchema`, shared `AgentScope.ts` drops `agentScopeLauncherScript`, shared + `shell.ts` drops the desktop's `applyShellEnvironment` (#28556), and `PullRequestsPage.tsx` drops its preview-session placeholders. ## Distribution diff --git a/docs/internals/web-ui.md b/docs/internals/web-ui.md index 13b7d9df99fd0..c54a3802be941 100644 --- a/docs/internals/web-ui.md +++ b/docs/internals/web-ui.md @@ -31,8 +31,8 @@ The composer banners are the reference. renders `Button`. - [`ComposerBannerStack.tsx`](../../apps/web/src/components/chat/ComposerBannerStack.tsx) composes the slots and owns only stack behavior: priority, expand and collapse, dismiss transitions. -- Consumers are a few lines of slots, and the slots carry the styling: - [`ComposerActivityStatus.tsx`](../../apps/web/src/components/chat/ComposerActivityStatus.tsx). +- Consumers are a few lines of slots, and the slots carry the banner styling: + [`ComposerPlanFollowUpBanner.tsx`](../../apps/web/src/components/chat/ComposerPlanFollowUpBanner.tsx). Build new UI the same way. Compose or extend a component instead of copying its markup and classes. When a call site repeats a treatment another one already uses, make it a variant or a slot on the diff --git a/docs/user/composer.md b/docs/user/composer.md index 9b3ae7437cca1..d6c3e438599a7 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -81,7 +81,8 @@ Each shows its text and any attached images. **Send now** sends a message right running turn if there is one. You can also edit or remove it. If you stop the agent or the workspace helper restarts, queued messages keep their order and are -held. Press **Resume** in an empty composer to continue. Sending a new message also resumes the +held. Press **Resume** in an empty composer to continue. **Resume** also continues a stopped run or +one that hit a usage limit, even with nothing queued. Sending a new message also resumes the queue, unless it steers a turn that is already running. You can edit or remove held messages without starting them. @@ -220,15 +221,17 @@ the provider’s own configuration in the workspace. ## Context meter -The context meter stays visible in the composer footer and shows how much of the selected -provider's context window the conversation uses. As Codex or Claude threads grow old and large, +Turn on **Settings → Labs → Legacy → Context window indicator (legacy)** to see context usage. The +meter is off by default and appears in the composer footer once the provider reports usage; it +shows how much of the selected provider's context window the conversation uses. As Codex or Claude threads grow old and large, T3 Coder offers to compact the conversation into a summary before you continue; you can also start compaction yourself from the meter. Compaction runs through the workspace provider session, summarizes history without changing the model's context window, and remains visible in the conversation even when it is the only activity in that turn. Compacting from the context meter preserves the current draft and its images. You can also send -`/compact` in an existing conversation when the provider supports it. +`/compact` in an existing conversation when the provider supports it, even with the context meter +turned off. **Compact idle threads** in **Settings > General** controls idle Claude threads over 200,000 tokens. Each Claude provider's settings can override it: diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index 23ee819faa9b3..e072954c756d6 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -11,6 +11,9 @@ thread keeps that thread's mode. Other new threads use the default from **Settin threads → Permissions** (**Full access** at first), which a project can override, unless you pick something else before sending. +Subagent approval requests appear in the parent conversation with the subagent's name, so you can +respond without switching threads. + ## The modes **Supervised** asks before commands and file changes. Use it when you want to inspect actions before @@ -26,7 +29,9 @@ Provider policy decides the exact approval boundary. a question. Claude can still ask in **Full access** when its settings disable bypass permissions or require -approval for an action. +approval for an action. Dangerous-removal safety checks in bypass mode reject the command with +the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it +continues without the removal and tells you what it skipped. While a Claude approval is pending, type a text reply to decline that request and give feedback directly to the agent that asked, including a subagent. Other pending requests stay unanswered. diff --git a/docs/user/providers-pi.md b/docs/user/providers-pi.md index c594d8e4fa40c..4eac4d4097bd4 100644 --- a/docs/user/providers-pi.md +++ b/docs/user/providers-pi.md @@ -77,5 +77,6 @@ threads. environment, including `PI_CODING_AGENT_DIR` if set. Trust the folder or its parent with `/trust`, then start a new thread using that same worktree. Launch arguments with `--no-approve` keep project files off without the notice. -- The context meter appears once Pi reports usage for the thread. Some model providers only - report usage when a response completes, so the meter can wait for the first reply. +- The context meter is off by default; see [commands and skills](./composer.md#commands-and-skills) + to enable it on web and desktop. It appears once Pi reports usage for the thread. Some model + providers only report usage when a response completes, so the meter can wait for the first reply. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 712a85f43a9cb..bce036e2a0576 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -212,8 +212,9 @@ from its context menu. **Thread ID** copies the bare ID for scripts. See **Limited** means the provider stopped on a usage or rate limit. The conversation keeps the provider's explanation. Retry after the limit resets, or switch to another provider instance. -Press **Resume** in an empty composer to continue a limited -or interrupted turn manually. +Press **Resume** in an empty composer to continue a limited or interrupted turn +manually. Do this when the provider reports no reset time, because nothing +continues the turn on its own. Queued messages stay saved while the limit blocks the thread. They run after the continuation finishes. If the queue was held by a restart, resume it then. diff --git a/packages/client-runtime/src/modelTraits.ts b/packages/client-runtime/src/modelTraits.ts index 23ada4ea11c46..b05f9226defb3 100644 --- a/packages/client-runtime/src/modelTraits.ts +++ b/packages/client-runtime/src/modelTraits.ts @@ -11,11 +11,25 @@ import { } from "@t3tools/shared/model"; import { REASONING_EFFORT_OPTION_IDS } from "./state/threadExecution.ts"; -export const REASONING_SELECT_DESCRIPTOR_IDS: ReadonlySet = new Set([ +const REASONING_DESCRIPTOR_IDS: ReadonlySet = new Set([ ...REASONING_EFFORT_OPTION_IDS, "thinking", ]); +/** The model's reasoning control: a known effort id, or a select its agent marked as reasoning. */ +export function isReasoningControl(descriptor: ProviderOptionDescriptor): boolean { + return ( + (descriptor.type === "select" && descriptor.role === "reasoning") || + REASONING_DESCRIPTOR_IDS.has(descriptor.id) + ); +} + +export function isReasoningSelect( + descriptor: ProviderOptionDescriptor, +): descriptor is Extract { + return descriptor.type === "select" && isReasoningControl(descriptor); +} + export function replaceDescriptorCurrentValue( descriptors: ReadonlyArray, descriptorId: string, @@ -106,8 +120,6 @@ export function buildTraitsTriggerDisplay(input: { label: string; /** "Fast" or "Ultrafast" when a speed option is on. */ speedLabel: string | null; - /** Labels other than reasoning and speed, such as context window or thinking. */ - otherLabels: ReadonlyArray; } { let fastModeFallbackLabel: string | null = null; let speedLabel: string | null = null; @@ -154,20 +166,15 @@ export function buildTraitsTriggerDisplay(input: { input.reportedModelSelection, ); if (typeof label === "string" && label.length > 0) { - if ( - reasoningLabelIndex === -1 && - descriptor.type === "select" && - REASONING_SELECT_DESCRIPTOR_IDS.has(descriptor.id) - ) { + if (reasoningLabelIndex === -1 && isReasoningSelect(descriptor)) { reasoningLabelIndex = labels.length; } labels.push(label); } } - const otherLabels = labels.filter((_, index) => index !== reasoningLabelIndex); if (labels.length === 0 && fastModeFallbackLabel !== null) { - return { label: fastModeFallbackLabel, speedLabel, otherLabels }; + return { label: fastModeFallbackLabel, speedLabel }; } if (speedLabel) { if (reasoningLabelIndex >= 0) { @@ -176,5 +183,5 @@ export function buildTraitsTriggerDisplay(input: { labels.push(speedLabel); } } - return { label: labels.join(" · "), speedLabel, otherLabels }; + return { label: labels.join(" · "), speedLabel }; } diff --git a/packages/client-runtime/src/providerSkills.test.ts b/packages/client-runtime/src/providerSkills.test.ts index ccc5bf6ef2807..bd5729656c841 100644 --- a/packages/client-runtime/src/providerSkills.test.ts +++ b/packages/client-runtime/src/providerSkills.test.ts @@ -12,6 +12,7 @@ import { createProviderWorkspaceSnapshotRefreshAtomFamily, getProviderSkillsForSlashMenu, hasCompleteProviderWorkspaceSnapshot, + isProviderWorkspaceSnapshotScanning, resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "./providerSkills.ts"; @@ -298,6 +299,53 @@ describe("provider workspace snapshot refresh atom", () => { unmount(); }); + it("reports skills loading while a missing snapshot is scanned, until it arrives", async () => { + vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") }); + const scanned = withSnapshot("2026-01-01T00:00:00.000Z"); + const { registry, atom, providersAtom, unmount } = setup(noSnapshot, [() => scanned]); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(true); + registry.set(providersAtom, scanned); + await vi.advanceTimersByTimeAsync(0); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false); + unmount(); + }); + + it("stops reporting skills loading when the scan fails", async () => { + vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") }); + const { registry, atom, unmount } = setup(noSnapshot); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(true); + await vi.advanceTimersByTimeAsync(0); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false); + unmount(); + }); + + it("keeps reporting skills loading while the scan returns a pending snapshot", async () => { + vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") }); + const pending = withSnapshot("2026-01-01T00:00:00.000Z", true); + const { registry, atom, providersAtom, unmount } = setup(pending, [() => pending]); + await vi.advanceTimersByTimeAsync(0); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(true); + registry.set(providersAtom, withSnapshot("2026-01-01T00:00:00.000Z")); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false); + unmount(); + }); + + it("stops reporting skills loading once a pending snapshot exhausts its retries", async () => { + vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") }); + const { registry, atom, run, unmount } = setup(withSnapshot("2026-01-01T00:00:00.000Z", true)); + await vi.advanceTimersByTimeAsync(60_000); + expect(run).toHaveBeenCalledTimes(3); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false); + unmount(); + }); + + it("does not report skills loading for a current snapshot", () => { + vi.useFakeTimers({ now: Date.parse("2026-01-01T00:01:00.000Z") }); + const { registry, atom, unmount } = setup(withSnapshot("2026-01-01T00:00:00.000Z")); + expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false); + unmount(); + }); + it("does not retry on a timer when the failed scan left no pending snapshot", async () => { vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") }); const { registry, atom, run, unmount } = setup(noSnapshot); diff --git a/packages/client-runtime/src/providerSkills.ts b/packages/client-runtime/src/providerSkills.ts index 63ded7a47dc5c..2598c895c5053 100644 --- a/packages/client-runtime/src/providerSkills.ts +++ b/packages/client-runtime/src/providerSkills.ts @@ -136,7 +136,7 @@ const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000; // A cwd that never scans, such as a deleted worktree, would otherwise retry forever. const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3; -interface ProviderWorkspaceSnapshotRefreshState { +export interface ProviderWorkspaceSnapshotRefreshState { /** * When the last scan was requested. A request inside the TTL is not * repeated, so a client clock ahead of the server's cannot loop rescans. @@ -147,6 +147,8 @@ interface ProviderWorkspaceSnapshotRefreshState { /** Failed scans within the current request TTL. */ readonly failedAttempts: number; readonly hadSnapshot: boolean; + /** The server published a partial snapshot and is still discovering. */ + readonly snapshotPending: boolean; } const initialProviderWorkspaceSnapshotRefreshState: ProviderWorkspaceSnapshotRefreshState = { @@ -154,6 +156,7 @@ const initialProviderWorkspaceSnapshotRefreshState: ProviderWorkspaceSnapshotRef retryNotBefore: null, failedAttempts: 0, hadSnapshot: false, + snapshotPending: false, }; /** @@ -172,6 +175,8 @@ function planProviderWorkspaceSnapshotRefresh( readonly recheckAt: number | null; } { const hasSnapshot = hasCompleteProviderWorkspaceSnapshot(provider, cwd); + const pending = + (provider && resolveProviderWorkspaceSnapshot(provider, cwd)?.slashCommandsPending) === true; // Losing a snapshot (the server dropped it) lifts both the TTL and the retry // cooldown so the scan happens at once. const lost = previous.hadSnapshot && !hasSnapshot; @@ -188,6 +193,7 @@ function planProviderWorkspaceSnapshotRefresh( ? 0 : previous.failedAttempts, hadSnapshot: hasSnapshot, + snapshotPending: pending, }; const refresh = (requestedAt === null || now - requestedAt >= PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS) && @@ -196,8 +202,6 @@ function planProviderWorkspaceSnapshotRefresh( if (refresh) { return { state: { ...state, requestedAt: now }, refresh: true, recheckAt: null }; } - const pending = - (provider && resolveProviderWorkspaceSnapshot(provider, cwd)?.slashCommandsPending) === true; return { state, refresh: false, recheckAt: pending ? retryNotBefore : null }; } @@ -223,6 +227,23 @@ function failProviderWorkspaceSnapshotRefresh( }; } +/** + * A scan is in flight, or the server is still discovering, for a cwd without a + * complete snapshot, so its skills and commands may still arrive. A failed scan + * clears `requestedAt`, and exhausted attempts end it, so this cannot stay true + * for a scan that will not finish. + */ +export function isProviderWorkspaceSnapshotScanning( + state: ProviderWorkspaceSnapshotRefreshState | undefined, +): boolean { + return ( + state !== undefined && + (state.requestedAt !== null || state.snapshotPending) && + !state.hadSnapshot && + state.failedAttempts < WORKSPACE_SNAPSHOT_MAX_ATTEMPTS + ); +} + type WorkspaceSnapshotStatus = "absent" | "pending" | "complete"; function resolveWorkspaceSnapshotStatus( @@ -330,6 +351,8 @@ export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: { ).pipe(Atom.withLabel(`provider-workspace-snapshot-refresh:${key}`)); return refreshAtom; }); - return (target: ProviderWorkspaceSnapshotRefreshTarget): Atom.Atom => + return ( + target: ProviderWorkspaceSnapshotRefreshTarget, + ): Atom.Atom => family({ environmentId: target.environmentId, instanceId: target.instanceId, cwd: target.cwd }); } diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.ts index abc16b9a7df67..6cc9bc91595da 100644 --- a/packages/client-runtime/src/state/entities.test.ts +++ b/packages/client-runtime/src/state/entities.test.ts @@ -22,7 +22,7 @@ import { canSnooze, effectiveSnoozed } from "./threadSettled.ts"; const environmentId = EnvironmentId.make("environment-v2"); describe("V2 client presentation", () => { - it("keeps async questions in Working until the run completes", () => { + it("an async question blocks snooze and wakes a snoozed thread", () => { const runId = RunId.make("run-async-question"); const running = { ...v2ThreadShell, @@ -39,22 +39,12 @@ describe("V2 client presentation", () => { }, }; const active = presentThreadShell(environmentId, running); - expect(active.hasPendingUserInput).toBe(false); - expect(isThreadWorking(active)).toBe(true); expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false); - - const completed = presentThreadShell(environmentId, { - ...running, - activeRunId: null, - status: "completed", - }); - expect(completed.hasPendingUserInput).toBe(true); - expect(isThreadWorking(completed)).toBe(false); expect(effectiveSnoozed(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false); }); - it("keeps blocking and legacy questions out of Working", () => { - for (const capability of [{ blocking: true }, {}]) { + it("moves a running thread with any question out of Working", () => { + for (const capability of [{ blocking: false }, { blocking: true }, {}]) { const shell = presentThreadShell(environmentId, { ...v2ThreadShell, latestRunId: RunId.make("run-blocking-question"), diff --git a/packages/client-runtime/src/state/filesystem.test.ts b/packages/client-runtime/src/state/filesystem.test.ts index 6d1c22bb856d3..6c21c5d926919 100644 --- a/packages/client-runtime/src/state/filesystem.test.ts +++ b/packages/client-runtime/src/state/filesystem.test.ts @@ -4,6 +4,7 @@ import { AuthFilesystemReadScope, AuthOrchestrationReadScope } from "@t3tools/co import { createBrowseNavigationCoordinator, getFilesystemBrowsePath, + getFilesystemBrowseTabCompletion, resolveFilesystemReadAccess, } from "./filesystem.ts"; @@ -79,6 +80,33 @@ describe("filesystem browse model", () => { expect(getFilesystemBrowsePath("C:\\Users\\test", "MacIntel").isBrowsing).toBe(false); expect(getFilesystemBrowsePath("~/projects/", "", false).isBrowsing).toBe(false); }); + + it("completes Tab like a shell", () => { + const entry = (name: string) => ({ name, fullPath: `/Users/me/${name}` }); + expect(getFilesystemBrowseTabCompletion([entry("Creations")], "Creation")).toEqual({ + name: "Creations", + isComplete: true, + }); + expect(getFilesystemBrowseTabCompletion([entry("OpenSourced"), entry("OpenAI")], "op")).toEqual( + { name: "Open", isComplete: false }, + ); + expect(getFilesystemBrowseTabCompletion([entry("Open"), entry("Opal")], "Op")).toBeNull(); + expect(getFilesystemBrowseTabCompletion([entry("openAI"), entry("OpenSource")], "o")).toEqual({ + name: "open", + isComplete: false, + }); + expect(getFilesystemBrowseTabCompletion([entry("😀one"), entry("😁two")], "")).toBeNull(); + expect(getFilesystemBrowseTabCompletion([entry("ΟΣα"), entry("οσβ")], "ο")).toBeNull(); + expect(getFilesystemBrowseTabCompletion([entry("İfoo"), entry("İfar")], "i\u0307")).toEqual({ + name: "İf", + isComplete: false, + }); + expect(getFilesystemBrowseTabCompletion([entry("😀one"), entry("😀other")], "😀")).toEqual({ + name: "😀o", + isComplete: false, + }); + expect(getFilesystemBrowseTabCompletion([], "x")).toBeNull(); + }); }); describe("browse navigation", () => { diff --git a/packages/client-runtime/src/state/filesystem.ts b/packages/client-runtime/src/state/filesystem.ts index 90276fe21661e..4d423d0ed3609 100644 --- a/packages/client-runtime/src/state/filesystem.ts +++ b/packages/client-runtime/src/state/filesystem.ts @@ -22,6 +22,8 @@ import { } from "./projects.ts"; import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; +const BROWSE_IDLE_TTL_MS = 5_000; + export function resolveFilesystemReadAccess(input: { readonly isCatalogReady: boolean; readonly connection: Pick | null; @@ -85,6 +87,33 @@ export function filterFilesystemBrowseEntries( return { visibleEntries, exactEntry }; } +/** Shell-style Tab: a single match enters the directory, several extend to their common prefix. */ +export function getFilesystemBrowseTabCompletion( + visibleEntries: ReadonlyArray, + filterQuery: string, +): { readonly name: string; readonly isComplete: boolean } | null { + const [first, ...rest] = visibleEntries; + if (first === undefined) return null; + if (rest.length === 0) return { name: first.name, isComplete: true }; + let prefix = Array.from(first.name); + for (const entry of rest) { + const characters = Array.from(entry.name); + let length = 0; + while ( + length < prefix.length && + prefix[length]?.toLowerCase() === characters[length]?.toLowerCase() + ) + length += 1; + prefix = prefix.slice(0, length); + } + const name = prefix.join(""); + const lowerName = name.toLowerCase(); + return lowerName.length > filterQuery.toLowerCase().length && + visibleEntries.every((entry) => entry.name.toLowerCase().startsWith(lowerName)) + ? { name, isComplete: false } + : null; +} + export function createBrowseNavigationCoordinator() { let generation = 0; @@ -121,6 +150,9 @@ export function createFilesystemEnvironmentAtoms( browse: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:filesystem:browse", tag: WS_METHODS.filesystemBrowse, + // A listing kept alive while unread is never revalidated, so reopening the browser + // would show folders as they were. Keep it only long enough for a prefetch to land. + idleTtlMs: BROWSE_IDLE_TTL_MS, }), }; } diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 79e70425468c1..8c7ee5bb48d49 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -215,17 +215,6 @@ function terminalRunStatus(status: OrchestrationV2RunStatus): boolean { ); } -/** An async question waits for an answer only once its run stops working. */ -export function shellHasPendingUserInput(thread: OrchestrationV2ThreadShell): boolean { - const status = shellRuntime(thread)?.status; - // Waiting runs have ended their provider turn and are only draining effects. - const working = status === "preparing" || status === "starting" || status === "running"; - return ( - thread.pendingRuntimeRequest?.kind === "user_input" && - (thread.pendingRuntimeRequest.blocking !== false || !working) - ); -} - // Only work the agent waits on holds it: commands and monitors it left running // unmarked, such as a dev server, present the run's own status. The // server suppresses the roster while an interruptible activity run exists, so a @@ -319,7 +308,8 @@ export function presentThreadShell( thread.pendingRuntimeRequest !== null && thread.pendingRuntimeRequest.kind !== "user_input" && thread.pendingRuntimeRequest.kind !== "auth_refresh", - hasPendingUserInput: shellHasPendingUserInput(thread), + // Async questions count too, so a thread with any open question leaves Working. + hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input", pendingSubagentRequest, pendingGuestMessageCount: thread.pendingGuestMessageCount ?? 0, hasActionableProposedPlan: thread.hasActionableProposedPlan, diff --git a/packages/client-runtime/src/state/providerInstanceDisplay.test.ts b/packages/client-runtime/src/state/providerInstanceDisplay.test.ts index 27129f11128b3..4ac36acedf761 100644 --- a/packages/client-runtime/src/state/providerInstanceDisplay.test.ts +++ b/packages/client-runtime/src/state/providerInstanceDisplay.test.ts @@ -62,6 +62,11 @@ describe("shouldShowInstanceBadge", () => { expect(shouldShowInstanceBadge(entry, [entry])).toBe(true); }); + it("ignores a non-hex accent color", () => { + const entry = { driverKind: codex, accentColor: "blue", enabled: true }; + expect(shouldShowInstanceBadge(entry, [entry])).toBe(false); + }); + it("shows the badge when two entries share a driver, even without an accent", () => { const first = { driverKind: codex, accentColor: undefined, enabled: true }; const second = { driverKind: codex, accentColor: undefined, enabled: true }; diff --git a/packages/client-runtime/src/state/providerInstanceDisplay.ts b/packages/client-runtime/src/state/providerInstanceDisplay.ts index 62f65445e8217..ad69b7275342b 100644 --- a/packages/client-runtime/src/state/providerInstanceDisplay.ts +++ b/packages/client-runtime/src/state/providerInstanceDisplay.ts @@ -74,7 +74,7 @@ export function shouldShowInstanceBadge( readonly enabled: boolean; }>, ): boolean { - if (entry.accentColor) return true; + if (normalizeProviderAccentColor(entry.accentColor)) return true; let sharedProviderCount = 0; for (const candidate of entries) { if (candidate.driverKind !== entry.driverKind) continue; diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index 81afabbe8aa49..9daa166e0b63d 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -22,9 +22,11 @@ import { deriveReportedModelSelection, deriveLatestThreadRun, deriveProviderSubagentStatus, + deriveResumableRunId, deriveRunlessWorkStartedAt, deriveThreadActivityRun, deriveThreadRuntime, + presentPendingBackgroundWork, presentProviderGoal, presentRunStop, threadRuntimeHasInterruptibleRun, @@ -83,6 +85,7 @@ describe("thread execution presentation", () => { lastError: "Plan limit reached", lastErrorClass: "usage_limit", }); + expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id); expect( deriveThreadRuntime({ ...projection, @@ -153,6 +156,7 @@ describe("thread execution presentation", () => { lastError: "Plan limit reached", lastErrorClass: "usage_limit", }); + expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(failed.id); const cancelledQueued = { ...run("cancelled-queued", 3, "cancelled"), startedAt: null, @@ -164,12 +168,15 @@ describe("thread execution presentation", () => { expect( deriveThreadRuntime({ ...projection, runs: [failed, queued, cancelledQueued] }), ).toMatchObject({ status: "failed", lastErrorClass: "usage_limit" }); - expect( - deriveThreadRuntime({ - ...projection, - turnItems: [{ ...item, failure: { ...item.failure, class: "provider_error" as const } }], - }), - ).toMatchObject({ status: "queued", lastErrorClass: null }); + const providerError = { + ...projection, + turnItems: [{ ...item, failure: { ...item.failure, class: "provider_error" as const } }], + }; + expect(deriveThreadRuntime(providerError)).toMatchObject({ + status: "queued", + lastErrorClass: null, + }); + expect(deriveResumableRunId(providerError, deriveThreadRuntime(providerError))).toBeNull(); }); it("keeps live activity attached to an executing run when a newer run is queued", () => { @@ -230,6 +237,7 @@ describe("thread execution presentation", () => { status: "interrupted", activeRunId: null, }); + expect(deriveResumableRunId(projection, deriveThreadRuntime(projection))).toBe(interrupted.id); const resumed = { ...projection, runs: [interrupted, { ...held, queueHeld: false }] }; expect(deriveThreadRuntime(resumed)).toMatchObject({ status: "queued" }); @@ -488,3 +496,16 @@ describe("presentProviderGoal", () => { ).toBe("1m / 1m tokens"); }); }); + +describe("presentPendingBackgroundWork", () => { + it("names a command by its script, not the shell that wraps it", () => { + const presentation = presentPendingBackgroundWork([ + { + taskId: "call_1", + kind: "command", + description: `/bin/zsh -lc "mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF"`, + }, + ]); + expect(presentation?.items[0]?.label).toBe("mv a.ts b.ts\ncat > b.ts <<'EOF'\nexport {};\nEOF"); + }); +}); diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 951e5d06404b3..3420c25de6cf2 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -1,4 +1,5 @@ import { + latestExecutedRun, latestRootProviderFailure, latestUnheldRun, threadErrorSummary, @@ -16,6 +17,7 @@ import { type OrchestrationV2ExecutionNode, type OrchestrationV2ThreadProjection, orchestrationV2RunWorkStartedAt, + type RunId, type ThreadId, } from "@t3tools/contracts"; import { @@ -33,6 +35,7 @@ import { type ThreadStructure, type ThreadStructureRuntime, } from "./models.ts"; +import { commandDisplayText } from "../work-log/commandLabel.ts"; import { formatSubagentDisplayTitle } from "./subagentDisplay.ts"; const ACTIVITY_RUN_STATUSES = new Set(["preparing", "starting", "running", "waiting"]); @@ -209,6 +212,20 @@ export function formatProviderSubagentStatus( return live ? `${label} ${elapsed}` : `${label} in ${elapsed}`; } +/** The run a manual continuation resumes; the server holds the queue until it does. */ +export function deriveResumableRunId( + projection: Pick, + runtime: Pick | null, +): RunId | null { + const run = latestExecutedRun(projection.runs); + if (run?.status === "interrupted") return run.id; + return run?.status === "failed" && + runtime?.lastErrorClass === "usage_limit" && + latestRootProviderFailure(run, projection.turnItems)?.class === "usage_limit" + ? run.id + : null; +} + export function deriveThreadRuntime( projection: ThreadStructure & Pick, ): ThreadRuntimeSummary | null { @@ -370,9 +387,13 @@ export function presentPendingBackgroundWork( .map((task): PendingBackgroundWorkItem => { const description = task.description?.trim(); const label = - task.kind === "subagent" && description !== undefined - ? formatSubagentDisplayTitle(description).trim() - : description; + description === undefined + ? undefined + : task.kind === "subagent" + ? formatSubagentDisplayTitle(description).trim() + : task.kind === "command" || task.kind === "monitor" + ? commandDisplayText(description) + : description; return { taskId: task.taskId, kind: task.kind, diff --git a/packages/client-runtime/src/state/threadRequests.test.ts b/packages/client-runtime/src/state/threadRequests.test.ts index d5d2c4ec16d8d..d9aaf9fdca71a 100644 --- a/packages/client-runtime/src/state/threadRequests.test.ts +++ b/packages/client-runtime/src/state/threadRequests.test.ts @@ -1,5 +1,9 @@ +import { presentThreadShell } from "./models.ts"; +import { threadKey } from "./entities.ts"; import { EnvironmentId, + ThreadId, + type ScopedThreadRef, NodeId, ProviderSessionId, RuntimeRequestId, @@ -7,11 +11,13 @@ import { type OrchestrationV2ThreadProjection, } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { AsyncResult } from "effect/reactivity"; +import { Atom, AtomRegistry, AsyncResult } from "effect/reactivity"; import * as Cause from "effect/Cause"; -import { v2Now, v2Projection } from "./orchestrationV2TestFixtures.ts"; +import { v2Now, v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; import { createQuestionHistoryProjector, + createChildThreadApprovalsAtom, + type PendingThreadRequests, derivePendingThreadRequests, declinePendingApprovals, sendApprovalFeedback, @@ -353,3 +359,59 @@ it("restores old text answers without mutating history or replacing unchanged ro expect(project(answered)).toBe(result); expect(project({ ...answered, visibleTurnItems: [...rows] })[0]).toBe(result[0]); }); + +it("loads only child approvals and retains their destination across environments", () => { + const local = EnvironmentId.make("local"); + const remote = EnvironmentId.make("remote"); + const parent = { environmentId: local, threadId: ThreadId.make("parent") }; + const childId = ThreadId.make("child"); + const children = Atom.make( + [local, remote].map((environmentId) => ({ + ...presentThreadShell(environmentId, v2ThreadShell), + id: childId, + title: environmentId, + hasPendingApprovals: true, + })), + ); + const details = Atom.family((key: string) => + Atom.make({ + approvals: [ + { + requestId: RuntimeRequestId.make(key), + requestKind: "command", + createdAt: "2026-10-19T00:00:00Z", + responseCapability: "live", + }, + ], + userInputs: [], + }), + ); + const readDetails = vi.fn((ref: ScopedThreadRef) => details(threadKey(ref))); + const approvalsAtom = createChildThreadApprovalsAtom({ + childThreadInputsAtom: () => children, + pendingRequestsAtom: readDetails, + }); + const registry = AtomRegistry.make(); + const unmount = registry.mount(approvalsAtom(parent)); + const pending = registry.get(approvalsAtom(parent)); + expect(pending.map((entry) => entry.thread)).toEqual( + [local, remote].map((environmentId) => ({ environmentId, threadId: childId })), + ); + expect(pending.map((entry) => entry.title)).toEqual(["local", "remote"]); + registry.set(details(threadKey({ environmentId: remote, threadId: childId })), { + approvals: [], + userInputs: [], + }); + expect(registry.get(approvalsAtom(parent))).toEqual([pending[0]]); + readDetails.mockClear(); + registry.set( + children, + registry + .get(children) + .map((child) => ({ ...child, hasPendingApprovals: false, hasPendingUserInput: true })), + ); + expect(registry.get(approvalsAtom(parent))).toEqual([]); + expect(readDetails).not.toHaveBeenCalled(); + unmount(); + registry.dispose(); +}); diff --git a/packages/client-runtime/src/state/threadRequests.ts b/packages/client-runtime/src/state/threadRequests.ts index 9797786371014..d930be7d77a96 100644 --- a/packages/client-runtime/src/state/threadRequests.ts +++ b/packages/client-runtime/src/state/threadRequests.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + ScopedThreadRef, ThreadId, OrchestrationV2ThreadProjection, OrchestrationV2RuntimeRequest, @@ -10,6 +11,9 @@ import type { ProviderRequestKind, RuntimeRequestId, } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; +import { parseThreadKey, threadKey } from "./entities.ts"; +import type { EnvironmentThreadShell } from "./models.ts"; import * as DateTime from "effect/DateTime"; import type { AtomCommandResult } from "./runtime.ts"; import type { ThreadStructure, ThreadStructureVisibleTurnItem } from "./models.ts"; @@ -339,3 +343,48 @@ export function createQuestionHistoryProjector< return previousResult; }; } + +export interface ChildThreadApproval { + readonly thread: ScopedThreadRef; + readonly title: string; + readonly approval: ThreadPendingApproval; +} + +export function createChildThreadApprovalsAtom(input: { + readonly childThreadInputsAtom: ( + ref: ScopedThreadRef, + ) => Atom.Atom>; + readonly pendingRequestsAtom: (ref: ScopedThreadRef) => Atom.Atom; +}) { + const family = Atom.family((key: string) => { + let previous: ReadonlyArray = []; + return Atom.make((get) => { + const next = get(input.childThreadInputsAtom(parseThreadKey(key))).flatMap((child) => { + if (!child.hasPendingApprovals) return []; + const thread = { environmentId: child.environmentId, threadId: child.id }; + // Only children asking for approval need a detail subscription. + return (get(input.pendingRequestsAtom(thread))?.approvals ?? []).map((approval) => ({ + thread, + title: child.title, + approval, + })); + }); + if ( + next.length === previous.length && + next.every((entry, index) => { + const old = previous[index]!; + return ( + old.approval === entry.approval && + old.title === entry.title && + threadKey(old.thread) === threadKey(entry.thread) + ); + }) + ) + return previous; + previous = next; + return next; + }); + }); + const empty = Atom.make>([]); + return (ref: ScopedThreadRef | null) => (ref === null ? empty : family(threadKey(ref))); +} diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts index 340afd95fa5aa..6ad788e0a6623 100644 --- a/packages/client-runtime/src/state/threadSettled.ts +++ b/packages/client-runtime/src/state/threadSettled.ts @@ -125,7 +125,7 @@ export function canSnooze( options: { readonly now: string }, ): boolean { if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false; - // The server rejects snoozing even for nonblocking questions. + // The server rejects snoozing for any pending request. if (shell.source?.pendingRuntimeRequest != null) return false; if (shell.pendingSubagentRequest != null) return false; // A waiting guest message would wake it at once. diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 038df6974c84b..a6aef329882ae 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -181,7 +181,7 @@ describe("v2 thread shell lists", () => { const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom); const withRequest = ( kind: "user_input" | "command", - options: { readonly blocking?: boolean; readonly settled?: boolean } = {}, + options: { readonly blocking?: boolean } = {}, ) => registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, @@ -189,7 +189,6 @@ describe("v2 thread shell lists", () => { root, { ...sideChat, - ...(options.settled ? { status: "completed" as const, activityRunStatus: null } : {}), pendingRuntimeRequest: { ...request, kind, @@ -206,11 +205,7 @@ describe("v2 thread shell lists", () => { root.id, ]); - // An async question waits while the side chat works, like its own row's indicator. withRequest("user_input", { blocking: false }); - expect(registry.get(parent)?.pendingSubagentRequest).toBeNull(); - expect(registry.get(inputs)).toEqual([]); - withRequest("user_input", { blocking: false, settled: true }); expect(registry.get(parent)?.pendingSubagentRequest).toBe("user_input"); withRequest("command"); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index b7a6eebe571ed..60c454469b551 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -15,7 +15,7 @@ import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts"; -import { presentThreadShell, shellHasPendingUserInput, threadRuntimeIsActive } from "./models.ts"; +import { presentThreadShell, threadRuntimeIsActive } from "./models.ts"; import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts"; import { arrayElementsEqual, @@ -84,17 +84,13 @@ function subagentRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq return kind === "user_input" ? "user_input" : "approval"; } -/** - * A side chat asks its user directly, so questions roll up to the parent as well as approvals, - * when its own row would show them. - */ +/** A side chat asks its user directly, so questions roll up to the parent as well as approvals. */ function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentRequest | null { const kind = thread.pendingRuntimeRequest?.kind; if (kind === undefined || kind === "auth_refresh" || thread.lineage.sideChat !== true) { return null; } - if (kind !== "user_input") return "approval"; - return shellHasPendingUserInput(thread) ? "user_input" : null; + return kind === "user_input" ? "user_input" : "approval"; } /** diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index d78828e3a4cd5..aabf2bd119c39 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -712,6 +712,31 @@ describe("EnvironmentThreads", () => { }), ); + it.effect("asks the server again after an HTTP miss, since the thread may not exist yet", () => + Effect.gen(function* () { + const resumeCache: NonNullable[1]> = { + snapshot: undefined, + owner: undefined, + }; + yield* Effect.scoped( + Effect.gen(function* () { + const first = yield* makeHarness({ httpSnapshot: { _tag: "missing" }, resumeCache }); + yield* awaitThreadState(first.observed, (value) => value.status === "deleted"); + }), + ); + const resumed = yield* makeHarness({ + resumeCache, + httpSnapshot: { + _tag: "present", + snapshot: { snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, projection: BASE_PROJECTION }, + }, + }); + const state = yield* awaitThreadState(resumed.observed, (value) => value.status === "live"); + expect(Option.getOrThrow(state.data)).toEqual(BASE_PROJECTION); + expect(yield* Ref.get(resumed.loaderCalls)).toBe(1); + }), + ); + it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index c641ab900fc51..07b91c36fe539 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -1007,6 +1007,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } case "missing": { yield* setDeleted(); + // A 404 also means "not created yet". Only a delete event may outlive this mount. + if (resumeCache?.owner === owner) resumeCache.snapshot = undefined; return yield* Effect.never; } case "unavailable": { diff --git a/packages/client-runtime/src/t3ToolSummary.test.ts b/packages/client-runtime/src/t3ToolSummary.test.ts index 0a1b3c4d793f4..1d681b1a1735c 100644 --- a/packages/client-runtime/src/t3ToolSummary.test.ts +++ b/packages/client-runtime/src/t3ToolSummary.test.ts @@ -35,6 +35,28 @@ describe("summarizeT3ToolCalls", () => { ).toBe("Sent 2 messages to 1 thread"); }); + // Coder: the labels say merge requests. + it("counts the pull requests batch link and unlink calls changed", () => { + const urls = [ + "https://gitlab.com/o/r/-/merge_requests/1", + "https://gitlab.com/o/r/-/merge_requests/1", + "not-a-pr", + ]; + const links = completed({ urls }, { linkedCount: 1 }); + expect(summarizeT3ToolCalls("link-pr", [links, completed({ number: 3 })]).label).toBe( + "Linked 2 merge requests", + ); + expect(summarizeT3ToolCalls("link-pr", [completed({ urls }, {})]).label).toBe( + "Linked merge requests", + ); + const batch = completed({ states: ["merged"] }, { unlinkedCount: 2 }); + expect(summarizeT3ToolCalls("unlink-pr", [batch, completed({ number: 3 })]).label).toBe( + "Unlinked 3 merge requests", + ); + const uncounted = completed({ states: ["merged"] }, { isError: false }); + expect(summarizeT3ToolCalls("unlink-pr", [uncounted]).label).toBe("Unlinked merge requests"); + }); + it("excludes failed and unfinished sends even if the provider reports completed", () => { const calls: T3ToolSummaryCall[] = [ completed({ threadId: "success" }, { messageId: "ok", threadId: "success" }), diff --git a/packages/client-runtime/src/t3ToolSummary.ts b/packages/client-runtime/src/t3ToolSummary.ts index 037d1a7a59929..a6d39ca248b28 100644 --- a/packages/client-runtime/src/t3ToolSummary.ts +++ b/packages/client-runtime/src/t3ToolSummary.ts @@ -79,6 +79,25 @@ function quantity(count: number, noun: string, plural = `${noun}s`): string { return `${count} ${count === 1 ? noun : plural}`; } +/** One PR per single call; a batch counts what its result reports. */ +function pullRequestQuantity( + calls: ReadonlyArray<{ + readonly input: Record | undefined; + readonly output: Record | undefined; + }>, + countKey: "linkedCount" | "unlinkedCount", +): string { + let count = 0; + for (const call of calls) { + const reported = call.output?.[countKey]; + if (typeof reported === "number") count += reported; + else if (call.input?.url !== undefined || call.input?.number !== undefined) count += 1; + // A batch result too large to compact loses its count, so the label drops the number. + else return "merge requests"; + } + return quantity(count, "merge request"); +} + export function summarizeT3ToolCalls( action: T3McpToolSummaryAction, calls: ReadonlyArray, @@ -379,10 +398,10 @@ export function summarizeT3ToolCalls( break; } case "link-pr": - label = phrase("Linked", "link", quantity(selected.length, "merge request")); + label = phrase("Linked", "link", pullRequestQuantity(selected, "linkedCount")); break; case "unlink-pr": - label = phrase("Unlinked", "unlink", quantity(selected.length, "merge request")); + label = phrase("Unlinked", "unlink", pullRequestQuantity(selected, "unlinkedCount")); break; case "watch-pr": label = phrase("Watching", "watch", quantity(selected.length, "merge request")); diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 9d60bec43fe5c..f9cd98311d19d 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -161,6 +161,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ linkFence: Schema.optionalKey(Schema.Boolean), /** Server answers server.prepareTriage. */ triage: Schema.optionalKey(Schema.Boolean), + /** Server accepts `{ type: "once" }` scheduled tasks; older servers reject them on save. */ + oneTimeSchedules: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index 87990e7f542f7..1a04cc61c887a 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -27,6 +27,8 @@ export const SelectProviderOptionDescriptor = Schema.Struct({ options: Schema.Array(ProviderOptionChoice), currentValue: Schema.optional(TrimmedNonEmptyString), promptInjectedValues: Schema.optional(Schema.Array(TrimmedNonEmptyString)), + /** Marks the reasoning control when its id is an agent's own, such as an ACP `thought_level`. */ + role: Schema.optional(Schema.Literal("reasoning")), }); export type SelectProviderOptionDescriptor = typeof SelectProviderOptionDescriptor.Type; diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 1474a5d6e87b6..438a3fe2def98 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -67,7 +67,7 @@ const OrchestratorMcpSchedule = Schema.Union([ OrchestratorMcpScheduleFromJsonString, ]).annotate({ description: - "Trigger: {type:'interval',everyMs}, {type:'fixed_time',timeOfDay,weekdays?}, or {type:'webhook'}.", + "Trigger: {type:'interval',everyMs}, {type:'fixed_time',timeOfDay,weekdays?}, {type:'once',runAt}, or {type:'webhook'}.", }); const OrchestratorMcpTargetOptionsFromRecord = Schema.Record( diff --git a/packages/contracts/src/scheduledTask.test.ts b/packages/contracts/src/scheduledTask.test.ts index 50a49de7f867d..c9b4d597bd0a3 100644 --- a/packages/contracts/src/scheduledTask.test.ts +++ b/packages/contracts/src/scheduledTask.test.ts @@ -22,6 +22,22 @@ describe("ScheduledTaskSchedule", () => { everyMs: MIN_SCHEDULED_TASK_INTERVAL_MS - 1, }); }); + + it("accepts a one-time run only with an offset", () => { + for (const runAt of ["2026-11-03T09:00Z", "2026-11-03T09:00:00.000-08:00"]) { + expect(decodeUpsertSchedule({ type: "once", runAt })).toEqual({ type: "once", runAt }); + } + for (const runAt of [ + "2026-11-03T09:00", + "2026-13-03T09:00Z", + "2026-02-30T09:00Z", + "9999-12-31T23:30-01:00", + "0000-01-01T00:00+00:01", + "tomorrow", + ]) { + expect(() => decodeUpsertSchedule({ type: "once", runAt })).toThrow(); + } + }); }); it.each(["literal", " ", "\t\n", "{{body.bad", "{{unknown.field}}"])( diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts index b4dffacd74c04..5fbbc48301d3a 100644 --- a/packages/contracts/src/scheduledTask.ts +++ b/packages/contracts/src/scheduledTask.ts @@ -45,6 +45,34 @@ const ScheduledTaskFixedTimeSchedule = Schema.Struct({ ), }); +const ISO_WITH_OFFSET = + /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/; + +const YEAR_0000 = Date.parse("0000-01-01T00:00:00Z"); +const YEAR_10000 = Date.parse("+010000-01-01T00:00:00Z"); + +/** Date.parse rolls impossible days like Feb 30 into the next month, so check the day too. */ +function isIsoWithOffset(value: string): boolean { + const match = ISO_WITH_OFFSET.exec(value); + // The server stores UTC, which must stay a four-digit year to decode again. + const time = Date.parse(value); + if (!match || !(time >= YEAR_0000 && time < YEAR_10000)) return false; + const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]; + const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1]; + return days !== undefined && day >= 1 && day <= days; +} + +// Checked by filter, not pattern, to keep the MCP tool schema small. +const ScheduledTaskOnceSchedule = Schema.Struct({ + type: Schema.Literal("once"), + runAt: TrimmedNonEmptyString.check( + Schema.makeFilter( + (value) => isIsoWithOffset(value) || "Expected an ISO date and time with an offset.", + ), + ), +}); + const ScheduledTaskWebhookSignatureFields = { header: TrimmedNonEmptyString.annotate({ description: "Header with the signature, such as x-hub-signature-256.", @@ -166,6 +194,7 @@ const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({ export const ScheduledTaskSchedule = Schema.Union([ ScheduledTaskIntervalSchedule, ScheduledTaskFixedTimeSchedule, + ScheduledTaskOnceSchedule, ScheduledTaskWebhookSchedule, ]); export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type; @@ -180,6 +209,7 @@ export const ScheduledTaskUpsertSchedule = Schema.Union([ }), }), ScheduledTaskFixedTimeSchedule, + ScheduledTaskOnceSchedule, ScheduledTaskUpsertWebhookSchedule, ]); export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type; diff --git a/packages/effect-codex-app-server/src/errors.ts b/packages/effect-codex-app-server/src/errors.ts index 33d8cf5c48839..9f16adcd66c87 100644 --- a/packages/effect-codex-app-server/src/errors.ts +++ b/packages/effect-codex-app-server/src/errors.ts @@ -109,6 +109,7 @@ export type CodexAppServerProtocolParseOperation = typeof CodexAppServerProtocol export const CodexAppServerTransportOperation = Schema.Literals([ "read-input-stream", + "write-output-stream", "read-process-exit-status", ]); export type CodexAppServerTransportOperation = typeof CodexAppServerTransportOperation.Type; diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts index b1bb9d8af3184..04a0660abad2c 100644 --- a/packages/effect-codex-app-server/src/protocol.test.ts +++ b/packages/effect-codex-app-server/src/protocol.test.ts @@ -1,8 +1,10 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as PlatformError from "effect/PlatformError"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Sink from "effect/Sink"; import * as Stdio from "effect/Stdio"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -820,6 +822,43 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => { }), ); + it.effect("fails pending requests when a write fails while input stays open", () => + Effect.gen(function* () { + const { stdio: baseStdio } = yield* makeInMemoryStdio(); + const writeFailure = PlatformError.systemError({ + _tag: "Unknown", + module: "Stdio", + method: "stdout", + cause: new Error("EPIPE"), + }); + const terminated = yield* Deferred.make(); + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ + stdio: Stdio.make({ + args: baseStdio.args, + stdin: baseStdio.stdin, + stdout: () => Sink.forEach(() => Effect.fail(writeFailure)), + stderr: baseStdio.stderr, + }), + onTermination: (error) => Deferred.succeed(terminated, error).pipe(Effect.asVoid), + }); + const pending = yield* transport.request("thread/read", {}).pipe(Effect.forkScoped); + + const failure = yield* Deferred.await(terminated); + assert.instanceOf(failure, CodexError.CodexAppServerTransportError); + assert.equal(failure.operation, "write-output-stream"); + assert.strictEqual(failure.cause, writeFailure); + for (const request of [Fiber.join(pending), transport.request("thread/read", {})]) { + const requestFailure = yield* request.pipe( + Effect.match({ + onFailure: (error) => error, + onSuccess: () => assert.fail("Expected the broken transport to reject the request"), + }), + ); + assert.strictEqual(requestFailure, failure); + } + }), + ); + it.effect("reports a process exit that follows input end", () => Effect.gen(function* () { const { stdio, input } = yield* makeInMemoryStdio(); diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts index 8edeea0f99730..f9f7fa5e30dce 100644 --- a/packages/effect-codex-app-server/src/protocol.ts +++ b/packages/effect-codex-app-server/src/protocol.ts @@ -521,7 +521,20 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa Effect.forkScoped, ); - yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); + yield* Stream.fromQueue(outgoing).pipe( + Stream.run(options.stdio.stdout()), + Effect.catch((cause) => + handleTermination(() => + Effect.succeed( + new CodexError.CodexAppServerTransportError({ + operation: "write-output-stream", + cause, + }), + ), + ), + ), + Effect.forkScoped, + ); const request = Effect.fn("CodexAppServerProtocol.request")(function* ( method: string, diff --git a/packages/provider-acp-registry/src/server/driver.test.ts b/packages/provider-acp-registry/src/server/driver.test.ts index 5f40cef3a8cd4..21986c8cdb037 100644 --- a/packages/provider-acp-registry/src/server/driver.test.ts +++ b/packages/provider-acp-registry/src/server/driver.test.ts @@ -172,6 +172,37 @@ describe("acpRegistrySnapshotReadiness", () => { nativeSessions: { canList: true, canLoad: true, canResume: true }, models: [{ slug: "live-model", isDefault: true }], }); + + expect( + applyAcpRegistryLiveConfiguration( + provider, + { models: [], currentModelId: null, configOptions: [] }, + [], + ).models, + ).toEqual(provider.models); + + const liveOptions = [ + { + id: "effort", + label: "Effort", + type: "select" as const, + options: [{ id: "high", label: "High" }], + currentValue: "high", + }, + ]; + expect( + applyAcpRegistryLiveConfiguration( + provider, + { models: [], currentModelId: null, configOptions: liveOptions }, + [], + ).models, + ).toMatchObject([ + { + slug: "probe-model", + isDefault: true, + capabilities: { optionDescriptors: [{ id: "effort", currentValue: "high" }] }, + }, + ]); }); it("maps local inspection status to provider readiness", () => { diff --git a/packages/provider-acp-registry/src/server/driver.ts b/packages/provider-acp-registry/src/server/driver.ts index 9268adc61d7e6..c30302aec5e95 100644 --- a/packages/provider-acp-registry/src/server/driver.ts +++ b/packages/provider-acp-registry/src/server/driver.ts @@ -212,10 +212,28 @@ export function applyAcpRegistryLiveConfiguration( customModels: ReadonlyArray, ): ServerProvider { const { message: _staleProbeMessage, ...snapshot } = provider; + // session/load may omit models (Kimi returns `{}`); keep the probed list + // and apply any live option descriptors to it. + const probedModels = provider.models.filter((model) => !model.isCustom); + const discovery = + configuration.models.length > 0 + ? configuration + : { + ...configuration, + models: probedModels.map((model) => ({ + id: model.slug, + name: model.name, + description: null, + })), + currentModelId: probedModels.find((model) => model.isDefault)?.slug ?? null, + }; return { ...snapshot, status: provider.enabled ? "ready" : provider.status, - models: modelsFromDiscovery(configuration, customModels), + models: + configuration.models.length === 0 && configuration.configOptions.length === 0 + ? provider.models + : modelsFromDiscovery(discovery, customModels), }; } diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 800b095c72d92..454881bf64e60 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -407,6 +407,8 @@ export interface AcpAdapterV2Flavor { readonly reportsPerTurnPromptUsage?: boolean; /** Grok can retain task_already_running until process exit. */ readonly restartRuntimeAfterInterrupt?: boolean; + /** Prompt failures after which the agent process keeps failing until replaced. */ + readonly restartRuntimeAfterPromptError?: (error: unknown) => boolean; readonly restartRuntimeOnEveryInterrupt?: boolean; readonly terminateRuntimeProcessGroupOnInterrupt?: boolean; readonly preserveRuntimeOnSettledInterrupt?: boolean; @@ -1005,6 +1007,12 @@ function completedAtForStatus(status: ProjectedToolStatus, now: DateTime.Utc): D return status === "completed" || status === "failed" || status === "interrupted" ? now : null; } +// Copilot advertises URL ids such as `https://agentclientprotocol.com/protocol/session-modes#plan`. +function isAcpPlanModeId(id: string): boolean { + const name = id.slice(id.lastIndexOf("#") + 1); + return name === "plan" || name === "architect"; +} + function selectPermissionOptionId( request: EffectAcpSchema.RequestPermissionRequest, decision: Exclude, @@ -3990,20 +3998,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (planState.latest === null) return; plan = { ...planState.latest, status: "superseded" }; } else if (update.kind === "items") { - const steps: ReadonlyArray = update.plan.map( - (step, index) => ({ - id: `acp-step-${index + 1}`, - text: nonEmptyText(step.step, `Step ${index + 1}`), - status: - step.status === "inProgress" - ? "running" - : step.status === "completed" - ? "completed" - : "pending", - }), + // A cancelled entry is not outstanding work, and plan steps have no + // cancelled status, so drop it rather than show it as pending. + const steps: ReadonlyArray = update.plan.flatMap( + (step, index) => + step.status === "cancelled" + ? [] + : [ + { + id: `acp-step-${index + 1}`, + text: nonEmptyText(step.step, `Step ${index + 1}`), + status: + step.status === "inProgress" + ? "running" + : step.status === "completed" + ? "completed" + : "pending", + }, + ], ); const completed = - steps.length > 0 && steps.every((step) => step.status === "completed"); + update.plan.length > 0 && steps.every((step) => step.status === "completed"); plan = { ...base, status: completed ? "completed" : "active", @@ -4573,10 +4588,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (yield* projectAgentTerminalUpdate(notification, context)) return; if ( update.sessionUpdate === "usage_update" || - update.sessionUpdate === "session_info_update" || - (update.sessionUpdate === "state_update" && - update.state === "idle" && - update.usage != null) + update.sessionUpdate === "session_info_update" ) { const stateEvent = parseSessionUpdateEvent(notification).events.find( (event) => event._tag === "UsageUpdated" || event._tag === "SessionInfoUpdated", @@ -4627,7 +4639,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( providerThread, }); } - if (update.sessionUpdate !== "state_update") return; + return; } if (yield* followNativeChild(notification, context)) return; if ( @@ -6911,8 +6923,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( })), }); } - const planMode = effectiveModeState?.availableModes.find( - (mode) => mode.id === "plan" || mode.id === "architect", + const planMode = effectiveModeState?.availableModes.find((mode) => + isAcpPlanModeId(mode.id), ); if (planMode !== undefined && effectiveModeState?.currentModeId !== planMode.id) { yield* runtime.setMode(planMode.id); @@ -6921,9 +6933,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const choices = option.options.flatMap((entry) => "value" in entry ? [entry.value] : entry.options.map((choice) => choice.value), ); - const requested = choices.find( - (choice) => choice === "plan" || choice === "architect", - ); + const requested = choices.find(isAcpPlanModeId); if (requested !== undefined && option.currentValue !== requested) { yield* runtime.setConfigOption(option.id, requested); } @@ -7798,12 +7808,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( Result.isSuccess(error) && error.success._tag === "AcpRequestError" && error.success.code === -32800); + const failure = Cause.squash(cause); + if (!interrupted && flavor.restartRuntimeAfterPromptError?.(failure) === true) { + yield* Ref.set(runtimeRestartRequired, true); + } yield* finalizeTurn( context, interrupted ? "interrupted" : "failed", - flavor.promptFailure?.(Cause.squash(cause)) ?? + flavor.promptFailure?.(failure) ?? makeProviderFailure({ - cause: Cause.squash(cause), + cause: failure, class: "provider_error", }), ).pipe( diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index b278c9e71bed0..c35789ec47dc4 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1047,10 +1047,7 @@ describe("AcpRuntimeModel", () => { data: { rawOutput: "Retained the implementation decisions." }, }, }); - expect(idle.events[0]).toMatchObject({ - _tag: "UsageUpdated", - usage: { usedTokens: 420 }, - }); + expect(idle.events).toEqual([]); }); it("applies ACP v2 agent-owned terminal snapshots and output chunks", () => { diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 9a34f7fa40573..49fd56cc19d6c 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -220,7 +220,7 @@ export type AcpPlanUpdate = readonly explanation?: string | null; readonly plan: ReadonlyArray<{ readonly step: string; - readonly status: "pending" | "inProgress" | "completed"; + readonly status: "pending" | "inProgress" | "completed" | "cancelled"; }>; } | { readonly nativePlanId: string; readonly kind: "markdown"; readonly markdown: string } @@ -493,10 +493,14 @@ export function parseSessionModeState( }; } -function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" { +function normalizePlanStepStatus( + raw: unknown, +): "pending" | "inProgress" | "completed" | "cancelled" { switch (raw) { case "completed": return "completed"; + case "cancelled": + return "cancelled"; case "in_progress": case "inProgress": return "inProgress"; @@ -1549,16 +1553,6 @@ export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotificat } break; } - case "state_update": { - if (upd.state === "idle" && upd.usage !== undefined && upd.usage !== null) { - events.push({ - _tag: "UsageUpdated", - usage: { usedTokens: upd.usage.totalTokens }, - rawPayload: params, - }); - } - break; - } case "usage_update": { const currency = upd.cost?.currency.trim().slice(0, 32); events.push({ diff --git a/packages/provider-acp/src/server/sessionConfig.test.ts b/packages/provider-acp/src/server/sessionConfig.test.ts index 308ba1db02ccf..ceb6ceb92783a 100644 --- a/packages/provider-acp/src/server/sessionConfig.test.ts +++ b/packages/provider-acp/src/server/sessionConfig.test.ts @@ -50,6 +50,7 @@ describe("acpProviderOptionDescriptors", () => { { id: "medium", label: "Medium", description: "Balanced" }, ], currentValue: "medium", + role: "reasoning", }, ]); }); diff --git a/packages/provider-acp/src/server/sessionConfig.ts b/packages/provider-acp/src/server/sessionConfig.ts index 46269bb5e0d13..b79fdaebe245d 100644 --- a/packages/provider-acp/src/server/sessionConfig.ts +++ b/packages/provider-acp/src/server/sessionConfig.ts @@ -102,6 +102,7 @@ export function acpProviderOptionDescriptors(input: { ...(currentValue && choices.some((choice) => choice.id === currentValue) ? { currentValue } : {}), + ...(option.category === "thought_level" ? { role: "reasoning" as const } : {}), }); if (descriptors.length === MAX_OPTION_DESCRIPTORS) return descriptors; } diff --git a/packages/provider-core/src/server/maintenance.ts b/packages/provider-core/src/server/maintenance.ts index 4e402717608b8..b9f793cc8bf72 100644 --- a/packages/provider-core/src/server/maintenance.ts +++ b/packages/provider-core/src/server/maintenance.ts @@ -15,6 +15,8 @@ export interface ProviderMaintenanceCapabilities { readonly compareVersions?: (current: string, latest: string) => number; /** Resolved executable path for advisories when no update command is proven. */ readonly installPath?: string; + /** Displayed for manual updates; never executed by T3 Code. */ + readonly manualCommand?: string; } export interface ProviderMaintenanceCommandAction { @@ -22,6 +24,6 @@ export interface ProviderMaintenanceCommandAction { readonly executable: string; readonly args: ReadonlyArray; readonly lockKey: string; - /** Native updaters must use the instance's custom home (e.g. `CODEX_HOME`). */ + /** The provider's environment, including its PATH and custom home. */ readonly env?: NodeJS.ProcessEnv; } diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index da59b77886a59..35ccaebf21e0f 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -25,10 +25,12 @@ import { homebrewOwnershipFromCommandPath, invalidateLatestProviderVersion, makeCachedProviderMaintenanceResolution, + makeManualOnlyProviderMaintenanceCapabilities, makePackageManagedProviderMaintenanceResolver, makeProviderMaintenanceCapabilities, normalizeCommandPath, npmGlobalPrefixFromCommandPath, + parseChocolateyLatestVersion, parseHomebrewLatestVersion, resolveLatestProviderVersion, resolvePackageManagedProviderMaintenance, @@ -232,7 +234,7 @@ it.layer( let probes = 0; const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( fixture.install === "native" ? nativePackageToolUpdate : packageToolUpdate, - { binaryPath, env: { PATH: "" } }, + { binaryPath, env: { PATH: fixture.install === "npm" ? npmBinDir : "" } }, ).pipe( Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }), Effect.provideService( @@ -381,6 +383,26 @@ it.layer( }); }); + it("shows the Chocolatey upgrade command without offering to run it", () => { + expect( + createProviderVersionAdvisory({ + driver: driver("claudeAgent"), + currentVersion: "2.1.304", + latestVersion: "2.1.306", + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: driver("claudeAgent"), + packageName: "@anthropic-ai/claude-code", + installPath: "C:\\ProgramData\\chocolatey\\bin\\claude.exe", + manualCommand: "choco upgrade claude-code", + }), + }), + ).toMatchObject({ + canUpdate: false, + canInstallVersion: false, + updateCommand: "choco upgrade claude-code", + }); + }); + it.effect("stays manual-only when the binary cannot be located", () => resolveProviderMaintenanceCapabilitiesEffect(packageToolUpdate, { binaryPath: "package-tool", @@ -394,7 +416,7 @@ it.layer( ); it.effect.skipIf(!symlinksSupported)( - "pins npm updates to the global prefix that owns the package", + "pins npm updates to the global prefix that owns the package and the provider's PATH", () => Effect.gen(function* () { const tempDir = yield* makeTempDir("t3-npm-capabilities"); @@ -404,12 +426,14 @@ it.layer( "@example", "package-tool", ]); + // A version manager's Node, which only the provider's settings put on PATH. + const providerEnv = { PATH: NodePath.join(tempDir, "bin") }; const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( packageToolUpdate, { binaryPath: link, - env: { PATH: "" }, + env: providerEnv, }, ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)); @@ -428,6 +452,7 @@ it.layer( "@example/package-tool@latest", ], lockKey: `npm-global:${normalizeCommandPath(tempDir)}`, + env: providerEnv, }, }); }), @@ -547,12 +572,13 @@ it.layer( readonly resolved: string; readonly real: string; readonly platform?: NodeJS.Platform; + readonly env?: NodeJS.ProcessEnv; }) => resolvePackageManagedProviderMaintenance(input.definition, { binaryPath: "claude", resolvedCommandPath: input.resolved, realCommandPath: input.real, - env: {}, + env: input.env ?? {}, platform: input.platform ?? "win32", }).pipe( Effect.provideService(HostProcess.Platform, input.platform ?? "win32"), @@ -585,6 +611,135 @@ it.layer( }), ); + const chocolateyShim = "C:\\ProgramData\\chocolatey\\bin\\claude.exe"; + const chocolateyPackage = "C:\\ProgramData\\chocolatey\\lib\\claude-code\\tools\\claude.exe"; + + it.effect.each([ + { name: "the shimgen shim", resolved: chocolateyShim, real: chocolateyShim }, + { name: "the package binary", resolved: chocolateyPackage, real: chocolateyPackage }, + { + name: "a custom root", + resolved: "D:\\Tools\\Choco\\bin\\claude.exe", + real: "D:\\Tools\\Choco\\bin\\claude.exe", + env: { ChocolateyInstall: "D:\\Tools\\Choco" }, + }, + { + name: "a custom root package", + resolved: "D:\\Tools\\Choco\\lib\\claude-code\\tools\\claude.exe", + real: "D:\\Tools\\Choco\\lib\\claude-code\\tools\\claude.exe", + env: { ChocolateyInstall: "D:\\Tools\\Choco" }, + }, + { + name: "a mixed-case custom root with a trailing separator", + resolved: "D:\\Tools\\Choco\\bin\\Claude.EXE", + real: "D:\\Tools\\Choco\\bin\\Claude.EXE", + env: { ChocolateyInstall: "d:/tools/choco/" }, + }, + { name: "a native-looking alias", resolved: nativeClaude, real: chocolateyPackage }, + ] as const)("keeps a Chocolatey Claude install manual-only through $name", (fixture) => + Effect.gen(function* () { + const capabilities = yield* resolveInstall({ definition: claudeUpdate, ...fixture }); + + expect(capabilities.update).toBeNull(); + expect(capabilities.installPath).toBe(fixture.real); + expect(capabilities.latestVersion).toBeNull(); + expect(capabilities.lookupLatestVersion).toBeDefined(); + expect(capabilities.manualCommand).toBe("choco upgrade claude-code"); + }), + ); + + it.effect("keeps a Chocolatey-shaped path off Windows on the native updater", () => + Effect.gen(function* () { + const commandPath = "/home/me/chocolatey/bin/claude.exe"; + const capabilities = yield* resolveInstall({ + definition: claudeUpdate, + resolved: commandPath, + real: commandPath, + platform: "linux", + }); + + expect(capabilities.update).toMatchObject({ lockKey: "claudeAgent-native" }); + }), + ); + + // Chocolatey publishes behind npm, so comparing against the registry would + // report an update `choco upgrade` cannot install yet. + it.effect("compares a Chocolatey Claude install against choco search", () => + Effect.gen(function* () { + const probes: Array<{ command: string; args: ReadonlyArray }> = []; + const capabilities = yield* resolvePackageManagedProviderMaintenance(claudeUpdate, { + binaryPath: "claude", + resolvedCommandPath: chocolateyShim, + realCommandPath: chocolateyShim, + env: {}, + platform: "win32", + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner((command, args) => { + probes.push({ command, args }); + return "claude-code|2.1.304\r\n"; + }), + ), + ); + expect(probes).toEqual([]); + + const latest = yield* resolveLatestProviderVersion(capabilities).pipe( + Effect.provide(ProviderLatestVersions.layer), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("the installer's latest should not come from npm")), + ), + ); + + expect(latest).toBe("2.1.304"); + expect(probes.map(({ command }) => NodePath.basename(command).replace(/\.\w+$/, ""))).toEqual( + ["choco"], + ); + expect(probes[0]?.args).toEqual(["search", "claude-code", "--exact", "--limit-output"]); + expect( + createProviderVersionAdvisory({ + driver: driver("claudeAgent"), + currentVersion: "2.1.304", + latestVersion: latest, + maintenanceCapabilities: capabilities, + }), + ).toMatchObject({ status: "current", canUpdate: false, canInstallVersion: false }); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("stays unknown when choco search fails instead of asking npm", () => + Effect.gen(function* () { + const capabilities = yield* resolvePackageManagedProviderMaintenance(claudeUpdate, { + binaryPath: "claude", + resolvedCommandPath: chocolateyShim, + realCommandPath: chocolateyShim, + env: {}, + platform: "win32", + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner( + () => "", + () => 1, + ), + ), + ); + + const latest = yield* resolveLatestProviderVersion(capabilities).pipe( + Effect.provide(ProviderLatestVersions.layer), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("a failed choco search should not fall back to npm")), + ), + ); + + expect(latest).toBeNull(); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect.each([ { name: "a native install", @@ -617,6 +772,12 @@ it.layer( resolved: userWinGetLink, real: userWinGetPackage, }, + { + name: "a claude-code tools path outside Chocolatey", + definition: claudeUpdate, + resolved: "C:\\Work\\lib\\claude-code\\tools\\claude.exe", + real: "C:\\Work\\lib\\claude-code\\tools\\claude.exe", + }, { name: "another WinGet package", definition: claudeUpdate, @@ -764,7 +925,8 @@ it.layer( it.effect.each([ { - case: "the eligible release", + case: "the eligible release with an inherited PATH", + inheritPath: true, outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } }, exitCode: 1, npmOutput: '"1.2.0"', @@ -819,9 +981,11 @@ it.layer( let npmProbes = 0; const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( packageToolUpdate, - { binaryPath: link, env: { PATH: "" } }, + { binaryPath: link, env: fixture.inheritPath ? {} : { PATH: pnpmBinDir } }, ).pipe( - Effect.provideService(HostProcess.Environment, { PATH: pnpmBinDir }), + Effect.provideService(HostProcess.Environment, { + PATH: fixture.inheritPath ? pnpmBinDir : "", + }), Effect.provideService( ChildProcessSpawner.ChildProcessSpawner, stdoutSpawner( @@ -1052,6 +1216,13 @@ it.layer( }), ); + it("reads the Chocolatey package version from choco search --limit-output", () => { + expect(parseChocolateyLatestVersion("claude-code|2.1.304\r\n", "claude-code")).toBe("2.1.304"); + expect(parseChocolateyLatestVersion("Claude-Code|2.1.304\r\n", "claude-code")).toBe("2.1.304"); + expect(parseChocolateyLatestVersion("claude-code-other|9.9.9\r\n", "claude-code")).toBeNull(); + expect(parseChocolateyLatestVersion("", "claude-code")).toBeNull(); + }); + it("recognizes Homebrew kegs and casks from the real executable path", () => { expect( homebrewOwnershipFromCommandPath("/opt/homebrew/Cellar/claude-code@latest/2.1.0/bin/claude"), diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index 3ce890e981e21..718a090925637 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -198,6 +198,8 @@ export function makeManualOnlyProviderMaintenanceCapabilities(input: { readonly provider: ProviderDriverKind; readonly packageName: string | null; readonly installPath?: string; + readonly lookupLatestVersion?: Effect.Effect; + readonly manualCommand?: string; }): ProviderMaintenanceCapabilities { return { ...makeProviderMaintenanceCapabilities({ @@ -206,8 +208,12 @@ export function makeManualOnlyProviderMaintenanceCapabilities(input: { updateExecutable: null, updateArgs: [], updateLockKey: null, + ...(input.lookupLatestVersion + ? { latestVersion: null, lookupLatestVersion: input.lookupLatestVersion } + : {}), }), ...(input.installPath ? { installPath: input.installPath } : {}), + ...(input.manualCommand ? { manualCommand: input.manualCommand } : {}), }; } @@ -247,6 +253,32 @@ function isWinGetClaudeCommandPath(commandPath: string): boolean { return winGetClaudeCommandPath.test(normalizeCommandPath(commandPath)); } +const CHOCOLATEY_CLAUDE_PACKAGE_ID = "claude-code"; + +// Chocolatey's executable shim is not a symlink, so realpath cannot prove its owner. +const chocolateyClaudeCommandPath = /\/chocolatey\/(?:bin|lib\/claude-code\/tools)\/claude\.exe$/; + +function isChocolateyClaudeCommandPath(commandPath: string, env: NodeJS.ProcessEnv): boolean { + const normalized = normalizeCommandPath(commandPath); + if (chocolateyClaudeCommandPath.test(normalized)) return true; + const root = nonEmptyString(env.ChocolateyInstall); + if (!root) return false; + const prefix = normalizeCommandPath(root.replace(/[\\/]+$/, "")); + return ( + normalized === `${prefix}/bin/claude.exe` || + normalized === `${prefix}/lib/claude-code/tools/claude.exe` + ); +} + +/** `choco search --exact --limit-output` prints `|` for a match and nothing otherwise. */ +export function parseChocolateyLatestVersion(output: string, packageId: string): string | null { + for (const line of output.split(/\r?\n/)) { + const [id, version] = line.trim().split("|", 2); + if (id?.toLowerCase() === packageId.toLowerCase()) return nonEmptyString(version); + } + return null; +} + function isPnpmGlobalCommandPath(commandPath: string): boolean { const normalized = normalizeCommandPath(commandPath); return ( @@ -392,15 +424,18 @@ const decodePnpmList = Schema.decodeUnknownOption( // Unlike npm's latest tag, pnpm outdated respects minimumReleaseAge and its excludes. const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion")(function* ( packageName: string, + env: NodeJS.ProcessEnv, ) { - // Match the updater's pnpm and server environment, rather than the instance's. - const pnpmPath = yield* resolveCommandPath("pnpm"); + // Match the updater's pnpm and environment. + const pnpmPath = yield* resolveCommandPath("pnpm", { + env: { ...(yield* HostProcess.Environment), ...env }, + }); if (!pnpmPath) return null; // Silent reporting keeps project package-manager warnings out of the JSON. const outdated = yield* runProbe( pnpmPath, ["outdated", "-g", "--reporter=silent", "--format", "json", packageName], - {}, + env, // pnpm outdated exits 1 when updates are available. [0, 1], ); @@ -414,7 +449,7 @@ const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion const listed = yield* runProbe( pnpmPath, ["ls", "-g", "--reporter=silent", "--depth", "0", "--json", packageName], - {}, + env, ); const listedEntries = listed ? Option.getOrUndefined(decodePnpmList(listed)) : undefined; return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version); @@ -447,6 +482,32 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( ) { return manual; } + // Chocolatey's package directory is writable only by administrators, so an + // unelevated server cannot run `choco upgrade`; `claude update` through the + // shim installs a native copy elsewhere and leaves the shim's version alone. + if ( + definition.provider === "claudeAgent" && + context.platform === "win32" && + commandPaths.some((commandPath) => isChocolateyClaudeCommandPath(commandPath, context.env)) + ) { + const services = yield* Effect.context(); + return makeManualOnlyProviderMaintenanceCapabilities({ + provider: definition.provider, + packageName, + installPath: context.realCommandPath, + manualCommand: "choco upgrade claude-code", + lookupLatestVersion: runProbe( + "choco", + ["search", CHOCOLATEY_CLAUDE_PACKAGE_ID, "--exact", "--limit-output"], + context.env, + ).pipe( + Effect.map((output) => + output ? parseChocolateyLatestVersion(output, CHOCOLATEY_CLAUDE_PACKAGE_ID) : null, + ), + Effect.provideContext(services), + ), + }); + } const nativeUpdate = definition.nativeUpdate; const nativeEnv = nativeUpdate?.env; @@ -486,6 +547,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( updateExecutable: "vp", updateArgs: ["i", "-g", packageName], updateLockKey: "vite-plus-global", + env: context.env, }); } if (commandPaths.some(isBunGlobalCommandPath)) { @@ -495,6 +557,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( updateExecutable: "bun", updateArgs: ["i", "-g", `${packageName}@latest`], updateLockKey: "bun-global", + env: context.env, }); } if (commandPaths.some(isPnpmGlobalCommandPath)) { @@ -511,7 +574,8 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( updateExecutable: "pnpm", updateArgs: ["add", "-g", ...allowBuild, `${packageName}@latest`], updateLockKey: "pnpm-global", - lookupLatestVersion: resolvePnpmGlobalLatestVersion(packageName).pipe( + env: context.env, + lookupLatestVersion: resolvePnpmGlobalLatestVersion(packageName, context.env).pipe( Effect.provideContext(services), ), }); @@ -524,6 +588,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( updateExecutable: "yarn", updateArgs: ["global", "add", `${packageName}@latest`], updateLockKey: "yarn-global", + env: context.env, }); } if (yield* isVoltaPackageInstall(context, packageName)) { @@ -533,6 +598,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( updateExecutable: "volta", updateArgs: ["install", `${packageName}@latest`], updateLockKey: "volta", + env: context.env, }); } @@ -553,6 +619,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( `${packageName}@latest`, ], updateLockKey: `npm-global:${normalizeCommandPath(npmPrefix)}`, + env: context.env, }); } @@ -723,7 +790,8 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup if (!packageName || capabilities.latestVersion !== undefined) { return capabilities; } - const npmPath = yield* resolveCommandPath("npm"); + const env = { ...(yield* HostProcess.Environment), ...capabilities.update?.env }; + const npmPath = yield* resolveCommandPath("npm", { env }); if (!npmPath) return capabilities; const services = yield* Effect.context(); const update = capabilities.update; @@ -741,7 +809,7 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup `${packageName}@latest`, "version", ], - {}, + env, ).pipe( Effect.map((stdout) => { const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null; @@ -872,7 +940,10 @@ export function createProviderVersionAdvisory(input: { status: advisory.status, currentVersion: input.currentVersion, latestVersion, - updateCommand: resolveLatestProviderUpdateAction(capabilities, latestVersion)?.command ?? null, + updateCommand: + resolveLatestProviderUpdateAction(capabilities, latestVersion)?.command ?? + capabilities.manualCommand ?? + null, canUpdate: capabilities.update !== null, canInstallVersion: makeTargetedProviderUpdateAction(capabilities, "0.0.0") !== null, checkedAt: input.checkedAt ?? null, @@ -895,12 +966,16 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack return Option.isSome(payload) ? nonEmptyString(payload.value.version) : null; }); -/** The installer's own answer is cached apart from the npm registry entry. */ +/** + * The installer's own answer is cached apart from the npm registry entry. A + * manual-only install has no command to key on, so its executable stands in. + */ function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) { if (!capabilities.lookupLatestVersion) return null; const update = capabilities.update; - return update - ? [update.lockKey, update.executable, ...update.args].join("\0") + if (update) return [update.lockKey, update.executable, ...update.args].join("\0"); + return capabilities.installPath + ? ["manual", capabilities.installPath].join("\0") : capabilities.packageName && `npm-registry\0${capabilities.packageName}`; } diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts index f83ba2408e6f9..9471be743f79d 100644 --- a/packages/provider-core/src/server/managedProvider.ts +++ b/packages/provider-core/src/server/managedProvider.ts @@ -44,6 +44,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean; readonly initialSnapshot: (settings: Settings) => Effect.Effect; readonly checkProvider: Effect.Effect; + readonly checkUsageLimits?: Effect.Effect; readonly invalidateUsageCache?: Effect.Effect; readonly enrichSnapshot?: (input: { readonly settings: Settings; @@ -250,14 +251,45 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( ); }); + const needsUsageRecovery = (snapshot: ServerProvider) => + input.checkUsageLimits !== undefined && + snapshot.installed && + snapshot.status === "ready" && + snapshot.auth.status === "authenticated" && + snapshot.usageLimits?.unavailable?.reason === "probeFailed"; + + const needsProviderRefresh = (snapshot: ServerProvider) => + input.refreshOnInterval !== false && + (typeof input.refreshOnInterval !== "function" || input.refreshOnInterval(snapshot)); + + const refreshOnInterval = Effect.fn("ManagedServerProvider.refreshOnInterval")(function* () { + const { snapshot } = yield* Ref.get(snapshotStateRef); + if (!snapshot.enabled) return; + if (!needsUsageRecovery(snapshot) || !input.checkUsageLimits) { + if (needsProviderRefresh(snapshot)) { + yield* applySnapshotBase(yield* input.getSettings, { forceRefresh: true }); + } + return; + } + const probed = yield* input.checkUsageLimits; + const next = yield* Ref.modify(snapshotStateRef, (state) => { + const usageLimits = resolveUsageLimitsAfterProbe({ + published: state.snapshot.usageLimits, + probed, + }); + const snapshot = withUsageLimits(state.snapshot, usageLimits); + return [snapshot, { ...state, snapshot }] as const; + }); + yield* PubSub.publish(changesPubSub, next); + }); + const shouldRefreshOnInterval = Effect.gen(function* () { const state = yield* Ref.get(snapshotStateRef); // A disabled instance has nothing to probe; a periodic check would only // republish a snapshot that differs in checkedAt. if ( !state.snapshot.enabled || - input.refreshOnInterval === false || - (typeof input.refreshOnInterval === "function" && !input.refreshOnInterval(state.snapshot)) + (!needsUsageRecovery(state.snapshot) && !needsProviderRefresh(state.snapshot)) ) { return false; } @@ -317,7 +349,9 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0 ? shouldRefreshOnInterval.pipe( Effect.flatMap((shouldRefresh) => - shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void, + shouldRefresh + ? refreshSemaphore.withPermits(1)(refreshOnInterval()) + : Effect.void, ), ) : Effect.void, diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index 0a7778ad7d708..7e1edeb2ac006 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -7,7 +7,7 @@ describe("buildRuntimeInstructions", () => { const instructions = buildRuntimeInstructions({ harness: "Codex" }); assert.include(instructions, "Link each PR you create, take over, or push to"); - assert.include(instructions, "one link_pull_request per PR"); + assert.include(instructions, "every stack layer"); assert.include(instructions, "Skip PRs you only read or review"); assert.include(instructions, "If linking fails, say so."); assert.notInclude(instructions, "git log -1"); diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index f6118a7cd9cd5..7f7dba43c2b08 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,5 +1,5 @@ const PULL_REQUEST_LINKING_INSTRUCTIONS = ` -Link each PR you create, take over, or push to: one link_pull_request per PR, full URL, every stack layer, as your next call. Host tools do not link for you. If linking fails, say so. Skip PRs you only read or review, and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. +Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools do not link for you. If linking fails, say so. Skip PRs you only read or review, and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. `; /** Omit model and effort when the harness manages them dynamically. */ diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index e18687414f92e..7179398cf602d 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -60,6 +60,7 @@ export function makeSubagentChildThread(input: { creationSource: input.creationSource, id: input.childThreadId, title: input.title, + titleRegeneration: null, linkedPullRequest: null, pullRequests: [], historyOrigin: undefined, diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 56754c30923bd..5c94de3040209 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -27,6 +27,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; @@ -3301,6 +3302,34 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("keeps an input dialog's title as the header above its placeholder", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-input-placeholder", + method: "input", + title: "Name", + placeholder: "Your name", + }); + const event = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { + return assert.fail("expected a user input request"); + } + assert.equal(event.turnItem.questions[0]?.header, "Name"); + assert.equal(event.turnItem.questions[0]?.question, "Your name"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("emits a valid empty select option and returns its original value", () => Effect.gen(function* () { const fake = yield* makeFakePi; @@ -3332,6 +3361,8 @@ describe("PiAdapterV2", () => { ["Empty value", ""], ], ); + assert.equal(questions[0]?.header, "Question"); + assert.equal(questions[0]?.question, "Pick a tag"); yield* runtime.respondToRuntimeRequest({ requestId: event.turnItem.requestId, answers: { "ui-select": "" }, @@ -3366,6 +3397,7 @@ describe("PiAdapterV2", () => { if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { return assert.fail("expected a user input request"); } + assert.equal(decodeUserInputQuestions(event.turnItem.questions)[0]?.header, "Question"); assert.equal(decodeUserInputQuestions(event.turnItem.questions)[0]?.question, title); yield* runtime.respondToRuntimeRequest({ requestId: event.turnItem.requestId, @@ -3401,6 +3433,7 @@ describe("PiAdapterV2", () => { return; assert.equal(event.turnItem.questions[0]?.initialAnswer, prefill); assert.deepEqual(event.turnItem.questions[0]?.options, []); + assert.equal(event.turnItem.questions[0]?.header, "Question"); assert.equal(event.turnItem.questions[0]?.question, "Commit message"); const edited = " fix(server): edited commit message\n\n"; yield* runtime.respondToRuntimeRequest({ @@ -4263,8 +4296,16 @@ describe("PiAdapterV2", () => { }); describe("PiRpc framing", () => { - it.effect("reassembles records across chunk boundaries and strips CR", () => - Effect.gen(function* () { + it.effect("reassembles records and warns when dropping oversized records", () => { + const warnings: Array> = []; + const warned = Deferred.makeUnsafe(); + const logCapture = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn" && Array.isArray(message)) { + warnings.push(message); + Deferred.doneUnsafe(warned, Effect.void); + } + }); + return Effect.gen(function* () { const stdout = yield* Queue.unbounded(); const spawner = ChildProcessSpawner.make(() => Effect.succeed( @@ -4295,9 +4336,11 @@ describe("PiRpc framing", () => { yield* push('{"type":"agent_'); yield* push('start"}\r\n{"type":"agent_settled"}\nnot json\n{"type":"queue_update"}\n'); - yield* push('{"type":"must_not_emit","text":"'); + const head = '{"type":"must_not_emit","text":"'; + yield* push(head); const chunk = new TextEncoder().encode("x".repeat(8 * 1024 * 1024)); for (let index = 0; index < 32; index++) yield* Queue.offer(stdout, chunk); + yield* Deferred.await(warned); yield* push('"}\n{"type":"after_oversized"}\n'); const first = yield* Queue.take(connection.events); @@ -4307,8 +4350,20 @@ describe("PiRpc framing", () => { const third = yield* Queue.take(connection.events); assert.equal(third["type"], "queue_update"); assert.equal((yield* Queue.take(connection.events))["type"], "after_oversized"); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); + assert.lengthOf(warnings, 1); + const [text, annotations] = warnings[0] ?? []; + assert.equal(text, "Dropping oversized pi stdout record."); + assert.deepEqual(annotations, { + recordLength: head.length + 28 * chunk.length, + maxRecordLength: 232084864, + }); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.merge(NodeServices.layer, Logger.layer([logCapture], { mergeWithExisting: false })), + ), + ); + }); }); describe("PiRpc early process exit", () => { diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index f1924e7639202..a32a5759ba707 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3333,15 +3333,15 @@ function piQuestion( value: "", }, ]; + // Pi's select and editor dialogs carry only a title, so show it once, as the question. // Extensions may send a blank placeholder, which is not a valid question. - const question = - [recordString(event, "message"), recordString(event, "placeholder")].find( - (text) => text !== undefined && text.trim().length > 0, - ) ?? title; + const detail = [recordString(event, "message"), recordString(event, "placeholder")].find( + (text) => text !== undefined && text.trim().length > 0, + ); return { id: questionId, - header: title, - question, + header: detail === undefined ? "Question" : title, + question: detail ?? title, ...(method === "editor" ? { initialAnswer: recordString(event, "prefill") ?? "" } : {}), options, }; diff --git a/packages/provider-pi/src/server/rpc.ts b/packages/provider-pi/src/server/rpc.ts index ed608613ac901..0af3fade61c33 100644 --- a/packages/provider-pi/src/server/rpc.ts +++ b/packages/provider-pi/src/server/rpc.ts @@ -96,14 +96,16 @@ const MAX_PI_RECORD_CHARS = function makeJsonlFramer() { let buffer = ""; let dropping = false; - return (chunk: string): ReadonlyArray => { + return (chunk: string) => { const lines: string[] = []; + const droppedLengths: number[] = []; let start = 0; while (start < chunk.length) { const newline = chunk.indexOf("\n", start); const end = newline < 0 ? chunk.length : newline; if (!dropping) { if (buffer.length + end - start > MAX_PI_RECORD_CHARS) { + droppedLengths.push(buffer.length + end - start); buffer = ""; dropping = true; } else { @@ -118,10 +120,22 @@ function makeJsonlFramer() { dropping = false; start = newline + 1; } - return lines; + return { lines, droppedLengths }; }; } +// Report the observed length before LF arrives; an unterminated response can time out first. +const logDroppedPiRecords = (droppedLengths: ReadonlyArray) => + Effect.forEach( + droppedLengths, + (recordLength) => + Effect.logWarning("Dropping oversized pi stdout record.", { + recordLength, + maxRecordLength: MAX_PI_RECORD_CHARS, + }), + { discard: true }, + ); + const UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown); const decodeJsonLine = Schema.decodeSync(UnknownFromJsonString); const encodeJsonLine = Schema.encodeSync(UnknownFromJsonString); @@ -294,7 +308,8 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp Stream.decodeText(), Stream.runForEach((chunk) => Effect.gen(function* () { - const lines = frame(chunk); + const { lines, droppedLengths } = frame(chunk); + yield* logDroppedPiRecords(droppedLengths); for (const line of lines) { const record = parsePiRecord(line); if (record === undefined) { @@ -308,7 +323,9 @@ export const makePiRpcConnection = Effect.fnUntraced(function* (options: PiRpcSp }), ), ); - for (const line of frame("\n")) { + const flushed = frame("\n"); + yield* logDroppedPiRecords(flushed.droppedLengths); + for (const line of flushed.lines) { const trailing = parsePiRecord(line); if (trailing !== undefined) yield* routeRecord(trailing); } diff --git a/packages/shared/package.json b/packages/shared/package.json index 4e9027532f78b..b79a857305bd3 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -16,6 +16,10 @@ "types": "./src/themePreview.ts", "import": "./src/themePreview.ts" }, + "./textDirection": { + "types": "./src/textDirection.ts", + "import": "./src/textDirection.ts" + }, "./projectFavicon": { "types": "./src/projectFavicon.ts", "import": "./src/projectFavicon.ts" diff --git a/packages/shared/src/agentAwareness.test.ts b/packages/shared/src/agentAwareness.test.ts index 3788b7a3e6ba2..d5f77e763622e 100644 --- a/packages/shared/src/agentAwareness.test.ts +++ b/packages/shared/src/agentAwareness.test.ts @@ -183,7 +183,7 @@ describe("projectThreadAwarenessV2", () => { ).toMatchObject({ phase }); }); - it("reports an async question as input only after the working run completes", () => { + it("reports an async question as input while the run keeps working", () => { const input = { environmentId: "env-1" as EnvironmentId, project, @@ -197,12 +197,9 @@ describe("projectThreadAwarenessV2", () => { }), }; expect(projectThreadAwarenessV2(input)).toMatchObject({ - phase: "running", - headline: "Agent is working", + phase: "waiting_for_input", + headline: "Waiting for input", }); - expect( - projectThreadAwarenessV2({ ...input, thread: { ...input.thread, status: "completed" } }), - ).toMatchObject({ phase: "waiting_for_input", headline: "Waiting for input" }); }); it("does not present authentication refreshes as user approvals", () => { diff --git a/packages/shared/src/agentAwareness.ts b/packages/shared/src/agentAwareness.ts index e36001ead3d4e..c7bf09fe0dd0b 100644 --- a/packages/shared/src/agentAwareness.ts +++ b/packages/shared/src/agentAwareness.ts @@ -98,22 +98,14 @@ export function projectThreadAwarenessV2( function resolveThreadAwarenessPhaseV2( thread: ProjectThreadAwarenessV2Input["thread"], ): AgentAwarenessPhase | null { - const runStatus = thread.activityRunStatus ?? thread.status; - if ( - thread.pendingRuntimeRequest?.kind === "user_input" && - (thread.pendingRuntimeRequest.blocking !== false || - !(runStatus === "preparing" || runStatus === "starting" || runStatus === "running")) - ) { - return "waiting_for_input"; - } + if (thread.pendingRuntimeRequest?.kind === "user_input") return "waiting_for_input"; if ( thread.pendingRuntimeRequest !== null && - thread.pendingRuntimeRequest.kind !== "user_input" && thread.pendingRuntimeRequest.kind !== "auth_refresh" ) { return "waiting_for_approval"; } - switch (runStatus) { + switch (thread.activityRunStatus ?? thread.status) { case "preparing": case "starting": return "starting"; diff --git a/packages/shared/src/atomicWrite.test.ts b/packages/shared/src/atomicWrite.test.ts index 366009f833132..3b0a99ec0d2d2 100644 --- a/packages/shared/src/atomicWrite.test.ts +++ b/packages/shared/src/atomicWrite.test.ts @@ -14,6 +14,36 @@ import { writeFileStringAtomically } from "./atomicWrite.ts"; import * as HostProcess from "./HostProcess.ts"; it.layer(NodeServices.layer)("writeFileStringAtomically", (it) => { + it.effect.each(HostProcess.Platform.defaultValue() === "linux" ? [39, 40, 41] : [])( + "matches native file access for a chain of %i symlinks", + (hops) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-atomic-write-" }); + const destination = path.join(root, "settings.json"); + const first = path.join(root, "link-0"); + yield* fs.writeFileString(destination, "before"); + for (let index = hops - 1; index >= 0; index--) { + const target = index === hops - 1 ? "settings.json" : `link-${index + 1}`; + yield* fs.symlink(target, path.join(root, `link-${index}`)); + } + + const read = yield* Effect.exit(fs.readFileString(first)); + const write = yield* Effect.exit( + writeFileStringAtomically({ filePath: first, contents: "after" }), + ); + + assert.strictEqual(Exit.isSuccess(read), hops <= 40); + assert.strictEqual(Exit.isSuccess(write), Exit.isSuccess(read)); + assert.strictEqual( + yield* fs.readFileString(destination), + Exit.isSuccess(read) ? "after" : "before", + ); + assert.strictEqual(yield* fs.readLink(first), "link-1"); + }), + ); + it.effect("keeps a symlinked file linked and rewrites its destination", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/packages/shared/src/cliArgs.test.ts b/packages/shared/src/cliArgs.test.ts index d4006e3bf4ebd..465feb3b049fc 100644 --- a/packages/shared/src/cliArgs.test.ts +++ b/packages/shared/src/cliArgs.test.ts @@ -25,6 +25,24 @@ describe("tokenizeCliArgs", () => { String.raw`--config model="gpt 5" --enable foo\ bar --config=profile='work profile'`, ), ).toEqual(["--config", "model=gpt 5", "--enable", "foo bar", "--config=profile=work profile"]); + + for (const whitespace of [" ", "\t"]) { + const args = `--add-dir /tmp/project\\${whitespace}`; + expect(tokenizeCliArgs(args)).toEqual(["--add-dir", `/tmp/project${whitespace}`]); + expect(tokenizeCliArgs(`${args} --verbose`)).toEqual([ + "--add-dir", + `/tmp/project${whitespace}`, + "--verbose", + ]); + } + }); + + it("ignores unescaped surrounding whitespace", () => { + expect(tokenizeCliArgs(" \t\n")).toEqual([]); + expect(tokenizeCliArgs(" \t--add-dir /tmp/project \t\n")).toEqual([ + "--add-dir", + "/tmp/project", + ]); }); it("preserves literal backslashes in path values", () => { diff --git a/packages/shared/src/cliArgs.ts b/packages/shared/src/cliArgs.ts index 253b7191ed83d..cfcda09e88a04 100644 --- a/packages/shared/src/cliArgs.ts +++ b/packages/shared/src/cliArgs.ts @@ -8,7 +8,7 @@ export interface ParseCliArgsOptions { } export function tokenizeCliArgs(args?: string): ReadonlyArray { - const input = args?.trim(); + const input = args; if (!input) return []; const tokens: string[] = []; diff --git a/packages/shared/src/composerTrigger.test.ts b/packages/shared/src/composerTrigger.test.ts index 757ad17ef7a59..c063b4e366c05 100644 --- a/packages/shared/src/composerTrigger.test.ts +++ b/packages/shared/src/composerTrigger.test.ts @@ -22,6 +22,16 @@ describe("detectComposerTrigger", () => { }); }); + it.each(["/Model opus", "/MODEL opus"])( + "opens the model picker for capitalized %j the same as /model", + (text) => { + expect(detectComposerTrigger(text, text.length)).toMatchObject({ + kind: "slash-model", + query: "opus", + }); + }, + ); + it.each(["Use /", "Use /review"])("detects the inline slash token in %j", (text) => { expect(detectComposerTrigger(text, text.length)).toEqual({ kind: "slash-command", diff --git a/packages/shared/src/composerTrigger.ts b/packages/shared/src/composerTrigger.ts index b89d6d7f6bdf2..ce40e77fe923f 100644 --- a/packages/shared/src/composerTrigger.ts +++ b/packages/shared/src/composerTrigger.ts @@ -121,7 +121,7 @@ export function detectComposerTrigger( }; } - const modelMatch = /^\/model(?:\s+(.*))?$/.exec(linePrefix); + const modelMatch = /^\/model(?:\s+(.*))?$/i.exec(linePrefix); if (modelMatch) { return { kind: "slash-model", diff --git a/packages/shared/src/delimitedPreview.test.ts b/packages/shared/src/delimitedPreview.test.ts index fee976e702201..a2464eef2b099 100644 --- a/packages/shared/src/delimitedPreview.test.ts +++ b/packages/shared/src/delimitedPreview.test.ts @@ -59,6 +59,39 @@ describe("delimited file previews", () => { expect(table.rows[0]?.[0]).toHaveLength(2000); expect(parseDelimitedPreview('a,"unfinished', ",").truncated).toBe(true); }); + describe.each([",", "\t"] as const)("Unicode cells with delimiter %j", (delimiter) => { + it.each([false, true])("does not split surrogate pairs in quoted=%s cells", (quoted) => { + const prefix = "x".repeat(1999); + const value = `${prefix}😀tail`; + const input = `${quoted ? `"${value}"` : value}${delimiter}next\nlast`; + expect(parseDelimitedPreview(input, delimiter)).toEqual({ + rows: [[prefix, "next"], ["last"]], + truncated: true, + }); + }); + it("keeps pairs that fit and truncates later characters", () => { + const value = `${"x".repeat(1998)}😀`; + expect(parseDelimitedPreview(value, delimiter)).toEqual({ + rows: [[value]], + truncated: false, + }); + expect(parseDelimitedPreview(`${value}tail`, delimiter)).toEqual({ + rows: [[value]], + truncated: true, + }); + }); + it("keeps escaped quotes and BMP text at the same limit", () => { + const prefix = "x".repeat(1999); + expect(parseDelimitedPreview(`"${prefix}""tail"`, delimiter)).toEqual({ + rows: [[`${prefix}"`]], + truncated: true, + }); + expect(parseDelimitedPreview(`${prefix}éextra`, delimiter)).toEqual({ + rows: [[`${prefix}é`]], + truncated: true, + }); + }); + }); it("reads worker pages beyond the old row, column and cell limits", () => { const text = Array.from({ length: 128 }, (_, row) => Array.from({ length: 40 }, (_, column) => `${row}:${column}`).join(","), diff --git a/packages/shared/src/delimitedPreview.ts b/packages/shared/src/delimitedPreview.ts index 6934b036c90af..07703482bf830 100644 --- a/packages/shared/src/delimitedPreview.ts +++ b/packages/shared/src/delimitedPreview.ts @@ -24,6 +24,14 @@ export function parseDelimitedPreview( let truncated = false; let rowStart = text.charCodeAt(0) === 0xfeff ? 1 : 0; const endCell = () => { + if (cell.length > limits.maxCellLength) { + let end = limits.maxCellLength; + const before = cell.charCodeAt(end - 1); + const after = cell.charCodeAt(end); + if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--; + cell = cell.slice(0, end); + truncated = true; + } if (row.length < limits.maxColumns) row.push(cell); else truncated = true; cell = ""; @@ -32,7 +40,7 @@ export function parseDelimitedPreview( const char = text[index]; if (char === '"') { if (quoted && text[index + 1] === '"') { - if (cell.length < limits.maxCellLength) cell += '"'; + if (cell.length <= limits.maxCellLength) cell += '"'; else truncated = true; index++; continue; @@ -52,7 +60,7 @@ export function parseDelimitedPreview( if (rows.length === limits.maxRows) return { rows, truncated: truncated || index < text.length - 1 }; } - } else if (cell.length < limits.maxCellLength) cell += char; + } else if (cell.length <= limits.maxCellLength) cell += char; else truncated = true; } if (rowStart < text.length) { diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index 30a5ca2bd5dea..ede9f059c578c 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -268,6 +268,12 @@ describe("sanitizeFeatureBranchName", () => { ])("keeps the fallback for unprefixed input %s", (input, expected) => { expect(sanitizeFeatureBranchName(input)).toBe(expected); }); + + it("keeps accented letters as their plain letters", () => { + expect(sanitizeFeatureBranchName("fix/Añadir validación del café")).toBe( + "fix/anadir-validacion-del-cafe", + ); + }); }); describe("resolveAutoFeatureBranchName", () => { diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index 3277ea3b29d92..4ac89394c213f 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -19,6 +19,8 @@ const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp( export function sanitizeBranchFragment(raw: string): string { const normalized = raw + .normalize("NFKD") + .replace(/[̀-ͯ]/g, "") .trim() .toLowerCase() .replace(/['"`]/g, "") diff --git a/packages/shared/src/inlineSkills.test.ts b/packages/shared/src/inlineSkills.test.ts new file mode 100644 index 0000000000000..9413148cee9e7 --- /dev/null +++ b/packages/shared/src/inlineSkills.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; +import { formatProviderSkillDisplayName } from "./inlineSkills.ts"; + +describe("formatProviderSkillDisplayName", () => { + it.each([ + ["mca_lab_status", "mca_lab_status"], + ["frontend-design:frontend-design", "frontend-design:frontend-design"], + ["superpowers:brainstorming", "superpowers:brainstorming"], + ["DesignSync", "DesignSync"], + ])("shows %s as its skill name when the provider sets no display name", (name, label) => { + expect(formatProviderSkillDisplayName({ name })).toBe(label); + }); + + it("prefers the provider display name", () => { + expect(formatProviderSkillDisplayName({ name: "gh-fix-ci", displayName: " Fix CI " })).toBe( + "Fix CI", + ); + }); +}); diff --git a/packages/shared/src/inlineSkills.ts b/packages/shared/src/inlineSkills.ts index 4898d037682f2..7a8c05f4e2b5b 100644 --- a/packages/shared/src/inlineSkills.ts +++ b/packages/shared/src/inlineSkills.ts @@ -2,23 +2,10 @@ import type { ServerProviderSkill } from "@t3tools/contracts"; export type InlineSkill = Pick; -function titleCaseWords(value: string): string { - const words: string[] = []; - for (const segment of value.split(/[\s:_-]+/)) { - if (segment.length === 0) continue; - words.push(segment.charAt(0).toUpperCase() + segment.slice(1)); - } - return words.join(" "); -} - export function formatProviderSkillDisplayName( skill: Pick, ): string { - const displayName = skill.displayName?.trim(); - if (displayName) { - return displayName; - } - return titleCaseWords(skill.name); + return skill.displayName?.trim() || skill.name; } const SKILL_TOKEN_REGEX = diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 690e6d94523c9..efab07d2e8961 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -1045,3 +1045,5 @@ effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => { }), ); }); + +// Coder: upstream's desktop shell environment update case (#28556) is cut with `applyShellEnvironment`. diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 73c54d1f8b88d..105d2936fd3cf 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -908,13 +908,13 @@ function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray Effect.succeedNone), diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index 33afbe3b11b17..f7a2746684c51 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -92,11 +92,21 @@ const T3_MCP_TOOLS: Readonly> = { "link-pr", "pull-request", ), + link_pull_requests: tool( + ["Link", "Linking", "Linked", "merge requests"], + "link-pr", + "pull-request", + ), unlink_pull_request: tool( ["Unlink", "Unlinking", "Unlinked", "a merge request"], "unlink-pr", "pull-request", ), + unlink_pull_requests: tool( + ["Unlink", "Unlinking", "Unlinked", "merge requests by state"], + "unlink-pr", + "pull-request", + ), list_thread_pull_requests: tool( ["Check", "Checking", "Checked", "linked merge requests"], "list-prs", @@ -132,10 +142,7 @@ const T3_MCP_TOOLS: Readonly> = { ["Cancel", "Canceling", "Requested cancellation of", "a delegated task"], "task-cancel", ), - schedule_task: tool( - ["Schedule", "Scheduling", "Scheduled", "a recurring task"], - "schedule-create", - ), + schedule_task: tool(["Schedule", "Scheduling", "Scheduled", "a task"], "schedule-create"), list_scheduled_tasks: tool(["List", "Listing", "Listed", "scheduled tasks"], "schedule-list"), update_scheduled_task: tool( ["Update", "Updating", "Updated", "a scheduled task"], diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts new file mode 100644 index 0000000000000..5611e41720d48 --- /dev/null +++ b/packages/shared/src/textDirection.ts @@ -0,0 +1,34 @@ +export type TextDirection = "ltr" | "rtl"; + +// Hebrew through Arabic Extended-A, their presentation forms, and the +// supplementary right-to-left blocks. +const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +const LETTER = /\p{L}/u; + +/** + * `dir="auto"` misreads Arabic prose that opens with an English term. + * Count words so mixed prose follows its main language; break ties with the first word. + */ +export function textDirection(text: string): TextDirection | undefined { + if (!RTL_LETTER.test(text)) return LETTER.test(text) ? "ltr" : undefined; + let rtlWords = 0; + let ltrWords = 0; + let first: TextDirection | undefined; + for (const word of text.split(/\s+/)) { + const letter = LETTER.exec(word)?.[0]; + if (!letter) continue; + const direction = RTL_LETTER.test(letter) ? "rtl" : "ltr"; + first ??= direction; + if (direction === "rtl") rtlWords += 1; + else ltrWords += 1; + } + if (rtlWords === ltrWords) return first; + return rtlWords > ltrWords ? "rtl" : "ltr"; +} + +const MARKDOWN_CODE_OR_URL = + /(`{3,}|~{3,})[\s\S]*?(?:\1|$)|(`{1,2})(?!`)[\s\S]*?(? { scheduledTaskId: "scheduled-1", status: "failed", summary: "A child failed; the tool itself succeeded.", + unlinked: [{ repository: "acme/app", state: "merged", numbers: [1] }], + unlinkedCount: 1, + linkedCount: 2, }; expect(compactDynamicToolOutput(output)).toEqual({ thread: { threadId: "thread-1" }, taskId: "task-1", scheduledTaskId: "scheduled-1", + linkedCount: 2, + unlinkedCount: 1, }); expect(output.thread.messages).toEqual(["Private message"]); }); diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.ts index 1982482a3d3a1..a41e9931eaa0f 100644 --- a/packages/shared/src/toolOutput.ts +++ b/packages/shared/src/toolOutput.ts @@ -43,6 +43,8 @@ interface CompactToolOutput { [MCP_APP_OUTPUT_KEY]?: McpAppReference; thread?: { threadId: string }; threads?: Array<{ threadId?: string; status?: "rolled_back" }>; + linkedCount?: number; + unlinkedCount?: number; } function readResult(value: unknown, budget: ResultReadBudget, depth = 0): ResultEnvelope { @@ -123,6 +125,10 @@ export function compactDynamicToolOutput(value: unknown): CompactToolOutput | un if (id !== undefined) output[key] = id; } if (data.status === "rolled_back") output.status = "rolled_back"; + for (const key of ["linkedCount", "unlinkedCount"] as const) { + const count = data[key]; + if (typeof count === "number" && Number.isSafeInteger(count)) output[key] = count; + } const htmlRender = readHtmlRenderReference(data.htmlRender); if (htmlRender !== undefined) output.htmlRender = htmlRender; const mcpApp = readMcpAppReference(data[MCP_APP_OUTPUT_KEY]); diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index e7f45b137a08e..a72632b99c61b 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -195,6 +195,8 @@ export class SourceControlProvider extends Context.Service< readonly cwd: string; readonly context?: SourceControlProviderContext; readonly repository: string; + /** The host the repository is on. Without it, the checkout's host. */ + readonly host?: string; }) => Effect.Effect; readonly createRepository: (input: { readonly cwd: string; diff --git a/packages/source-control-core/src/shared/definition.ts b/packages/source-control-core/src/shared/definition.ts index d2aaccfe95b2f..f777027bb1bde 100644 --- a/packages/source-control-core/src/shared/definition.ts +++ b/packages/source-control-core/src/shared/definition.ts @@ -101,6 +101,8 @@ export interface SourceControlMediaUrl { readonly fileName: string; /** Set when the URL alone says what the media is, as an extensionless upload can. */ readonly kind?: "image" | "video"; + /** Set when the bytes behind `fetchUrl` can never change, so a client may cache them by it. */ + readonly immutable?: true; } export interface ReferenceAutolink { diff --git a/packages/source-control-gitlab/src/server/GitLabCli.test.ts b/packages/source-control-gitlab/src/server/GitLabCli.test.ts index 003b0407052ea..6d441fcc46980 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.test.ts @@ -82,6 +82,19 @@ layer("GitLabCli.layer", (it) => { args: ["mr", "view", "--output", "json", "--", "42"], }), ); + const classifyFailure = mockedRun.mock.calls.at(-1)?.[0].classifyFailure; + assert.strictEqual( + classifyFailure?.( + "x gitlab.example.test has not been authenticated with glab. Run `glab auth login`", + ), + "authentication", + ); + assert.strictEqual( + classifyFailure?.( + 'Failed to get merge request 42: oauth2: "invalid_grant" "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."', + ), + "authentication", + ); }), ); diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index 8ec8b0ddb8c67..f854dc4c330e1 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -442,11 +442,18 @@ function parseRepositoryPath(repository: string): { return { namespacePath, projectPath }; } -// glab prints a missing project or merge request as a bare 404. +// glab prints a missing project or merge request as a bare 404, and an expired +// OAuth login as an `invalid_grant` refresh failure without suggesting `glab auth login`. const classifyGlabFailure = (stderr: string): VcsProcessExitFailureKind | null => { const normalized = stderr.toLowerCase(); - if (normalized.includes("glab auth login")) return "authentication"; - if (normalized.includes("not found") || normalized.includes("404")) return "not-found"; + if (normalized.includes("glab auth login") || normalized.includes("invalid_grant")) { + return "authentication"; + } + + if (normalized.includes("not found") || normalized.includes("404")) { + return "not-found"; + } + return null; }; diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts index 74403b4dae9a6..870fe42df4ffd 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.test.ts @@ -148,6 +148,14 @@ describe("decodeMergeRequestDetailJson", () => { ]); }); + it.each(["canceled", "canceling"])("maps a %s pipeline to cancelled", (status) => { + const detail = expectSuccess( + decodeMergeRequestDetailJson(detailJson({ head_pipeline: { status } })), + ); + + expect(detail.checks[0]?.status).toBe("cancelled"); + }); + it("reads an uncounted change set as its floor", () => { const detail = expectSuccess( decodeMergeRequestDetailJson(detailJson({ changes_count: "1000+" })), diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts index 8f50d9ea6659c..e8e5e664b3720 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequestJson.ts @@ -262,7 +262,7 @@ function toPipelineStatus(value: string | null | undefined): PullRequestCheckSta case "failed": return "failure"; case "canceled": - case "cancelling": + case "canceling": return "cancelled"; case "skipped": return "skipped"; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c630dfec12286..1a48e84824c83 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -498,6 +498,9 @@ importers: '@tiptap/extension-blockquote': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-bold': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) '@tiptap/extension-code': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) @@ -516,6 +519,9 @@ importers: '@tiptap/extension-list': specifier: ^3.31.3 version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3) + '@tiptap/extension-strike': + specifier: ^3.31.3 + version: 3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3)) '@tiptap/extension-task-item': specifier: ^3.31.3 version: 3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3)) @@ -561,6 +567,9 @@ importers: html-url-attributes: specifier: ^3.0.1 version: 3.0.1 + jsonc-parser: + specifier: 3.3.1 + version: 3.3.1 jszip: specifier: 3.10.1 version: 3.10.1 @@ -3901,6 +3910,9 @@ packages: engines: {node: '>=6'} hasBin: true + jsonc-parser@3.3.1: + resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} + jszip@3.10.1: resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==} @@ -7557,6 +7569,8 @@ snapshots: json5@2.2.3: {} + jsonc-parser@3.3.1: {} + jszip@3.10.1: dependencies: lie: 3.3.0 diff --git a/scripts/seams-check.mjs b/scripts/seams-check.mjs index c4be76c30c550..492e4372640c7 100644 --- a/scripts/seams-check.mjs +++ b/scripts/seams-check.mjs @@ -14,7 +14,7 @@ import { execFile, execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; -const SYNC_BASE = "15fe283272"; +const SYNC_BASE = "8760d063e9"; const base = process.argv[2] ?? SYNC_BASE; const DOC = "docs/internals/coder-only.md"; const SECTIONS = ["Upstream seams", "Cut surfaces"]; diff --git a/scripts/sync-resolve-deleted.mjs b/scripts/sync-resolve-deleted.mjs index 31a96e934df14..5eef33e5eab10 100644 --- a/scripts/sync-resolve-deleted.mjs +++ b/scripts/sync-resolve-deleted.mjs @@ -165,6 +165,10 @@ const DELETED_PATHS = { "scripts/apply-web-brand-assets.ts", "scripts/build-desktop-artifact.ts", "scripts/fixtures/desktop-launch/", + // The desktop build's server bytecode cache (#28572). + "scripts/lib/server-compile-cache.ts", + "scripts/lib/server-compile-cache.test.ts", + "scripts/prepare-server-compile-cache.cjs", ], // Mobile: no mobile app. mobile: ["apps/mobile/", "patches/@expo__ui@58.0.20.patch", "patches/expo-sharing@58.0.19.patch"], @@ -186,6 +190,8 @@ const DELETED_PATHS = { "server CLI": [ "apps/server/src/binCli.ts", "apps/server/src/cli/", + "apps/server/src/cliCompileCache.ts", + "apps/server/src/cliCompileCache.test.ts", "apps/server/src/environment/ServerEnvironment.ts", "apps/server/src/serverRuntimeStartup.autoPull.test.ts", "apps/server/src/serverRuntimeStartup.test.ts", @@ -196,6 +202,9 @@ const DELETED_PATHS = { "local editors and provider setup": [ "apps/server/src/process/externalLauncher.ts", "apps/server/src/process/externalLauncher.test.ts", + // Late editor and SSH target discovery (#14519); only the cut launcher and open targets use it. + "apps/server/src/environment/staleWhileRevalidate.ts", + "apps/server/src/environment/staleWhileRevalidate.test.ts", "apps/web/src/components/settings/CodexSetupSection.tsx", "packages/shared/src/editor.ts", "apps/server/src/provider/CodexChatGptModels.ts", @@ -222,6 +231,10 @@ const DELETED_PATHS = { "apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx", "apps/web/test/fakeEnvironment.ts", "packages/client-runtime/src/state/server.test.ts", + // Bulk provider updates' management-scope gate (#23183), which the always-grant scopes open. + "apps/web/src/components/ProviderUpdatesAction.browser.test.tsx", + // The primary-environment shell factory, which the fork's every-workspace-remote atom replaces. + "apps/web/src/state/shell.test.ts", ], // Relay: no relay, Tailscale, or SSH transport. relay: [ @@ -391,6 +404,10 @@ const DELETED_PATHS = { "scripts/check-changed.ts", "scripts/dev-runner.ts", "scripts/dev-runner.test.ts", + // Startup profiling (#28566) preloads into upstream's dev runner and CLI, neither carried. + "scripts/profile-startup.mjs", + "scripts/profile-startup-modules.mjs", + "scripts/profile-startup.test.ts", // Upstream's ChatMarkdown browser test, which the fork has not carried since its first commit. "apps/web/src/components/ChatMarkdown.browser.test.tsx", // CodeRabbit's configuration and upstream's MCP tool-use evals.