diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 583cbe7098e15..69ef04feb4f2f 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -18,6 +18,7 @@ import { type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { deriveThreadCheckpointSummaries } from "@t3tools/client-runtime/state/thread-checkpoints"; +import { summarizeToolGroup } from "@t3tools/client-runtime/work-log/presentation"; import { getReviewSectionIdForCheckpoint } from "../features/review/reviewModel"; import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; @@ -596,6 +597,24 @@ describe("buildThreadFeed", () => { expect(items[0]).toMatchObject({ output: rawOutput }); }); + it("counts every file of a multi-file patch", () => { + const item: OrchestrationV2TurnItem = { + ...base("multi-file-change", "2026-06-20T00:00:04.000Z", 3), + type: "file_change", + fileName: "src/a.ts", + changes: [ + { operation: "update", path: "src/a.ts" }, + { operation: "add", path: "src/b.ts" }, + { operation: "update", path: "src/renamed.ts", oldPath: "src/original.ts" }, + ], + }; + const activity = buildThreadFeed([projected(item, 0)]).flatMap((entry) => + entry.type === "activity-group" ? entry.activities : [], + )[0]!; + expect(workEntryRowLabel(activity.workEntry)).toBe("src/a.ts +2 more"); + expect(summarizeToolGroup([activity.workEntry]).summary).toBe("Changed 3 files"); + }); + it("anchors feedback before later committed turns", () => { const laterUser = { ...userMessage("2026-08-29T00:00:05.000Z"), diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 91681731aab16..8cb5ccb043794 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -733,7 +733,7 @@ function toWorkLogEntry( case "file_change": return { ...common, - changedFiles: [item.fileName], + changedFiles: item.changes?.map((change) => change.path) ?? [item.fileName], toolTitle: title ?? "File change", toolData: item, }; diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 3c1f225ca35f7..ff43a8641461e 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -20,6 +20,7 @@ import * as PlatformError from "effect/PlatformError"; import * as Result from "effect/Result"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { ChildProcessSpawner } from "effect/process"; import { expect } from "vite-plus/test"; import type { @@ -1077,6 +1078,78 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("a settled branch PR is rechecked only when the branch moves or every 15 minutes", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + const remoteDir = yield* createBareRemote(); + yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]); + yield* runGit(repoDir, ["push", "-u", "origin", "main"]); + yield* runGit(repoDir, ["checkout", "-b", "feature/settled"]); + yield* runGit(repoDir, ["push", "-u", "origin", "feature/settled"]); + const pullRequest = (number: number, state: "open" | "merged"): FakeChangeRequest => ({ + number, + title: "Settled", + url: `https://github.com/pingdotgg/codething-mvp/pull/${number}`, + baseRefName: "main", + headRefName: "feature/settled", + state, + updatedAt: `2026-04-0${number}T15:00:00Z`, + }); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ + gitCommands, + providerScenario: { + prListSequence: [ + [pullRequest(1, "merged")], + [pullRequest(1, "merged")], + [pullRequest(1, "merged")], + ], + prListOtherwise: [pullRequest(2, "open")], + }, + }); + const lookup = manager.branchPullRequest({ cwd: repoDir, branch: "feature/settled" }); + const freshLookups = () => gitCommands.filter((args) => args === "remote").length; + + expect((yield* lookup)?.state).toBe("merged"); + gitCommands.length = 0; + expect((yield* lookup)?.state).toBe("merged"); + expect((yield* lookup)?.state).toBe("merged"); + expect(gitCommands.map((args) => args.split(" ", 1)[0]).toSorted()).toEqual([ + "config", + "config", + "for-each-ref", + "for-each-ref", + ]); + expect(freshLookups()).toBe(0); + + NodeFS.writeFileSync(NodePath.join(repoDir, "settled.txt"), "new work\n"); + yield* runGit(repoDir, ["add", "settled.txt"]); + yield* runGit(repoDir, ["commit", "-m", "New work"]); + gitCommands.length = 0; + expect((yield* lookup)?.state).toBe("merged"); + expect(freshLookups()).toBe(1); + gitCommands.length = 0; + yield* lookup; + expect(freshLookups()).toBe(0); + + // Remembered git state expires after 5 minutes; that rereads git without a recheck. + yield* TestClock.adjust("10 minutes"); + gitCommands.length = 0; + expect((yield* lookup)?.state).toBe("merged"); + expect(freshLookups()).toBe(1); + + yield* TestClock.adjust("5 minutes"); + gitCommands.length = 0; + expect((yield* lookup)?.state).toBe("merged"); + expect(freshLookups()).toBe(2); + + // A new PR from the reused branch shows on the next host query. + yield* TestClock.adjust("5 minutes"); + expect((yield* lookup)?.number).toBe(2); + }), + ); + it.effect("branch PR lookup uses a saved tracked branch without changing checkout", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index d1f48bfed3681..993eff3a35f54 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -171,6 +171,7 @@ const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20); const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15); const PR_LOOKUP_CACHE_CAPACITY = 2_048; const PR_LOOKUP_GIT_STATE_TTL = Duration.minutes(5); +const SETTLED_PR_LOOKUP_RECHECK_INTERVAL = Duration.minutes(15); const PR_THREAD_CONTEXT_BYTES = 16_000; const PR_THREAD_COMMAND_OUTPUT_CHARS = 2_000; const isSourceControlProviderError = Schema.is(SourceControlProviderError); @@ -2425,6 +2426,10 @@ export const make = Effect.gen(function* () { prLookupGitStateByKey.set(entryKey, { readAtMs, value }); return value; }); + const settledPrLookupByBranchKey = new Map< + string, + { readonly url: string; readonly fingerprint: string; readonly confirmedAtMs: number } + >(); const forgetPrLookupGitState = (cwd: string) => normalizeStatusCacheKey(cwd).pipe( Effect.map((cacheCwd) => { @@ -2470,6 +2475,39 @@ export const make = Effect.gen(function* () { }; }, ); + // objectname lets a settled PR result notice new commits on its branch. + const readPrLookupBranchRef = (cacheCwd: string, branch: string, fresh: boolean) => + rememberPrLookupGitState( + cacheCwd, + `branchRef\u0000${branch}`, + fresh, + gitCore + .execute({ + operation: "GitManager.branchPullRequest.branchRef", + cwd: cacheCwd, + args: [ + "for-each-ref", + "--format=%(refname)%00%(upstream:short)%00%(upstream:remotename)%00%(upstream:remoteref)%00%(objectname)", + `refs/heads/${branch}`, + ], + }) + .pipe(Effect.map((result) => result.stdout)), + ); + const readSettledPrLookupFingerprint = (cacheCwd: string, branch: string) => + Effect.all( + [ + readPrLookupBranchRef(cacheCwd, branch, true), + gitCore + .execute({ + operation: "GitManager.branchPullRequest.remoteUrls", + cwd: cacheCwd, + args: ["config", "--get-regexp", "^remote\\..*\\.url$"], + allowNonZeroExit: true, + }) + .pipe(Effect.map((result) => result.stdout)), + ], + { concurrency: "unbounded" }, + ).pipe(Effect.map((parts) => parts.join("\u0000"))); const lookupBranchPullRequest = Effect.fn("lookupBranchPullRequest")(function* ( cacheCwd: string, branch: string, @@ -2493,20 +2531,7 @@ export const make = Effect.gen(function* () { .filter((remoteName) => remoteName.length > 0); const [firstRemoteName] = remoteNames; if (firstRemoteName === undefined) return null; - const branchRef = yield* remember( - `branchRef\u0000${branch}`, - gitCore - .execute({ - operation: "GitManager.branchPullRequest.branchRef", - cwd: cacheCwd, - args: [ - "for-each-ref", - "--format=%(refname)%00%(upstream:short)%00%(upstream:remotename)%00%(upstream:remoteref)", - `refs/heads/${branch}`, - ], - }) - .pipe(Effect.map((result) => result.stdout)), - ); + const branchRef = yield* readPrLookupBranchRef(cacheCwd, branch, options.freshGitState); const expectedRefName = `refs/heads/${branch}`; const exactBranch = (branchRef ?? "") .split("\n") @@ -2657,10 +2682,38 @@ export const make = Effect.gen(function* () { freshGitState, }); if (pullRequest === null || pullRequest.state === "open" || freshGitState) return pullRequest; - return yield* lookupBranchPullRequest(cacheCwd, branch, { + // A confirmed closed or merged result stays final until the branch or remotes change, + // with a periodic fresh lookup so a new PR from a reused branch still shows up. + const settledKey = `${cacheCwd}\u0000${branch}`; + const now = yield* Clock.currentTimeMillis; + const settled = settledPrLookupByBranchKey.get(settledKey); + // Read before any fresh lookup, so a change made during it forces another one. + const fingerprint = yield* readSettledPrLookupFingerprint(cacheCwd, branch); + if ( + settled !== undefined && + settled.url === pullRequest.url && + settled.fingerprint === fingerprint && + now - settled.confirmedAtMs < Duration.toMillis(SETTLED_PR_LOOKUP_RECHECK_INTERVAL) + ) { + return pullRequest; + } + const confirmed = yield* lookupBranchPullRequest(cacheCwd, branch, { refresh: false, freshGitState: true, }); + settledPrLookupByBranchKey.delete(settledKey); + if (confirmed !== null && confirmed.state !== "open") { + if (settledPrLookupByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY) { + const oldestKey = settledPrLookupByBranchKey.keys().next().value; + if (oldestKey !== undefined) settledPrLookupByBranchKey.delete(oldestKey); + } + settledPrLookupByBranchKey.set(settledKey, { + url: confirmed.url, + fingerprint, + confirmedAtMs: now, + }); + } + return confirmed; }); const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn( "invalidateLocalStatus", diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 9b010fdffa031..4506d78514a6d 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -144,6 +144,7 @@ const RPC_AGGREGATES = { [WS_METHODS.sourceControlSignInCancel]: "source-control", [WS_METHODS.sourceControlAppAccess]: "source-control", [WS_METHODS.sourceControlStarred]: "source-control", + [WS_METHODS.sourceControlStar]: "source-control", [WS_METHODS.projectCloneStart]: "source-control", [WS_METHODS.projectCloneCancel]: "source-control", [WS_METHODS.projectCloneRetry]: "source-control", diff --git a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts index c4068702e3a57..71d9cf3dadaf9 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts @@ -137,6 +137,19 @@ describe("handoff budget", () => { assert.equal(command?.kind, "command_execution"); assert.include(command!.text, "Exit code: 1"); assert.include(command!.text, "界".repeat(300)); + assert.equal( + historicalMessage({ + ...base, + type: "file_change", + fileName: "src/a.ts", + changes: [ + { operation: "update", path: "src/a.ts" }, + { operation: "add", path: "src/b.ts" }, + { operation: "update", path: "src/new.ts", oldPath: "src/old.ts" }, + ], + })?.text, + "File change: src/a.ts, src/b.ts, src/new.ts", + ); assert.isNull( historicalMessage({ ...base, diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts index 0282819d81b56..78958c2e317d5 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.test.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.test.ts @@ -210,6 +210,36 @@ it.effect("caps the side chat context block without summarizing discarded parent }); assert.isTrue(framingOnly.startsWith("You are in a side chat beside the main thread.")); assert.notInclude(framingOnly, "Main thread activity"); + + const multiFilePatch = ContextHandoffService.makeSideChatContext({ + parentThreadId, + digest: [ + { + id: TurnItemId.make("turn-item:patch"), + threadId: parentThreadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 60, + status: "completed", + title: null, + startedAt: null, + completedAt: null, + updatedAt: DateTime.makeUnsafe(0), + type: "file_change", + fileName: "src/a.ts", + changes: [ + { operation: "update", path: "src/a.ts" }, + { operation: "add", path: "src/b.ts" }, + { operation: "update", path: "src/new.ts", oldPath: "src/old.ts" }, + ], + }, + ], + }); + assert.include(multiFilePatch, "- File change: src/a.ts, src/b.ts, src/new.ts"); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/ContextHandoffService.ts b/apps/server/src/orchestration-v2/ContextHandoffService.ts index dcfffa018c8c0..10f2701446268 100644 --- a/apps/server/src/orchestration-v2/ContextHandoffService.ts +++ b/apps/server/src/orchestration-v2/ContextHandoffService.ts @@ -213,7 +213,7 @@ function summarizeDeltaItem(item: OrchestrationV2TurnItem): string | null { case "command_execution": return `- Command: ${compactText(item.input)}`; case "file_change": - return `- File change: ${item.fileName}`; + return `- File change: ${compactText(item.changes?.map((change) => change.path).join(", ") ?? item.fileName)}`; case "checkpoint": return `- Checkpoint: ${item.files.length} files`; case "handoff": diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index cabc322d31331..3f0f9cf0342ee 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -158,7 +158,7 @@ const seedParentWithTerminalTask = (input: { readonly runId: RunId; readonly rootNodeId: NodeId; readonly taskId: NodeId; - readonly deliveryState: "delivered" | "claimed" | "acknowledged" | "disposed"; + readonly deliveryState: "pending" | "delivered" | "claimed" | "acknowledged" | "disposed"; readonly completionWake?: "always" | "settled_only"; readonly deliveryTaskIds?: ReadonlyArray; readonly parentRunStatus?: "running" | "completed"; @@ -1049,6 +1049,7 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { { command: "acknowledge", before: "running", after: "failed", capture: false }, { command: "acknowledge", before: "waiting", after: "completed", capture: true }, { command: "accept", before: "waiting", after: "completed", capture: true }, + { command: "wake-policy", before: "running", after: "completed", capture: true }, ] as const)( "keeps a $after run that settled between $command's read and commit", ({ command, before, after, capture }) => @@ -1062,14 +1063,20 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { const taskId = NodeId.make(`node:${race}-task`); const checkpointId = CheckpointId.make(`checkpoint:${race}`); const messageId = MessageId.make(`message:delegated-delivery:${threadId}`); + const commandType = { + acknowledge: "delegated_task.completion-delivery.acknowledge", + accept: "notification.delivery.accept", + "wake-policy": "delegated_task.wake-policy", + }[command]; yield* seedParentWithTerminalTask({ threadId, projectId: ProjectId.make(`project:${race}`), runId, rootNodeId: NodeId.make(`node:${race}-root`), taskId, - deliveryState: "claimed", - deliveryTaskIds: [taskId], + ...(command === "wake-policy" + ? { deliveryState: "pending" } + : { deliveryState: "claimed", deliveryTaskIds: [taskId] }), now, }); const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; @@ -1110,18 +1117,18 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { const { delegatedCompletion: _cohort, ...settledRun } = parent; const commit = sink.commitCommand; let settled = false; + let planned: OrchestrationV2Run["delegatedCompletion"]; yield* Effect.acquireUseRelease( Effect.sync(() => vi.spyOn(sink, "commitCommand").mockImplementation((input) => Effect.gen(function* () { - if ( - !settled && - input.commandType === - (command === "accept" - ? "notification.delivery.accept" - : "delegated_task.completion-delivery.acknowledge") - ) { + if (!settled && input.commandType === commandType) { settled = true; + const plannedRun = input.events.find((event) => event.type === "run.updated"); + planned = + plannedRun?.type === "run.updated" + ? plannedRun.payload.delegatedCompletion + : undefined; // The provider turn ends (or its checkpoint lands) after the command read the run. yield* commit({ commandId: CommandId.make(`command:${race}`), @@ -1159,13 +1166,21 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { threadId, messageId, } - : { - type: "delegated_task.completion-delivery.acknowledge", - commandId: CommandId.make(`command:${race}:task-status`), - parentThreadId: threadId, - taskId, - observedByRunId: runId, - }, + : command === "wake-policy" + ? { + type: "delegated_task.wake-policy", + commandId: CommandId.make(`command:${race}:wake-policy`), + parentThreadId: threadId, + taskId, + completionWake: "always", + } + : { + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make(`command:${race}:task-status`), + parentThreadId: threadId, + taskId, + observedByRunId: runId, + }, ), (spy) => Effect.sync(() => spy.mockRestore()), ); @@ -1173,12 +1188,22 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { const finished = yield* orchestrator.getThreadProjection(threadId); assert.equal( finished.subagents.find((row) => row.id === taskId)?.completionDelivery?.state, - command === "accept" ? "delivered" : "acknowledged", + { acknowledge: "acknowledged", accept: "delivered", "wake-policy": "claimed" }[command], ); const run = finished.runs.find((candidate) => candidate.id === runId)!; assert.deepEqual( - { status: run.status, completedAt: run.completedAt, checkpointId: run.checkpointId }, - { status: after, completedAt: now, checkpointId: capture ? checkpointId : null }, + { + status: run.status, + completedAt: run.completedAt, + checkpointId: run.checkpointId, + delegatedCompletion: run.delegatedCompletion, + }, + { + status: after, + completedAt: now, + checkpointId: capture ? checkpointId : null, + delegatedCompletion: planned, + }, ); }), ); diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 461a6801e3a26..5ba9befef1b8b 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -279,6 +279,10 @@ export const layerExecutor: Layer.Layer< const message = projection.messages.find((item) => item.id === messageId); const run = projection.runs.find((item) => item.id === message?.runId); if (message === undefined || run === undefined) return yield* error; + // Notifications must be queued messages. + const queued = + message.delegatedCompletion !== undefined || + message.notification !== undefined; // Reuse message ids and receipts so retries cannot duplicate messages or follow-ups. yield* threads .dispatch({ @@ -293,10 +297,7 @@ export const layerExecutor: Layer.Layer< ? {} : { modelSelection: run.modelSelection }), dispatchMode: { - type: - message.delegatedCompletion === undefined - ? "start_immediately" - : "queue_after_active", + type: queued ? "queue_after_active" : "start_immediately", }, createdBy: message.createdBy, creationSource: message.creationSource, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 9731de8813d95..42f48f37419ce 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4734,6 +4734,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"]; readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"]; readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"]; + readonly notification?: OrchestrationV2ConversationMessage["notification"]; readonly forceRestart: boolean; }) { const targetRun = input.projection.runs.find((candidate) => candidate.id === input.targetRunId); @@ -4887,6 +4888,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(input.delegatedCompletion === undefined ? {} : { delegatedCompletion: input.delegatedCompletion }), + ...(input.notification === undefined ? {} : { notification: input.notification }), ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }), @@ -4988,6 +4990,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio input.projection.thread.providerInstanceId !== input.modelSelection.instanceId; if ( input.delegatedCompletion === undefined && + input.notification === undefined && (instanceChanged || !modelSelectionsEqual(input.projection.thread.modelSelection, input.modelSelection)) ) { @@ -5774,13 +5777,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio taskIds: delivery.taskIds, }; } - // Route durable mailbox deliveries under the thread lock, using the live - // session's capabilities. Never interrupt/restart a turn for a notification. + // Route durable mailbox deliveries and delegated task questions under the + // thread lock, using the live session's capabilities. A question queued + // behind a long parent turn is never seen. Never interrupt/restart a turn + // for a notification. if ( - delegatedCompletion !== undefined && - delegatedCompletion.taskIds.every( - (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always", - ) + delegatedCompletion !== undefined + ? delegatedCompletion.taskIds.every( + (id) => + projection.subagents.find((task) => task.id === id)?.completionWake === "always", + ) + : command.notification?.source.kind === "delegated_task" ) { const active = projection.runs.find((run) => run.status === "running"); const providerThread = projection.providerThreads.find( @@ -5804,7 +5811,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if ( Option.isSome(session) && session.value.providerSession.capabilities.turns.supportsActiveSteering && - session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true + session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true && + !(yield* stopReachedRun(command, command.threadId, active.id)) ) { dispatchMode = { type: "steer_active", targetRunId: active.id }; } @@ -5871,11 +5879,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio effects, projection, modelSelection: - delegatedCompletion === undefined + delegatedCompletion === undefined && command.notification === undefined ? modelSelection : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)?.modelSelection ?? modelSelection), delegatedCompletion, + ...(command.notification === undefined ? {} : { notification: command.notification }), targetRunId: dispatchMode.targetRunId, messageId: command.messageId, text: dispatchText, @@ -7310,7 +7319,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(command.context ? { context: command.context } : {}), attachments: command.attachments, ...(run.contextHandoffId === null - ? modelSwitchSince(projection, modelSelection, sourceRun?.modelSelection) + ? modelSwitchSince( + projection, + modelSelection, + // Side chats do not show the parent's runs. + sideChatFork ? undefined : sourceRun?.modelSelection, + ) : {}), }; const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff; @@ -8617,6 +8631,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: completionPlan.message, }); } + return completionPlan.parentRun?.id; }); const dispatchCreatedThreadRecord = Effect.fn("orchestrationV2.dispatch.createdThreadRecord")( @@ -13433,7 +13448,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* dispatchRemoteDelegatedTaskStop(command, events); break; case "delegated_task.wake-policy": - yield* dispatchDelegatedTaskWakePolicy(command, events); + updateDelegatedCompletionOnlyRunId = yield* dispatchDelegatedTaskWakePolicy( + command, + events, + ); break; case "delegated_task.completion-delivery.acknowledge": case "delegated_task.completion-delivery.dispose": diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index e570c3ad81055..bd3f4e5b2e7d8 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -44,13 +44,16 @@ it.effect.each( [true, "with interrupting native steering"], [true, "settled only"], [false, "during continuation"], + ["question", "during delivery"], ] as const - ).map(([mailbox, timing]) => ({ - mailbox, + ).map(([kind, timing]) => ({ + mailbox: kind === true, + question: kind === "question", timing, - label: mailbox ? "mailbox notification" : "steering", + label: + kind === "question" ? "delegated task question" : kind ? "mailbox notification" : "steering", })), -)("delivers $label when completion wins $timing", ({ mailbox, timing }) => +)("delivers $label when completion wins $timing", ({ mailbox, question, timing }) => Effect.scoped( Effect.gen(function* () { const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`); @@ -255,6 +258,21 @@ it.effect.each( ], }); } + if (question) { + const { thread } = yield* orchestrator.getThreadProjection(threadId); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:composer-selection"), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: instanceId, + occurredAt: yield* DateTime.now, + payload: { ...thread, modelSelection: composerSelection }, + }, + ], + }); + } const dispatchSteer = orchestrator.dispatch({ type: "message.dispatch", commandId: CommandId.make("steer"), @@ -270,11 +288,21 @@ it.effect.each( sizeBytes: 10, }, ], - dispatchMode: mailbox - ? { type: "queue_after_active" } - : { type: "steer_active", targetRunId: first.runId }, - createdBy: mailbox ? "agent" : "user", - creationSource: mailbox ? "server" : "web", + dispatchMode: + mailbox || question + ? { type: "queue_after_active" } + : { type: "steer_active", targetRunId: first.runId }, + createdBy: mailbox || question ? "agent" : "user", + creationSource: mailbox || question ? "server" : "web", + ...(question + ? { + notification: { + source: { kind: "delegated_task", taskIds: [taskId] }, + outcome: "updated", + summary: "Delegated task has a question", + }, + } + : {}), ...(mailbox ? { delegatedCompletion: { @@ -340,6 +368,8 @@ it.effect.each( if (delivery !== null) { yield* Deferred.succeed(rejectSteer, undefined); yield* Fiber.join(delivery); + } + if (delivery !== null && !question) { const requeued = yield* orchestrator.getThreadProjection(threadId); const item = requeued.turnItems.find( (item) => item.type === "user_message" && item.messageId === messageId, @@ -399,7 +429,11 @@ it.effect.each( ]); assert.equal(steerCalls, timing === "during delivery" ? 1 : 0); const final = yield* orchestrator.getThreadProjection(threadId); - if (!mailbox) { + if (question) { + assert.deepEqual(final.thread.modelSelection, composerSelection); + assert.deepEqual(started[1]?.modelSelection, composerSelection); + } + if (!mailbox && !question) { assert.equal( final.turnItems.find( (item) => item.type === "user_message" && item.messageId === messageId, @@ -414,7 +448,7 @@ it.effect.each( ); assert.equal( final.turnItems.filter((item) => - mailbox + mailbox || question ? item.type === "notification" : item.type === "user_message" && item.messageId === messageId, ).length, @@ -617,6 +651,65 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* return { cwd, events, started, steered, interrupted, layer, startFirstTurn }; }); +it.effect("steers a delegated task question notice into the running parent turn", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "delegated-question-steer", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const { thread } = yield* orchestrator.getThreadProjection(threadId); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:composer-selection"), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: instanceId, + occurredAt: yield* DateTime.now, + payload: { ...thread, modelSelection: composerSelection }, + }, + ], + }); + const messageId = MessageId.make("message:delegated-task-question:child-question"); + const notification = { + source: { + kind: "delegated_task" as const, + taskIds: [NodeId.make("task:question")], + childThreadId: ThreadId.make("thread:question-child"), + }, + outcome: "updated" as const, + summary: "Delegated task has a question", + }; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("question-wake"), + threadId, + messageId, + text: "Delegated task asked a question", + notification, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["Delegated task asked a question"]); + assert.lengthOf(started, 1); + assert.isFalse(after.runs.some((run) => run.status === "queued")); + const message = after.messages.find((candidate) => candidate.id === messageId); + assert.equal(message?.runId, started[0]?.runId); + assert.deepEqual(message?.notification, notification); + assert.deepEqual(after.thread.modelSelection, composerSelection); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("sends a selected held message once and preserves the remaining queue order", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts index 96c7263173f32..d955755e92122 100644 --- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts +++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts @@ -852,7 +852,11 @@ const forkSideChat = (commandId: string, sourceThreadId: ThreadId, targetThreadI }); }); -const askSideChat = (threadId: ThreadId, commandId: string) => +const askSideChat = ( + threadId: ThreadId, + commandId: string, + modelSelection?: (typeof forkCases)[number]["modelSelection"], +) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; yield* orchestrator.dispatch({ @@ -862,6 +866,7 @@ const askSideChat = (threadId: ThreadId, commandId: string) => messageId: MessageId.make(commandId), text: "What is the main thread doing?", attachments: [], + ...(modelSelection === undefined ? {} : { modelSelection }), dispatchMode: { type: "start_immediately" }, createdBy: "user", creationSource: "web", @@ -954,10 +959,17 @@ it.effect("a side chat of an idle parent still starts with the framing note", () query.includes("FROM orchestration_v2_projection_context_transfers"), ), ); - yield* askSideChat(sideChatId, "side-chat-idle-first-message"); + yield* askSideChat(sideChatId, "side-chat-idle-first-message", { + ...forkCases[0]!.modelSelection, + model: "side-chat-model", + }); const started = yield* orchestrator.getThreadProjection(sideChatId); assert.isNotNull(started.providerThreads[0]?.forkedFrom); + // The side chat does not show the parent's run, so it is no baseline. + assert.isFalse( + started.turnItems.some((item) => item.type === "user_message" && item.modelSwitch), + ); assert.lengthOf(started.contextHandoffs, 1); const [handoff] = started.contextHandoffs; assert.isTrue( diff --git a/apps/server/src/sourceControl/SourceControlSignIn.ts b/apps/server/src/sourceControl/SourceControlSignIn.ts index 3dd9ca03e2062..31f7837322fec 100644 --- a/apps/server/src/sourceControl/SourceControlSignIn.ts +++ b/apps/server/src/sourceControl/SourceControlSignIn.ts @@ -28,6 +28,7 @@ export class SourceControlSignIn extends Context.Service< ) => Effect.Effect; readonly access: (input: SourceControlAppAccessInput) => Effect.Effect; readonly starred: (input: SourceControlStarredInput) => Effect.Effect; + readonly star: (input: SourceControlStarredInput) => Effect.Effect; } >()("t3/sourceControl/SourceControlSignIn") {} @@ -70,6 +71,11 @@ const make = Effect.gen(function* () { .isRepositoryStarred; return isStarred === undefined ? false : yield* isStarred(input.host, input.repository); }), + star: Effect.fn("SourceControlSignIn.star")(function* (input) { + const star = drivers.find(({ driver }) => driver.kind === input.provider)?.instance + .starRepository; + return star === undefined ? false : yield* star(input.host, input.repository); + }), }); }); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index b76dff11362e8..9ed56cf0c9728 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2849,12 +2849,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("reads range patches from source without textconv or color", () => + it.effect("reads range patches from source without textconv, color, or diff.relative", () => 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, ["config", "color.ui", "always"]); + yield* git(cwd, ["config", "diff.relative", "true"]); yield* git(cwd, ["checkout", "-b", "feature/range"]); yield* writeTextFile(cwd, ".gitattributes", "*.doc diff=probe\n"); yield* writeTextFile(cwd, "notes.doc", "source line\n"); @@ -2864,8 +2865,10 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* git(cwd, ["commit", "-m", "range files"]); const driver = yield* GitVcsDriver.GitVcsDriver; const fileSystem = yield* FileSystem.FileSystem; + const projectCwd = `${cwd}/app`; + yield* fileSystem.makeDirectory(projectCwd); - const context = yield* driver.readRangeContext(cwd, initialBranch); + const context = yield* driver.readRangeContext(projectCwd, initialBranch); assert.include(context.diffPatch, "+source line"); assert.notInclude(context.diffPatch, "converted"); @@ -2878,7 +2881,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { 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"]); + const staged = yield* driver.prepareCommitContext(projectCwd, ["notes.doc"]); assert.include(staged?.stagedPatch ?? "", "+updated source line"); assert.notInclude(staged?.stagedPatch ?? "", "converted"); assert.notInclude(staged?.stagedPatch ?? "", "\u001b["); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 7db5190ed1397..b804a2a9d5b93 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2537,7 +2537,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const stagedSummary = yield* runGitStdoutWithOptions( "GitVcsDriver.prepareCommitContext.stagedSummary", cwd, - ["diff", "--cached", "--name-status"], + // cwd can be a subdirectory; diff.relative would hide changes outside it. + ["-c", "diff.relative=false", "diff", "--cached", "--name-status"], { env, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ).pipe(Effect.map((stdout) => stdout.trim())); if (stagedSummary.length === 0) { @@ -2551,6 +2552,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "GitVcsDriver.prepareCommitContext.stagedPatch", cwd, [ + "-c", + "diff.relative=false", "diff", "--no-color", "--no-ext-diff", @@ -2970,7 +2973,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* runGitStdoutWithOptions( "GitVcsDriver.readRangeContext.diffStat", cwd, - ["diff", "--stat", "--no-color", "--end-of-options", diffRange], + [ + "-c", + "diff.relative=false", + "diff", + "--stat", + "--no-color", + "--end-of-options", + diffRange, + ], { maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, appendTruncationMarker: true, @@ -2980,6 +2991,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "GitVcsDriver.readRangeContext.diffPatch", cwd, [ + "-c", + "diff.relative=false", "diff", "--no-color", "--no-ext-diff", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e736dd15de680..966f78ea79880 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2763,6 +2763,7 @@ export const layerWsRpc = ( [WS_METHODS.sourceControlSignInCancel]: (input) => sourceControlSignIn.cancel(input), [WS_METHODS.sourceControlAppAccess]: (input) => sourceControlSignIn.access(input), [WS_METHODS.sourceControlStarred]: (input) => sourceControlSignIn.starred(input), + [WS_METHODS.sourceControlStar]: (input) => sourceControlSignIn.star(input), [WS_METHODS.projectCloneStart]: (input) => projectCloneTracker.start(input, { createProject: (project) => diff --git a/apps/web/package.json b/apps/web/package.json index a0d6023f0d6f4..ea936e6eb113e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -56,6 +56,7 @@ "@tiptap/pm": "^3.31.3", "@tiptap/react": "^3.31.3", "@tiptap/starter-kit": "^3.31.3", + "canvas-confetti": "1.9.4", "class-variance-authority": "^0.7.1", "culori": "^4.0.2", "dompurify": "^3.4.16", @@ -99,6 +100,7 @@ "@effect/vitest": "catalog:", "@tailwindcss/vite": "^4.0.0", "@tanstack/router-plugin": "^1.161.0", + "@types/canvas-confetti": "1.9.0", "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 59b355885a9f6..eddcfb67c5ab8 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -177,7 +177,6 @@ import { GuestPendingMessages } from "./chat/GuestShareControls"; import { useDeviceState } from "~/state/device"; import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar"; import { ComposerContextPermissions } from "./ComposerContextPermissions"; -import { resolveCompatibleRuntimeMode } from "./chat/runtimeModeConfig"; import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; import { isEditableFocused } from "../lib/editableFocus"; import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings"; @@ -1838,9 +1837,6 @@ export default function ChatView(props: ChatViewProps) { }); }; const scheduleComposerFocusStable = useStableCallback(scheduleComposerFocus); - const openComposerPermissionsStable = useStableCallback(() => - composerRef.current?.openControl("composer.mode"), - ); const insertArtifactTemplate = (template: CodexArtifactTemplate) => { const composer = composerRef.current; if (!composer) return; @@ -3367,6 +3363,7 @@ export default function ChatView(props: ChatViewProps) { {isWorkspaceFileDragActive ? : null} ), })} diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index 3883a3e2258e9..9faeab83c6ffc 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -1,13 +1,28 @@ -import { describe, expect, it } from "vite-plus/test"; +import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; import { render } from "../../test/render"; import { openCommandPalette } from "../commandPaletteBus"; import { useCommandPaletteStore } from "../commandPaletteStore"; +import { makeThreadFixture } from "../test-fixtures"; +import type { Project, Thread } from "../types"; import { CommandPalette } from "./CommandPalette"; -function setup() { +const entities = vi.hoisted(() => ({ + projects: [] as ReadonlyArray, + threads: [] as ReadonlyArray, +})); +vi.mock("../state/entities", async (original) => ({ + ...(await original()), + useProjects: () => entities.projects, + useVisibleThreadShells: () => entities.threads, +})); + +function setup(state: { projects?: ReadonlyArray; threads?: ReadonlyArray } = {}) { useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true); + entities.projects = state.projects ?? []; + entities.threads = state.threads ?? []; } describe("CommandPalette open intents", () => { @@ -30,4 +45,50 @@ describe("CommandPalette open intents", () => { await expect.element(input).toHaveFocus(); await expect.element(input).toHaveValue("acme"); }); + + it("opens a searched project's latest listed thread, not a newer subagent", async () => { + const environmentId = EnvironmentId.make("local"); + const projectId = ProjectId.make("acme"); + const parentId = ThreadId.make("parent"); + setup({ + projects: [ + { + id: projectId, + environmentId, + title: "Acme", + workspaceRoot: "/work/acme", + repositoryIdentity: null, + defaultModelSelection: null, + createdAt: "2026-03-01T00:00:00.000Z", + updatedAt: "2026-03-01T00:00:00.000Z", + scripts: [], + }, + ], + threads: [ + makeThreadFixture({ + id: parentId, + environmentId, + projectId, + latestUserMessageAt: "2026-03-02T00:00:00.000Z", + }), + makeThreadFixture({ + id: ThreadId.make("subagent"), + environmentId, + projectId, + updatedAt: "2026-03-03T00:00:00.000Z", + lineage: { + rootThreadId: parentId, + parentThreadId: parentId, + relationshipToParent: "subagent", + }, + }), + ], + }); + await using screen = await render({null}); + + openCommandPalette({ query: "Acme" }); + await page.getByRole("option", { name: /Acme/ }).first().click(); + + await vi.waitFor(() => expect(screen.router?.state.location.pathname).toBe("/local/parent")); + }); }); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 2e729a5d61468..4caf1bc768d99 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -213,6 +213,7 @@ import { type SearchOverlayMode, } from "./CommandPalette.logic"; import { resolveEnvironmentOptionLabel } from "./BranchToolbar.logic"; +import { isSidebarHiddenThread } from "./Sidebar.logic"; import { CommandPaletteContent } from "./CommandPaletteContent"; import { selectCommandPaletteClientSettings, @@ -496,7 +497,8 @@ function OpenCommandPaletteDialog(props: { if (activeThreadReferenceCopyTarget === null) return; await copyThreadReference(activeThreadReferenceCopyTarget); }; - const threads = useVisibleThreadShells(); + // Side chats and subagents open inside their parent, so opening a project never lands on one. + const threads = useVisibleThreadShells().filter((thread) => !isSidebarHiddenThread(thread)); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const providersByEnvironment = useEnvironmentProviders(); const { changeThemeItem, changeAppearanceItem, themeEditorItem } = useCommandPaletteThemeItems(); diff --git a/apps/web/src/components/ComposerContextPermissions.tsx b/apps/web/src/components/ComposerContextPermissions.tsx index b4ac2a2eb6983..688968f9bca53 100644 --- a/apps/web/src/components/ComposerContextPermissions.tsx +++ b/apps/web/src/components/ComposerContextPermissions.tsx @@ -1,41 +1,67 @@ -import type { RuntimeMode } from "@t3tools/contracts"; +import type { EnvironmentId, RuntimeMode } from "@t3tools/contracts"; import { useAtomValue } from "@effect/atom-react"; import { shortcutLabelForCommand } from "../keybindings"; +import { useManagedPolicy } from "../state/managedPolicy"; import { primaryServerKeybindingsAtom } from "../state/server"; import { ComposerControl } from "./chat/ComposerControl"; -import { runtimeModeConfig } from "./chat/runtimeModeConfig"; +import { ComposerPermissionsSection } from "./chat/ComposerFooterControls"; +import { useComposerMenuProps } from "./chat/composerEventScope"; +import { + resolveCompatibleRuntimeMode, + resolveRuntimeModeOptions, + runtimeModeConfig, +} from "./chat/runtimeModeConfig"; import { ComposerContextLabel } from "./ComposerContextLabel"; +import { Menu, MenuPopup, MenuTrigger } from "./ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; -/** The new-thread strip names the permissions the first send will use; clicking opens them. */ export function ComposerContextPermissions(props: { + environmentId: EnvironmentId | null; runtimeMode: RuntimeMode; - onOpen: () => void; + supportedRuntimeModes: ReadonlyArray | undefined; + onRuntimeModeChange: (mode: RuntimeMode) => void; }) { const shortcutLabel = shortcutLabelForCommand( useAtomValue(primaryServerKeybindingsAtom), "composer.mode", ); - const { icon: Icon, label } = runtimeModeConfig[props.runtimeMode]; + const { mode, modes } = resolveCompatibleRuntimeMode( + props.runtimeMode, + props.supportedRuntimeModes, + ); + const options = resolveRuntimeModeOptions(modes, useManagedPolicy(props.environmentId)); + const composerMenuProps = useComposerMenuProps(); + const { icon: Icon, label } = runtimeModeConfig[mode]; return ( - - - } - > - - Permissions{shortcutLabel ? ` · ${shortcutLabel}` : null} - + + + + } + /> + } + > + + Permissions{shortcutLabel ? ` · ${shortcutLabel}` : null} + + + + + ); } diff --git a/apps/web/src/components/GitHubStarPrompt.test.ts b/apps/web/src/components/GitHubStarPrompt.test.ts index 9dbe023b2d56f..f748ec8b82209 100644 --- a/apps/web/src/components/GitHubStarPrompt.test.ts +++ b/apps/web/src/components/GitHubStarPrompt.test.ts @@ -3,29 +3,54 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { toastManager } from "./ui/toast"; -const { add, starred } = vi.hoisted(() => ({ +const { add, update, openExternal, commands, starred, page } = vi.hoisted(() => ({ add: vi.fn(), - starred: { value: false, failed: false, duringCheck: () => {} }, + update: vi.fn(), + openExternal: vi.fn(async (_url: string) => {}), + commands: { checkStarred: {}, star: {} }, + starred: { value: false, failed: false, starWorks: true, duringCheck: () => {} }, + page: { + focused: true, + activeElement: null as { matches: (selector: string) => boolean } | null, + events: new EventTarget(), + }, })); -vi.mock("./ui/toast", () => ({ toastManager: { add, close: vi.fn() } })); +vi.mock("./ui/toast", () => ({ toastManager: { add, update, close: vi.fn() } })); +vi.mock("../localApi", () => ({ readLocalApi: () => ({ shell: { openExternal } }) })); vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} })); -vi.mock("../state/sourceControl", () => ({ sourceControlEnvironment: { checkStarred: {} } })); +vi.mock("../state/sourceControl", () => ({ sourceControlEnvironment: commands })); vi.mock("@t3tools/client-runtime/state/runtime", () => ({ - runAtomCommand: async () => { + runAtomCommand: async (_registry: unknown, command: unknown) => { + if (command === commands.star) return { _tag: "Success", value: starred.starWorks }; starred.duringCheck(); return starred.failed ? { _tag: "Failure" } : { _tag: "Success", value: starred.value }; }, })); const environmentId = EnvironmentId.make("environment-1"); +const IDLE_MS = 30_000; function setup({ sent = 0, writable = true, alreadyStarred = false } = {}) { add.mockReset(); + update.mockReset(); + openExternal.mockClear(); starred.value = alreadyStarred; starred.failed = false; + starred.starWorks = true; starred.duringCheck = () => {}; + page.focused = true; + page.activeElement = null; + page.events = new EventTarget(); const store = new Map([["t3code:github-star-prompt:sent", String(sent)]]); + vi.stubGlobal("document", { + hasFocus: () => page.focused, + get activeElement() { + return page.activeElement; + }, + }); vi.stubGlobal("window", { + addEventListener: page.events.addEventListener.bind(page.events), + removeEventListener: page.events.removeEventListener.bind(page.events), localStorage: { getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { @@ -41,10 +66,48 @@ function setup({ sent = 0, writable = true, alreadyStarred = false } = {}) { async function startSession() { vi.resetModules(); const session = await import("./GitHubStarPrompt"); - return { send: () => session.recordPromptSent(environmentId) }; + return { + // Sends a prompt, then leaves the page idle long enough to ask. + send: async () => { + const sent = session.recordPromptSent(environmentId); + await vi.advanceTimersByTimeAsync(IDLE_MS); + await sent; + }, + sendWithoutWaiting: () => void session.recordPromptSent(environmentId), + }; } +// The toast's handlers ignore their click event. +const click = (props: unknown) => (props as { onClick: () => unknown }).onClick(); + describe("recordPromptSent", () => { + vi.useFakeTimers(); + + it("asks only after the focused page is idle", async () => { + setup({ sent: 5 }); + (await startSession()).sendWithoutWaiting(); + await vi.advanceTimersByTimeAsync(IDLE_MS - 1); + page.events.dispatchEvent(new Event("keydown")); + await vi.advanceTimersByTimeAsync(IDLE_MS - 1); + expect(add).not.toHaveBeenCalled(); + + page.focused = false; + await vi.advanceTimersByTimeAsync(IDLE_MS); + expect(add).not.toHaveBeenCalled(); + + page.focused = true; + page.activeElement = { matches: (selector) => selector.includes("iframe") }; + page.events.dispatchEvent(new Event("focus")); + await vi.advanceTimersByTimeAsync(IDLE_MS); + expect(add).not.toHaveBeenCalled(); + + page.activeElement = null; + page.events.dispatchEvent(new Event("pointerdown")); + await vi.advanceTimersByTimeAsync(IDLE_MS); + expect(add).toHaveBeenCalledOnce(); + vi.unstubAllGlobals(); + }); + it("asks after five prompts, once per session, and never again once closed", async () => { setup(); let session = await startSession(); @@ -101,4 +164,36 @@ describe("recordPromptSent", () => { expect(add).not.toHaveBeenCalled(); vi.unstubAllGlobals(); }); + it("stars on click, opens GitHub when starring fails, and asks for a click once the click expired", async () => { + const store = setup({ sent: 5 }); + await (await startSession()).send(); + click(add.mock.lastCall?.[0].actionProps); + await vi.advanceTimersByTimeAsync(0); + expect(update.mock.lastCall?.[1]).toMatchObject({ title: "Thanks for the star!" }); + expect(store.get("t3code:github-star-prompt:dismissed")).toBe("true"); + expect(openExternal).not.toHaveBeenCalled(); + + setup({ sent: 5 }); + starred.starWorks = false; + await (await startSession()).send(); + click(add.mock.lastCall?.[0].actionProps); + await vi.advanceTimersByTimeAsync(0); + expect(openExternal).toHaveBeenCalledWith("https://github.com/pingdotgg/t3code"); + expect(update.mock.lastCall?.[1]).not.toMatchObject({ + actionProps: { children: "Open GitHub" }, + }); + + setup({ sent: 5 }); + starred.starWorks = false; + vi.stubGlobal("navigator", { userActivation: { isActive: false } }); + await (await startSession()).send(); + click(add.mock.lastCall?.[0].actionProps); + await vi.advanceTimersByTimeAsync(0); + const fallback = update.mock.lastCall?.[1]; + expect(fallback).toMatchObject({ actionProps: { children: "Open GitHub" } }); + expect(openExternal).not.toHaveBeenCalled(); + click(typeof fallback === "object" ? fallback.actionProps : undefined); + expect(openExternal).toHaveBeenCalledOnce(); + vi.unstubAllGlobals(); + }); }); diff --git a/apps/web/src/components/GitHubStarPrompt.tsx b/apps/web/src/components/GitHubStarPrompt.tsx index db8ddb4de2035..679d61b1f3502 100644 --- a/apps/web/src/components/GitHubStarPrompt.tsx +++ b/apps/web/src/components/GitHubStarPrompt.tsx @@ -14,6 +14,9 @@ const SENT_KEY = "t3code:github-star-prompt:sent"; const DISMISSED_KEY = "t3code:github-star-prompt:dismissed"; const REPOSITORY = "pingdotgg/t3code"; const PROMPTS_BEFORE_ASKING = 5; +const IDLE_MS = 30_000; +// User-driven actions (send, navigate, type, scroll) start with one of these; touch fires pointerdown. +const ACTIVITY_EVENTS = ["pointerdown", "keydown", "wheel", "focus"] as const; let shownThisSession = false; @@ -24,22 +27,41 @@ function dismiss() { } // Every close path, including both buttons, runs `onClose`, which saves the dismissal. -function showStarPrompt() { +function showStarPrompt(environmentId: EnvironmentId) { const close = () => toastManager.close(id); + const openInBrowser = () => { + close(); + void readLocalApi() + ?.shell.openExternal(`https://github.com/${REPOSITORY}`) + .catch(() => undefined); + }; + const starInPlace = async () => { + toastManager.update(id, { actionProps: { children: "Starring…", disabled: true } }); + if (await starRepository(environmentId)) { + // Thank them in place: a closing and opening toast would slide under the confetti. + dismiss(); + toastManager.update(id, { + type: "success", + title: "Thanks for the star!", + description: "It really helps T3 Code grow.", + timeout: 5_000, + actionProps: undefined, + data: {}, + }); + celebrate(); + return; + } + // Browsers block new tabs once the click's activation expires; desktop opens through its bridge. + if (window.desktopBridge || navigator.userActivation?.isActive !== false) + return openInBrowser(); + toastManager.update(id, { actionProps: { children: "Open GitHub", onClick: openInBrowser } }); + }; const id = toastManager.add({ title: "Enjoying T3 Code?", description: "Give us a star on GitHub to let us know!", timeout: 0, onClose: dismiss, - actionProps: { - children: "Star on GitHub", - onClick: () => { - close(); - void readLocalApi() - ?.shell.openExternal(`https://github.com/${REPOSITORY}`) - .catch(() => undefined); - }, - }, + actionProps: { children: "Star on GitHub", onClick: () => void starInPlace() }, data: { actionLayout: "stacked-end", leadingIcon: , @@ -49,27 +71,76 @@ function showStarPrompt() { }); } +// One burst out of the toast. The library loads only here, and its canvas stops when done. +function celebrate() { + void import("canvas-confetti") + .then(({ default: confetti }) => + confetti({ + particleCount: 160, + spread: 360, + startVelocity: 38, + gravity: 1.6, + ticks: 140, + origin: { x: 0.83, y: 0.15 }, + disableForReducedMotion: true, + }), + ) + .catch(() => undefined); +} + +// Resolves after IDLE_MS without input while this window has focus. +function waitForIdle() { + return new Promise((resolve) => { + let timer: ReturnType | undefined; + const restart = () => { + clearTimeout(timer); + timer = setTimeout(() => { + // Input inside another app or an embedded frame never reaches us; the next focus restarts. + if (!document.hasFocus() || document.activeElement?.matches("iframe, webview")) return; + for (const type of ACTIVITY_EVENTS) window.removeEventListener(type, restart, true); + resolve(); + }, IDLE_MS); + }; + for (const type of ACTIVITY_EVENTS) { + window.addEventListener(type, restart, { capture: true, passive: true }); + } + restart(); + }); +} + // The server's GitHub account stands in for the user's; it may not be theirs on a shared server. +const starInput = (environmentId: EnvironmentId) => ({ + environmentId, + input: { + provider: SourceControlProviderKind.make("github"), + host: "github.com", + repository: REPOSITORY, + }, +}); + async function alreadyStarred(environmentId: EnvironmentId) { const result = await runAtomCommand( appAtomRegistry, sourceControlEnvironment.checkStarred, - { - environmentId, - input: { - provider: SourceControlProviderKind.make("github"), - host: "github.com", - repository: REPOSITORY, - }, - }, + starInput(environmentId), { label: "check GitHub star", reportFailure: false, reportDefect: false }, ); return result._tag === "Success" ? result.value : undefined; } +async function starRepository(environmentId: EnvironmentId) { + const result = await runAtomCommand( + appAtomRegistry, + sourceControlEnvironment.star, + starInput(environmentId), + { label: "star on GitHub", reportFailure: false, reportDefect: false }, + ); + return result._tag === "Success" && result.value; +} + /** * Counts a sent prompt. After more than five, asks once per session for a star until dismissed, - * unless the environment's GitHub account already starred the repo. + * unless the environment's GitHub account already starred the repo. Waits until the user is idle. */ export async function recordPromptSent(environmentId: EnvironmentId): Promise { if (shownThisSession) return; @@ -86,11 +157,12 @@ export async function recordPromptSent(environmentId: EnvironmentId): Promise ({ + openCommandPalette: vi.fn(), + isCommandPaletteOpen: () => false, +})); +vi.mock("./sidebar/SidebarChrome", () => ({ + SidebarChromeHeader: () => null, + SidebarChromeFooter: () => null, +})); + +function project(id: string): Project { + return { + id: ProjectId.make(id), + environmentId: EnvironmentId.make("local"), + title: id, + workspaceRoot: `/projects/${id}`, + repositoryIdentity: null, + defaultModelSelection: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + scripts: [], + }; +} + +describe("sidebar header new thread", () => { + it.each([ + { mode: "normal", count: 2, shift: false, picker: true }, + { mode: "boring", count: 2, shift: false, picker: true }, + { mode: "boring", count: 2, shift: true, picker: false }, + { mode: "boring", count: 1, shift: false, picker: false }, + { mode: "legacy", count: 2, shift: false, picker: false }, + ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => { + using stack = new DisposableStack(); + const previousSettings = getClientSettings(); + stack.defer(() => __setClientSettingsForTests(previousSettings)); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + boringSidebarEnabled: scenario.mode === "boring", + legacySidebarEnabled: scenario.mode === "legacy", + }); + const projects = [project("active"), project("idle")].slice(0, scenario.count); + const currentProjectRef = { + environmentId: projects[0]!.environmentId, + projectId: projects[0]!.id, + }; + const startThread = vi.fn().mockResolvedValue(null); + vi.mocked(useProjects).mockReturnValue(projects); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: currentProjectRef, + handleNewThread: startThread, + routeDraftId: null, + routeThreadRef: null, + }); + vi.mocked(openCommandPalette).mockClear(); + await using screen = await render( + + + , + ); + + await userEvent.click(screen.getByRole("button", { name: "New thread", exact: true }), { + modifiers: scenario.shift ? ["Shift"] : [], + }); + + if (scenario.picker) { + expect(openCommandPalette).toHaveBeenCalledExactlyOnceWith({ open: "new-thread-in" }); + expect(startThread).not.toHaveBeenCalled(); + } else { + expect(openCommandPalette).not.toHaveBeenCalled(); + expect(startThread).toHaveBeenCalledExactlyOnceWith(currentProjectRef); + } + }); +}); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index aa52402920021..aef9e6c2b5c7a 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1008,6 +1008,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }, }); const boringSidebarEnabled = useBoringSidebarEnabled(); + const legacySidebarEnabled = useClientSettings((settings) => settings.legacySidebarEnabled); const folderRowsMultiline = useClientSettings((settings) => settings.boringSidebarMultilineRows); const newThreadContext = useHandleNewThread(); // Row callbacks capture only the handler; the rest of the context changes with the route. @@ -1033,7 +1034,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const projectScopeFilter = useComboboxFilter(); const allProjectSnapshotsReady = useAllEnvironmentProjectSnapshotsReady(); const allProjectConfigsReady = useAtomValue(environmentProjects.projectConfigsReadyAtom); - const headerSearchRef = useRef(null); // Safari may click after Ctrl+click opens settings; suppress that selection until the picker reopens. const suppressNextScopeChangeRef = useRef(false); const highlightedProjectScopeKeyRef = useRef(null); @@ -2983,7 +2983,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const handleNewThreadClick = (event?: ReactMouseEvent) => { if ( - boringSidebarEnabled || + legacySidebarEnabled || shouldCreateNewThreadInCurrentProject( event?.shiftKey ?? false, scopeGroups.length, @@ -3025,7 +3025,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve fixedHeader={ 0} projectScope={ closeType === "keyboard"} > >; @@ -41,6 +43,7 @@ export function ChatBannerLane(props: { return (
setDismissedProviderStatusBannerKey(providerStatusBannerKey)} onOpenProviderSetup={onOpenProviderSetup} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9ad9158cd4da3..25b7f5ce6f87c 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -5,7 +5,7 @@ import { BackgroundThreadContext } from "./backgroundThread"; import { resolveCompatibleRuntimeMode, runtimeModeConfig, - runtimeModeOptions as runtimeModes, + resolveRuntimeModeOptions, } from "./runtimeModeConfig"; import { isLocalEnvironmentDisabled } from "../../localEnvironment"; import { usePrimaryEnvironmentId } from "../../state/environments"; @@ -285,8 +285,6 @@ function consumePasteAsTextShortcut(deadline: { current: number }): boolean { return armed; } -const runtimeModeOptions = runtimeModes.map((mode) => ({ mode, ...runtimeModeConfig[mode] })); - export interface ChatComposerHandle { focusAtEnd: () => void; focusAt: (cursor: number) => void; @@ -920,12 +918,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); // Modes above an administrator's ceiling stay listed, disabled with the reason. const managedPolicy = useManagedPolicy(environmentId); - const compatibleRuntimeModeOptions = runtimeModeOptions - .filter((option) => compatibleRuntimeModes.includes(option.mode)) - .map((option) => { - const disabledReason = managedRuntimeModeDenial(managedPolicy, option.mode); - return disabledReason === undefined ? option : { ...option, disabledReason }; - }); + const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( + compatibleRuntimeModes, + managedPolicy, + ); // A thread or draft already above the ceiling would be refused; offer the broadest mode left. const runtimeModeCeilingDenial = managedRuntimeModeDenial(managedPolicy, compatibleRuntimeMode); const runtimeModeCeilingFallback = diff --git a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx index 850256b28904a..0fe4cc14d3869 100644 --- a/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerPermissionsSection.browser.test.tsx @@ -5,6 +5,7 @@ import { page, userEvent } from "vite-plus/test/browser"; import { render } from "../../../test/render"; import { ComposerHandleContext, type ComposerHandleRef } from "../../composerHandleContext"; +import { ComposerContextPermissions } from "../ComposerContextPermissions"; import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../ui/menu"; import { focusRequestedPermission, @@ -149,3 +150,38 @@ it("returns focus to the editor when picking the default hides the chip", async await vi.waitFor(() => expect(handle.focusAtEnd).toHaveBeenCalled()); await expect.element(screen.getByRole("button", { name: "Model" })).not.toHaveFocus(); }); + +function ContextPermissions() { + const [mode, setMode] = useState("full-access"); + return ( + + ); +} + +it("opens permissions directly from the context strip and applies a supported mode", async () => { + await using screen = await render(, { router: false }); // no routes involved + await userEvent.click(screen.getByRole("button", { name: "Permissions: Full access" })); + await expect + .element(page.getByRole("menuitemradio", { name: "Full access" })) + .toHaveAttribute("aria-checked", "true"); + await expect + .element(page.getByRole("menuitemradio", { name: "Auto", exact: true })) + .not.toBeInTheDocument(); + await userEvent.click(page.getByRole("menuitemradio", { name: "Supervised" })); + const trigger = screen.getByRole("button", { name: "Permissions: Supervised" }); + await expect.element(trigger).toBeVisible(); + await expect + .element(page.getByRole("menuitemradio", { name: "Supervised" })) + .not.toBeInTheDocument(); + await userEvent.click(trigger); + await expect + .element(page.getByRole("menuitemradio", { name: "Supervised" })) + .toHaveAttribute("aria-checked", "true"); + await userEvent.keyboard("{Escape}"); + await expect.element(trigger).toHaveFocus(); +}); diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index e70c32b064a3e..69da770f1f84b 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -79,6 +79,7 @@ export const ModelListRow = memo(function ModelListRow(props: { {/* The logo is decorative, so name the provider for screen readers. */} , {props.providerDisplayName}
+ {props.isSelected ?