diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts index 6a44bce6c567..89ed63002059 100644 --- a/apps/desktop/src/app/DesktopObservability.ts +++ b/apps/desktop/src/app/DesktopObservability.ts @@ -4,6 +4,7 @@ import { makeTraceSink, type SignalExport, } from "@t3tools/shared/observability"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SharedObservability from "@t3tools/shared/observability"; import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; import { @@ -625,12 +626,16 @@ const layerTelemetry = Layer.unwrap( Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const endpoints = yield* resolveOtlpEndpoints; + // `host.name` keeps machines apart on a shared collector; one set in + // `OTEL_RESOURCE_ATTRIBUTES` wins, since explicit attributes override it. const resource = { serviceName: "t3code-desktop", + serviceVersion: environment.appVersion, attributes: { "service.namespace": "t3code", "service.runtime": "desktop", "service.mode": environment.isDevelopment ? "development" : "packaged", + "host.name": endpoints.resourceAttributes["host.name"] || (yield* HostProcess.Hostname), }, }; diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 677eb44a8f93..6efe817574a3 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -367,6 +367,32 @@ describe("DesktopShellEnvironment", () => { }), ); + it.effect("hydrates missing CA trust variables from the login shell", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + SSL_CERT_DIR: "/etc/ssl/certs", + }; + + yield* runShellEnvironment({ + env, + platform: "darwin", + handler: () => + envOutput({ + PATH: "/opt/zerobrew/bin:/usr/bin", + SSL_CERT_FILE: "/opt/zerobrew/etc/ca-certificates/cacert.pem", + SSL_CERT_DIR: "/opt/zerobrew/etc/ca-certificates", + NODE_EXTRA_CA_CERTS: "/Users/me/corp-root.pem", + }), + }); + + assert.equal(env.SSL_CERT_FILE, "/opt/zerobrew/etc/ca-certificates/cacert.pem"); + assert.equal(env.SSL_CERT_DIR, "/etc/ssl/certs"); + assert.equal(env.NODE_EXTRA_CA_CERTS, "/Users/me/corp-root.pem"); + }), + ); + it.effect("keeps mise's PATH record with the login shell PATH", () => Effect.gen(function* () { const env: NodeJS.ProcessEnv = { diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index ebf5abfdc9f8..2b41b6ea7db9 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -86,6 +86,9 @@ const LOGIN_SHELL_ENV_NAMES = [ "XDG_SESSION_DESKTOP", "XDG_SESSION_TYPE", "WAYLAND_DISPLAY", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", "__MISE_DIFF", ] as const; @@ -454,6 +457,12 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "XDG_DATA_HOME", "XDG_RUNTIME_DIR", "WAYLAND_DISPLAY", + // CA trust set in the shell profile. Without it, a Node or OpenSSL build + // that has no bundled roots (a shared-OpenSSL node on PATH) cannot verify + // TLS, so provider updaters and agents fail to reach their registries. + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "NODE_EXTRA_CA_CERTS", // The telemetry opt-out is documented as a shell variable; GUI launches never see it. "T3CODE_TELEMETRY_ENABLED", ] as const) { diff --git a/apps/mobile/src/components/AndroidScreenHeader.tsx b/apps/mobile/src/components/AndroidScreenHeader.tsx index 624c6d6d939f..1ae2464e0a77 100644 --- a/apps/mobile/src/components/AndroidScreenHeader.tsx +++ b/apps/mobile/src/components/AndroidScreenHeader.tsx @@ -6,6 +6,7 @@ import { AppText as Text } from "./AppText"; import { cn } from "../lib/cn"; import { MaterialIconButton } from "./MaterialIconButton"; import { AndroidAnchoredMenu } from "./AndroidAnchoredMenu"; +import { splitAndroidHeaderActions } from "./headerMenu.android"; import { useScaledTextRole } from "../features/settings/appearance/useScaledTextRole"; import { useMaterialToolbarLayout } from "./useMaterialToolbarLayout"; @@ -16,6 +17,8 @@ export interface AndroidHeaderAction { readonly disabled?: boolean; readonly loading?: boolean; readonly selected?: boolean; + readonly destructive?: boolean; + readonly overflowOnly?: boolean; } export function AndroidHeaderIconButton(props: { @@ -45,10 +48,10 @@ export function AndroidScreenHeader(props: { props.embedded, ); const [headerWidth, setHeaderWidth] = useState(0); - const actions = props.actions ?? []; - const directCount = actions.length > 2 ? (headerWidth >= 600 ? 3 : 1) : actions.length; - const visibleActions = actions.slice(0, directCount); - const overflowActions = actions.slice(directCount); + const { visibleActions, overflowActions } = splitAndroidHeaderActions( + props.actions ?? [], + headerWidth >= 600, + ); return ( - {packageIcon.paths.map((path) => ( + + {packageIcon.paths.map((path, index) => + path.gradient ? ( + + {path.gradient.stops.map((stop) => ( + + ))} + + ) : null, + )} + + {packageIcon.paths.map((path, index) => ( ))} diff --git a/apps/mobile/src/components/headerMenu.android.ts b/apps/mobile/src/components/headerMenu.android.ts index 49c9d9abeb6a..7bb87865bc62 100644 --- a/apps/mobile/src/components/headerMenu.android.ts +++ b/apps/mobile/src/components/headerMenu.android.ts @@ -41,3 +41,16 @@ export function findHeaderMenuAction( } return undefined; } + +export function splitAndroidHeaderActions( + actions: ReadonlyArray, + wide: boolean, +) { + const inline = actions.filter((action) => !action.overflowOnly); + const directCount = actions.length > 2 ? (wide ? 3 : 1) : inline.length; + const visibleActions = inline.slice(0, directCount); + return { + visibleActions, + overflowActions: actions.filter((action) => !visibleActions.includes(action)), + }; +} diff --git a/apps/mobile/src/components/headerMenu.test.ts b/apps/mobile/src/components/headerMenu.test.ts index bbc0b1d1ee4d..c63f0165019a 100644 --- a/apps/mobile/src/components/headerMenu.test.ts +++ b/apps/mobile/src/components/headerMenu.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; -import { androidHeaderMenuActions, findHeaderMenuAction } from "./headerMenu.android"; +import { + androidHeaderMenuActions, + findHeaderMenuAction, + splitAndroidHeaderActions, +} from "./headerMenu.android"; import type { ScreenHeaderMenuItem } from "./ScreenHeader.types"; const items: ReadonlyArray = [ @@ -63,4 +67,36 @@ describe("header menus", () => { expect(findHeaderMenuAction(items, "sessions")).toBeUndefined(); expect(findHeaderMenuAction(items, "removed-session")).toBeUndefined(); }); + + it("keeps overflow-only Android header actions in the overflow menu", () => { + const action = (accessibilityLabel: string, overflowOnly?: boolean) => ({ + accessibilityLabel, + icon: "trash" as const, + onPress: () => {}, + overflowOnly, + }); + const labels = ( + split: ReturnType>>, + ) => ({ + visible: split.visibleActions.map((item) => item.accessibilityLabel), + overflow: split.overflowActions.map((item) => item.accessibilityLabel), + }); + const open = action("Open"); + const remove = action("Delete", true); + expect(labels(splitAndroidHeaderActions([open, action("Comment")], false))).toEqual({ + visible: ["Open", "Comment"], + overflow: [], + }); + expect(labels(splitAndroidHeaderActions([open, remove], true))).toEqual({ + visible: ["Open"], + overflow: ["Delete"], + }); + expect(labels(splitAndroidHeaderActions([remove], true))).toEqual({ + visible: [], + overflow: ["Delete"], + }); + expect( + labels(splitAndroidHeaderActions([action("Review"), action("Comment"), open, remove], true)), + ).toEqual({ visible: ["Review", "Comment", "Open"], overflow: ["Delete"] }); + }); }); diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts index bab9daaed9b9..a68dea36e1fc 100644 --- a/apps/mobile/src/features/home/useThreadListActions.ts +++ b/apps/mobile/src/features/home/useThreadListActions.ts @@ -312,7 +312,9 @@ export function useThreadListActions(): { if (!canSnooze(thread, { now: new Date().toISOString() })) { Alert.alert( "Could not snooze thread", - thread.hasPendingApprovals || thread.hasPendingUserInput + thread.hasPendingApprovals || + thread.hasPendingUserInput || + thread.pendingSubagentRequest != null ? "This thread is waiting on you. Respond to the pending request before snoozing it." : "This thread is still starting a turn. Try again once it's running.", ); diff --git a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx index 069fe077a4c5..24296142593d 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListFilters.tsx @@ -1,6 +1,11 @@ +import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping"; +import { useMemo } from "react"; import { ScrollView } from "react-native"; import type { ControlPillMenuProps } from "../../components/ControlPillMenu.types"; import { ListFilterMenu } from "../workspace/ListFilterMenu"; +import { useProjects, useThreadShells } from "../../state/entities"; +import { useMobileProjectGroupingSettings } from "../../state/project-grouping"; +import { buildHomeProjectScopes, sortHomeProjectScopes } from "../home/homeThreadList"; import { DEFAULT_PR_LIST_CONTROLS, type PullRequestListControls } from "./pullRequestList"; const STATES = { open: "Open", closed: "Closed", merged: "Merged", all: "All states" } as const; @@ -28,6 +33,30 @@ function choices(field: string, options: Readonly>, selec })); } +/** The project list's own order, which is the order its sidebar and new-task picker show. */ +function useProjectsInSidebarOrder( + projects: readonly Project[], +) { + const allProjects = useProjects(); + const threads = useThreadShells(); + const { sidebarProjectGroupingMode } = useMobileProjectGroupingSettings(); + const scopes = useMemo( + () => + sortHomeProjectScopes({ + scopes: buildHomeProjectScopes({ + projects: allProjects, + environmentId: null, + projectGroupingMode: sidebarProjectGroupingMode, + }), + threads, + pendingTasks: [], + projectSortOrder: "updated_at", + }).map((scope) => ({ memberProjectRefs: scope.projectRefs })), + [allProjects, sidebarProjectGroupingMode, threads], + ); + return useMemo(() => sortProjectsByGroupOrder(projects, scopes), [projects, scopes]); +} + export function PullRequestListFilters(props: { readonly environments: readonly { id: string; label: string }[]; readonly environmentId: string | null; @@ -39,6 +68,7 @@ export function PullRequestListFilters(props: { readonly projects: readonly { id: string; title: string; environmentId: string }[]; }) { const { value } = props; + const projects = useProjectsInSidebarOrder(props.projects); const selectedLabels = value.filters.labels?.flat() ?? []; const selectedLabelSet = new Set(selectedLabels); const author = value.filters.author; @@ -76,7 +106,7 @@ export function PullRequestListFilters(props: { props.onChange({ ...value, sort: next as PullRequestListControls["sort"] }); break; case "project": { - const project = props.projects.find( + const project = projects.find( (project) => JSON.stringify([project.environmentId, project.id]) === next, ); props.onChange({ @@ -165,7 +195,7 @@ export function PullRequestListFilters(props: { { id: "projects", title: - props.projects.find( + projects.find( (project) => project.id === value.projectId && project.environmentId === value.projectEnvironmentId, )?.title ?? "Project", @@ -173,7 +203,7 @@ export function PullRequestListFilters(props: { "project", Object.fromEntries([ ["", "All projects"], - ...props.projects.map((project) => [ + ...projects.map((project) => [ JSON.stringify([project.environmentId, project.id]), project.title, ]), diff --git a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx index a1495eb19f51..539775aa44d0 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestReviewSheet.tsx @@ -154,7 +154,7 @@ export function PullRequestReviewSheet({ /> } > - {reviewing && offered.length ? ( + {reviewing && offered.length > 1 ? ( ({ value: option.value, label: option.title }))} selected={verdict?.value ?? "comment"} diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx index 37fa732930a0..f68a19bbf28e 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx @@ -17,7 +17,12 @@ import { PR_ROW_EXIT, PR_POSITION_LAYOUT, } from "./pullRequestAnimations"; -import { openOnProviderLabel } from "./pullRequestActions"; +import { + canPerformPullRequestAction, + openOnProviderLabel, + PR_ACTION_ICONS, + PR_ACTION_LABELS, +} from "./pullRequestActions"; import * as Clipboard from "expo-clipboard"; import { ControlPillMenu } from "../../components/ControlPillMenu"; import { MaterialIconButton } from "../../components/MaterialIconButton"; @@ -25,6 +30,7 @@ import { MaterialButton } from "../../components/MaterialButton"; import { usePullRequestReviewDraft } from "./usePullRequestReviewDraft"; import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed"; import { usePullRequestPermissions } from "./usePullRequestPermissions"; +import { usePullRequestAction } from "./usePullRequestAction"; import { annotatePullRequestDiff, reviewPosition } from "./pullRequestDiffComments"; import { usePullRequestFileFilter } from "./usePullRequestFileFilter"; import { isPullRequestTestFile } from "./pullRequestFileFilters"; @@ -341,6 +347,15 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps + pr && + action.confirm( + "delete-branch", + PR_ACTION_LABELS["delete-branch"], + `Delete ${pr.headBranch} from ${pr.headRepositoryNameWithOwner ?? pr.repository}? Local branches and worktrees are not changed.`, + ); const stack = usePullRequestStack(params, pr); const refreshActivity = useAtomRefresh(composerPullRequests.activity(requestTarget(params))); const refreshGuide = useAtomRefresh(composerPullRequests.reviewGuide(requestTarget(params))); @@ -417,6 +432,18 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps ) : null} @@ -456,6 +483,25 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps ) : null} + {showsDeleteBranch ? ( + + + {PR_ACTION_LABELS["delete-branch"]} + + + ) : null} withoutScratchProjectScope(savedControls, allProjects), + [allProjects, savedControls], + ); const targets = useMemo( () => environments @@ -175,8 +181,9 @@ export function PullRequestsScreen( ].sort(), })); } - const projects = useProjects().filter( - (project) => environmentId === null || project.environmentId === environmentId, + const projects = allProjects.filter( + (project) => + !project.isScratch && (environmentId === null || project.environmentId === environmentId), ); const renderPullRequest = useCallback( ({ item }: { readonly item: EnvironmentPullRequestListEntry }) => ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts index 8bc20666cf26..c554e6d1cd53 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestActions.test.ts @@ -112,6 +112,19 @@ describe("mobile pull request actions", () => { expect(mergeSummary(unknown, true)).toBe("Squash"); }); + it("offers deleting the source branch only once merged or closed on a host that supports it", () => { + const capabilities = { ...detail().capabilities, deleteBranch: true }; + expect(canPerformPullRequestAction(detail({ capabilities }), "delete-branch")).toBe(false); + for (const state of ["merged", "closed"] as const) { + expect(canPerformPullRequestAction(detail({ state, capabilities }), "delete-branch")).toBe( + true, + ); + expect(canPerformPullRequestAction(detail({ state }), "delete-branch")).toBe(false); + } + const refused = detail({ state: "merged", capabilities, viewerPermissions: { actions: [] } }); + expect(canPerformPullRequestAction(refused, "delete-branch")).toBe(false); + }); + it("cannot merge when the repository has disabled every offered strategy", () => { const pr = detail({ mergeCapabilities: { merge: false, squash: false, rebase: false } }); expect(canPerformPullRequestAction(pr, "merge")).toBe(false); diff --git a/apps/mobile/src/features/pull-requests/pullRequestActions.ts b/apps/mobile/src/features/pull-requests/pullRequestActions.ts index 8ce458ae62b5..359cbf436333 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestActions.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestActions.ts @@ -13,7 +13,7 @@ type ActionDetail = Pick< > & { readonly capabilities: Pick< PullRequestDetail["capabilities"], - "actions" | "mergeMethods" | "updateMethods" + "actions" | "mergeMethods" | "updateMethods" | "deleteBranch" >; readonly viewerPermissions: Pick< PullRequestDetail["viewerPermissions"], @@ -41,6 +41,7 @@ export const PR_ACTION_LABELS = { "enable-auto-merge": "Enable auto-merge", "disable-auto-merge": "Disable auto-merge", revert: "Create revert pull request", + "delete-branch": "Delete branch", "approve-workflows": "Approve workflows", } as const satisfies Record; @@ -54,6 +55,7 @@ export const PR_ACTION_ICONS = { "enable-auto-merge": "clock", "disable-auto-merge": "xmark", revert: "arrow.uturn.backward", + "delete-branch": "trash", "approve-workflows": "checkmark", } as const satisfies Record; @@ -68,6 +70,7 @@ export const ALL_PR_ACTIONS: readonly PullRequestAction[] = [ "close", "reopen", "revert", + "delete-branch", ]; export function allowedMergeMethods(pr: ActionDetail) { @@ -86,6 +89,8 @@ export function canPerformPullRequestAction(pr: ActionDetail, action: PullReques return false; if (action === "reopen") return pr.state === "closed"; if (action === "revert") return pr.state === "merged"; + if (action === "delete-branch") + return pr.state !== "open" && pr.capabilities.deleteBranch === true; if (pr.state !== "open") return false; switch (action) { case "update-branch": diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.test.ts b/apps/mobile/src/features/pull-requests/pullRequestList.test.ts index f3a085e02b45..de5dd166ff1d 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.test.ts @@ -18,6 +18,7 @@ import { pullRequestLabelColor, scopedPullRequestListKey, pullRequestListRowsAreEqual, + withoutScratchProjectScope, } from "./pullRequestList"; function entry(number: number, patch: Partial = {}): PullRequestListEntry { @@ -373,3 +374,39 @@ describe("mobile PR scan and filters", () => { expect(pullRequestLabelColor("not-a-color")).toBeNull(); }); }); + +describe("withoutScratchProjectScope", () => { + const projects = [ + { id: "repo", environmentId: "env-a" }, + { id: "scratch", environmentId: "env-a", isScratch: true as const }, + ]; + + it("reads a scope saved on the Scratch folder as all projects", () => { + const controls = withoutScratchProjectScope( + { ...DEFAULT_PR_LIST_CONTROLS, projectId: "scratch", projectEnvironmentId: "env-a" }, + projects, + ); + expect(controls.projectId).toBeUndefined(); + expect(controls.projectEnvironmentId).toBeUndefined(); + }); + + it("keeps a repository scope, and one whose projects have not arrived yet", () => { + const repository = { + ...DEFAULT_PR_LIST_CONTROLS, + projectId: "repo", + projectEnvironmentId: "env-a", + }; + expect(withoutScratchProjectScope(repository, projects)).toBe(repository); + const pending = { ...repository, projectId: "scratch" }; + expect(withoutScratchProjectScope(pending, [])).toBe(pending); + }); + + it("keeps another server's project that shares the Scratch folder's id", () => { + const elsewhere = { + ...DEFAULT_PR_LIST_CONTROLS, + projectId: "scratch", + projectEnvironmentId: "env-b", + }; + expect(withoutScratchProjectScope(elsewhere, projects)).toBe(elsewhere); + }); +}); diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index 4527ba1e295d..f0deeef6c974 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -15,6 +15,21 @@ export const DEFAULT_PR_LIST_CONTROLS: PullRequestListControls = { sort: "updated", }; +/** A scope saved on the Scratch folder is no longer offered, so it reads as "All projects". */ +export function withoutScratchProjectScope( + controls: PullRequestListControls, + projects: readonly { id: string; environmentId: string; isScratch?: true }[], +): PullRequestListControls { + return projects.some( + (project) => + project.isScratch && + project.id === controls.projectId && + project.environmentId === controls.projectEnvironmentId, + ) + ? { ...controls, projectId: undefined, projectEnvironmentId: undefined } + : controls; +} + export function pullRequestListKey( item: Pick, ) { diff --git a/apps/mobile/src/features/pull-requests/usePullRequestAction.ts b/apps/mobile/src/features/pull-requests/usePullRequestAction.ts index 870bcbed3976..2b0193ca3081 100644 --- a/apps/mobile/src/features/pull-requests/usePullRequestAction.ts +++ b/apps/mobile/src/features/pull-requests/usePullRequestAction.ts @@ -14,7 +14,7 @@ import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff" import { usePullRequestPermissions } from "./usePullRequestPermissions"; /** Small row actions stay in place, preserving expanded rows and scroll position. */ -export function usePullRequestAction(params: PullRequestParams, pr: PullRequestDetail) { +export function usePullRequestAction(params: PullRequestParams, pr: PullRequestDetail | null) { const target = pullRequestTarget(params); const permissions = usePullRequestPermissions(params, pr); const run = useAtomCommand(composerPullRequests.runAction, { reportFailure: false }); @@ -23,7 +23,7 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD const pending = useRef(false); const [busy, setBusy] = useState(false); const available = (action: PullRequestAction) => - !busy && permissions.canWrite && canPerformPullRequestAction(pr, action); + pr !== null && !busy && permissions.canWrite && canPerformPullRequestAction(pr, action); const perform = async (action: PullRequestAction, updateMethod?: PullRequestUpdateMethod) => { if (pending.current || !available(action)) return; pending.current = true; @@ -51,7 +51,7 @@ export function usePullRequestAction(params: PullRequestParams, pr: PullRequestD { text: "Cancel", style: "cancel" }, { text: title, - style: action === "close" ? "destructive" : "default", + style: action === "close" || action === "delete-branch" ? "destructive" : "default", onPress: () => void perform(action), }, ]); diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 4a680a06026b..fe8328df83cf 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -11,9 +11,10 @@ import { } from "@t3tools/client-runtime/connection"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import type { HandoffEndpoints } from "@t3tools/client-runtime/handoff"; -import type { - CodexFeedbackSubmission, - EnvironmentThreadStatus, +import { + childThreadInputsTitle, + type CodexFeedbackSubmission, + type EnvironmentThreadStatus, } from "@t3tools/client-runtime/state/threads"; import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard"; import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills"; @@ -536,11 +537,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread if (childInput && contentPresentationKind === "ready") { return { kind: "child-input", - label: - childThreadInputs.length === 1 - ? "Subagent needs input" - : `${childThreadInputs.length} subagents need input`, - accessibilityLabel: `Open question from ${childInput.title}`, + label: childThreadInputsTitle(childThreadInputs), + accessibilityLabel: `Open ${childInput.hasPendingApprovals ? "approval" : "question"} from ${childInput.title}`, onPress: () => { Keyboard.dismiss(); navigation.navigate("Thread", { diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 5ab042dba125..d47466ecc382 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1313,10 +1313,12 @@ function renderFeedEntry( {intentBadge ? ( - Alert.alert("Message history", intentBadge.explanation)} className={cn( "rounded-full border px-1.5 py-0.5", intentBadge.tone === "queued" @@ -1334,7 +1336,7 @@ function renderFeedEntry( > {intentBadge.label} - + ) : null} {entry.pendingMessage && !entry.acknowledged ? "Pending" : timestampLabel} diff --git a/apps/mobile/src/features/threads/thread-handoff-row.tsx b/apps/mobile/src/features/threads/thread-handoff-row.tsx index 4b05662595f8..cc36efe1dad0 100644 --- a/apps/mobile/src/features/threads/thread-handoff-row.tsx +++ b/apps/mobile/src/features/threads/thread-handoff-row.tsx @@ -9,7 +9,7 @@ import type { ServerProvider, } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; -import { Fragment, useMemo } from "react"; +import { useMemo } from "react"; import { Alert, Pressable, View, type ColorValue } from "react-native"; import { AppText as Text } from "../../components/AppText"; import { SymbolView } from "../../components/AppSymbol"; @@ -76,14 +76,17 @@ export function ThreadHandoffDivider(props: { > {endpoints.from.map((endpoint, index) => ( - - {index > 0 ? ( + + + {index < endpoints.from.length - 1 ? ( , ) : null} - - + ))} {endpoints.from.length > 0 ? ( diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index c5fe2752df10..b9e3d2ad3230 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -94,7 +94,7 @@ const STATUS_LABEL_BY_STATUS: Partial> = }, waiting: { label: "Waiting", - icon: "clock", + icon: "circle.dashed.inset.filled", className: "text-foreground-muted", iconTintClassName: "accent-foreground-muted", }, diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index b5aee8fb4b22..4024af958271 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -144,11 +144,17 @@ export function resolveThreadListV2SwipeActions(input: { export function resolveThreadListV2SnoozeGateExpiryMs( thread: Pick< EnvironmentThreadShell, - "hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime" + | "hasPendingApprovals" + | "hasPendingUserInput" + | "pendingSubagentRequest" + | "latestRun" + | "latestUserMessageAt" + | "runtime" >, options: { readonly now: string }, ): number | null { if (thread.hasPendingApprovals || thread.hasPendingUserInput) return null; + if (thread.pendingSubagentRequest != null) return null; if (!hasQueuedTurnStart(thread, options)) return null; const messageAtMs = Date.parse(thread.latestUserMessageAt ?? ""); if (Number.isNaN(messageAtMs)) return null; @@ -183,12 +189,15 @@ export function threadHasUnseenCompletion( } export function resolveThreadListV2Status( - thread: Pick, + thread: Pick< + EnvironmentThreadShell, + "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime" + >, ): ThreadListV2Status { - if (thread.hasPendingApprovals) { + if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") { return "approval"; } - if (thread.hasPendingUserInput) { + if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") { return "input"; } if ( diff --git a/apps/mobile/src/features/threads/userMessageIntentBadge.test.ts b/apps/mobile/src/features/threads/userMessageIntentBadge.test.ts index f29c4bba1643..c38ab3f66ca9 100644 --- a/apps/mobile/src/features/threads/userMessageIntentBadge.test.ts +++ b/apps/mobile/src/features/threads/userMessageIntentBadge.test.ts @@ -8,18 +8,21 @@ describe("user message intent badge", () => { expect(resolveUserMessageIntentBadge("turn_start")).toBeNull(); }); - it("labels messages waiting behind the active turn", () => { + it("explains the queued history without claiming delivery", () => { expect(resolveUserMessageIntentBadge("queued_turn")).toEqual({ - label: "queued", - accessibilityLabel: "Queued behind the active turn", + label: "from queue", + accessibilityLabel: "Queued while the agent was busy", + explanation: + "This badge records that the message was queued. It stays visible after the message leaves the queue.", tone: "queued", }); }); - it("labels messages that steer the active turn", () => { + it("explains the intent to steer without claiming delivery", () => { expect(resolveUserMessageIntentBadge("steer")).toEqual({ label: "steer", accessibilityLabel: "Steered the active turn", + explanation: "This message was intended to steer the agent while its turn was still running.", tone: "steer", }); }); @@ -28,6 +31,8 @@ describe("user message intent badge", () => { expect(resolveUserMessageIntentBadge("promoted_queued_to_steer")).toEqual({ label: "queued → steer", accessibilityLabel: "Originally queued, then promoted to steer the active turn", + explanation: + "This message was originally queued, then promoted to steer the agent while its turn was still running.", tone: "steer", }); }); diff --git a/apps/mobile/src/features/threads/userMessageIntentBadge.ts b/apps/mobile/src/features/threads/userMessageIntentBadge.ts index c72c1c342d83..c234fb1734d8 100644 --- a/apps/mobile/src/features/threads/userMessageIntentBadge.ts +++ b/apps/mobile/src/features/threads/userMessageIntentBadge.ts @@ -3,6 +3,7 @@ import type { OrchestrationV2UserMessageInputIntent } from "@t3tools/contracts"; export interface UserMessageIntentBadgePresentation { readonly label: string; readonly accessibilityLabel: string; + readonly explanation: string; readonly tone: "queued" | "steer"; } @@ -12,20 +13,26 @@ export function resolveUserMessageIntentBadge( switch (intent) { case "queued_turn": return { - label: "queued", - accessibilityLabel: "Queued behind the active turn", + label: "from queue", + accessibilityLabel: "Queued while the agent was busy", + explanation: + "This badge records that the message was queued. It stays visible after the message leaves the queue.", tone: "queued", }; case "steer": return { label: "steer", accessibilityLabel: "Steered the active turn", + explanation: + "This message was intended to steer the agent while its turn was still running.", tone: "steer", }; case "promoted_queued_to_steer": return { label: "queued → steer", accessibilityLabel: "Originally queued, then promoted to steer the active turn", + explanation: + "This message was originally queued, then promoted to steer the agent while its turn was still running.", tone: "steer", }; case "turn_start": diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index e940628e8453..2b3a73f5364e 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -10,6 +10,7 @@ import { AuthSessionId, AuthOrchestrationReadScope, EnvironmentHttpApi, + EnvironmentId, EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, ORCHESTRATION_V2_WS_METHODS, @@ -35,6 +36,7 @@ import * as HttpApi from "effect/http-api/HttpApi"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { HttpRouter, HttpServer } from "effect/http"; import { Rpc, RpcGroup, RpcServer, RpcSerialization } from "effect/rpc"; +import * as ServerEnvironment from "../src/environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../src/persistence/Sqlite.ts"; import * as OrchestrationEventStore from "../src/persistence/OrchestrationEventStore.ts"; import * as EventStore from "../src/orchestration-v2/EventStore.ts"; @@ -111,6 +113,11 @@ const layerEnrichment = Layer.unwrap( ); // The transfer history has no project events, so shell streams never read a project shell. const layerServices = layerManagement.pipe( + Layer.provideMerge( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(EnvironmentId.make("transfer-test")), + }), + ), Layer.provideMerge(ProjectStore.layer), Layer.provideMerge(Layer.mock(ProjectService.ProjectService)({})), Layer.provideMerge(layerEnrichment), @@ -237,6 +244,7 @@ it.live( Layer.provide(Layer.succeedContext(context)), Layer.provideMerge( NodeHttpServer.layer(NodeHttp.createServer, { + host: "127.0.0.1", port: 0, websocket: { perMessageDeflate: true }, }), diff --git a/apps/server/src/config.test.ts b/apps/server/src/config.test.ts new file mode 100644 index 000000000000..d21a96c9f415 --- /dev/null +++ b/apps/server/src/config.test.ts @@ -0,0 +1,18 @@ +import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; +import { assert, describe, it } from "@effect/vitest"; + +import * as ServerConfig from "./config.ts"; + +describe("otlpResource", () => { + const resource = (resourceAttributes: Record) => + ServerConfig.otlpResource( + { mode: "web", otelEnvironment: { ...OtelEnvironment.none, resourceAttributes } }, + "box-1", + ); + + it("names the host, unless OTEL_RESOURCE_ATTRIBUTES already does", () => { + assert.equal(resource({}).attributes["host.name"], "box-1"); + assert.equal(resource({ "host.name": "from-env" }).attributes["host.name"], "from-env"); + assert.equal(resource({ "host.name": "" }).attributes["host.name"], "box-1"); + }); +}); diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index ec48ad1394b5..7937c662428d 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -19,6 +19,7 @@ import * as Schema from "effect/Schema"; import { sweepStalePendingAttachments } from "./attachmentStore.ts"; import { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability"; import * as OtelEnvironment from "@t3tools/shared/otelEnvironment"; +import packageJson from "../package.json" with { type: "json" }; export const DEFAULT_PORT = 3773; @@ -120,14 +121,21 @@ export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config) /** * Resource attributes shared by every OTLP exporter, so traces, metrics, and - * logs report the same service identity to the collector. + * logs report the same service identity to the collector. `host.name` keeps + * servers apart when several export to one collector; a `host.name` set in + * `OTEL_RESOURCE_ATTRIBUTES` wins, since explicit attributes override it. */ -export const otlpResource = (config: ServerConfig["Service"]) => ({ +export const otlpResource = ( + config: Pick, + hostName: string, +) => ({ serviceName: "t3code-server", + serviceVersion: packageJson.version, attributes: { "service.namespace": "t3code", "service.runtime": "t3-server", "service.mode": config.mode, + "host.name": config.otelEnvironment.resourceAttributes["host.name"] || hostName, }, }); diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 8c27261a6307..15547b0240d3 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -119,6 +119,13 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => { expect(descriptor.capabilities.serverSelfUpdate).toBe( mode === "web" ? undefined : "desktop-managed", ); + expect(descriptor.capabilities).toMatchObject({ + settledWorktreeCleanup: true, + storageCleanupRun: true, + projectWorktreeCleanup: true, + worktreesDirectory: true, + threadAutoSettlementScope: true, + }); } }), ); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b2667a9edd3f..8e635f9814b3 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -231,7 +231,9 @@ export const make = Effect.gen(function* () { storageCleanupRun: true, otlpEndpointCheck: true, projectWorktreeCleanup: true, + settledWorktreeCleanup: true, worktreesDirectory: true, + threadAutoSettlementScope: true, threadRestartContinuation: true, projectSettingsOverrides: true, projectProviderInstanceOverrides: true, diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 733f2e62d6f0..63a93371fea4 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -96,6 +96,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; let hasNestedWork = true; const layerDependencies = Layer.mergeAll( @@ -223,6 +224,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( @@ -308,6 +310,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( NodeServices.layer, @@ -385,6 +388,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( NodeServices.layer, @@ -465,6 +469,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( NodeServices.layer, @@ -552,6 +557,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( NodeServices.layer, @@ -655,6 +661,7 @@ describe("OrchestratorMcpService", () => { appOwnedTask("node:mcp-cancel-grandchild-below", childThreadId, grandchildThreadId), ], providerThreads: [], + runtimeRequests: [], }, ], [ @@ -666,6 +673,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], }, ], ]) as unknown as ReadonlyMap; @@ -883,6 +891,7 @@ describe("OrchestratorMcpService provider resolution", () => { messages: [], subagents: [], providerThreads: [], + runtimeRequests: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 745c89e508db..7583c7e74362 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -102,13 +102,14 @@ import * as SecretRequests from "../secrets/SecretRequests.ts"; const DEFAULT_WAIT_TIMEOUT_MS = 10 * 60 * 1_000; const MAX_WAIT_TIMEOUT_MS = 60 * 60 * 1_000; -// Events that can make a delegated task terminal: the parent's task record, -// and the child's runs, nested tasks, and pending provider background work. +// Events that can end a delegated task wait: the parent's task record, +// and the child's runs, nested tasks, provider background work, and questions. const TASK_WAKE_EVENTS = [ { thread: "parent", eventType: "subagent.updated" }, { thread: "child", eventType: "run.updated" }, { thread: "child", eventType: "subagent.updated" }, { thread: "child", eventType: "provider-thread.updated" }, + { thread: "child", eventType: "runtime-request.updated" }, ] as const; /** A person answers the card, so a slower poll is plenty. */ const SECRET_REQUEST_POLL_INTERVAL_MS = 500; @@ -1455,7 +1456,14 @@ const make = Effect.gen(function* () { const childControls = yield* threadManagement .getThreadRecords( task.childThreadId, - ["runs", "messages", "contextTransfers", "subagents", "providerThreads"], + [ + "runs", + "messages", + "contextTransfers", + "subagents", + "providerThreads", + "runtimeRequests", + ], { messageRoles: ["user"] }, ) .pipe(Effect.mapError(threadManagementFailure)); @@ -1560,6 +1568,15 @@ const make = Effect.gen(function* () { : subagentResultForRun(childProjection, terminalRun).text : null, latestTerminalResultContextTransferId: resultTransferForRun(terminalRun)?.id ?? null, + // A finished task has no question of its own; later child runs belong to other tasks. + hasPendingQuestion: + !isTerminalTaskStatus(status) && + childControls.runtimeRequests.some( + (request) => + request.kind === "user_input" && + request.status === "pending" && + request.responseCapability.type === "live", + ), waitTimedOut, } satisfies OrchestratorMcpDelegateTaskResult; if ( @@ -1612,7 +1629,9 @@ const make = Effect.gen(function* () { .getThreadEventSequence(scope.thread.threadId) .pipe(Effect.mapError(streamError)); const initial = yield* readTask(scope, taskId, false, true); - if (isTerminalTaskStatus(initial.status)) return Option.some(initial); + if (initial.hasPendingQuestion || isTerminalTaskStatus(initial.status)) { + return Option.some(initial); + } // One stream per event type, so transcript events never fill a buffer. return yield* Stream.mergeAll( TASK_WAKE_EVENTS.map(({ thread, eventType }) => @@ -1626,7 +1645,7 @@ const make = Effect.gen(function* () { ).pipe( Stream.mapError(streamError), Stream.mapEffect(() => readTask(scope, taskId, false, true)), - Stream.filter((result) => isTerminalTaskStatus(result.status)), + Stream.filter((result) => result.hasPendingQuestion || isTerminalTaskStatus(result.status)), Stream.runHead, ); }).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)), Effect.map(Option.flatten)); @@ -2160,13 +2179,12 @@ const make = Effect.gen(function* () { Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS), ); const waited = yield* waitForTask(scope, taskId, timeoutMs); - if (Option.isSome(waited)) { + if (Option.isSome(waited) && isTerminalTaskStatus(waited.value.status)) { return waited.value; } - // The blocking wait timed out, so it no longer owns delivery: upgrade - // the task so a later terminal wakes the parent even mid-turn. Best - // effort; on failure the settled_only policy still wakes a settled - // parent. + // An incomplete wait gives up delivery: upgrade so a later terminal + // wakes the parent even mid-turn. Best effort; settled_only still + // wakes a settled parent if the upgrade fails. yield* threadManagement .dispatch({ type: "delegated_task.wake-policy", @@ -2180,7 +2198,7 @@ const make = Effect.gen(function* () { completionWake: "always", }) .pipe( - // The tool result is the timed-out task either way, so failures + // The tool result still returns after a timeout or question, so failures // stay warnings. Keep the two shapes apart: a rejected receipt // means this exact command id already failed (a replay of a // no-op upgrade), while anything else is a fresh dispatch fault. @@ -2202,7 +2220,7 @@ const make = Effect.gen(function* () { }), ), ); - return yield* readTask(scope, taskId, true, true); + return yield* readTask(scope, taskId, Option.isNone(waited), true); }), taskStatus: (callerScope, taskId) => Effect.gen(function* () { diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 65bba7e002a4..c5deca324153 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -30,6 +30,7 @@ import { ProviderThreadId, ProviderTurnId, type ScheduledTask, + RuntimeRequestId, ScheduledTaskId, type ScheduledTaskUpsertInput, type ServerProvider, @@ -2725,6 +2726,66 @@ describe("orchestrator MCP toolkit", () => { ).toMatchObject({ state: "disposed" }); yield* expectOffersToStay(0); + // A live question ends the wait and leaves completion delivery armed. + const questionWait = yield* invoke("delegate_task", { + task: cancellationPrompt, + title: "Wait question", + target: { providerInstanceId: codexInstanceId, model: codexModel }, + mode: "wait", + timeoutMs: 30_000, + clientRequestId: "delegate-wait-question-1", + }).pipe(Effect.forkChild); + const question = (yield* waitForProjection(orchestrator, parentThreadId, (p) => + p.subagents.some( + (task) => task.title === "Wait question" && task.childThreadId !== null, + ), + )).subagents.find((task) => task.title === "Wait question")!; + const asking = yield* waitForProjection(orchestrator, question.childThreadId!, (p) => + p.providerTurns.some((turn) => turn.status === "running"), + ); + const askedAt = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:wait-question:live"), + type: "runtime-request.updated", + threadId: question.childThreadId!, + occurredAt: askedAt, + payload: { + id: RuntimeRequestId.make("request:wait-question"), + nodeId: question.id, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { + type: "live", + providerSessionId: asking.providerSessions[0]!.id, + }, + createdAt: askedAt, + resolvedAt: null, + }, + }, + ], + }); + expect((yield* Fiber.join(questionWait)).structuredContent).toMatchObject({ + status: "running", + hasPendingQuestion: true, + waitTimedOut: false, + }); + expect( + (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find( + (task) => task.id === question.id, + )?.completionWake, + ).toBe("always"); + yield* invoke("task_cancel", { + taskId: question.id, + clientRequestId: "cancel-wait-question-1", + }); + yield* waitForProjection(orchestrator, parentThreadId, (p) => + p.subagents.some((task) => task.id === question.id && task.status === "interrupted"), + ); + // The MCP tool cannot force the reverse interleaving (child // terminal before the upgrade lands), so dispatch the command // directly. The first wait-mode delegation completed while the diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 90019ef6041b..4480400fc69c 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -73,7 +73,7 @@ const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", { export const DelegateTaskTool = Tool.make("delegate_task", { description: - "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion or timeout. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.", + "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For every T3 delegated review round, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. The childThreadId is backing storage, not the target for starting another delegated review round through t3_thread_send. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.", parameters: OrchestratorMcpDelegateTaskInput, success: OrchestratorMcpDelegateTaskResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/observability/Observability.ts b/apps/server/src/observability/Observability.ts index 9ae9875749b2..80ef1f84b70c 100644 --- a/apps/server/src/observability/Observability.ts +++ b/apps/server/src/observability/Observability.ts @@ -1,3 +1,4 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as HttpObservability from "@t3tools/shared/httpObservability"; import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability"; import * as SharedObservability from "@t3tools/shared/observability"; @@ -25,7 +26,7 @@ export const layer = Layer.unwrap( // The trace serializer stays in the returned context because the browser // trace forwarder exports on the same signal. const layerSerialization = SharedObservability.layerOtlpSerialization(traces.protocol); - const resource = ServerConfig.otlpResource(config); + const resource = ServerConfig.otlpResource(config, yield* HostProcess.Hostname); const attribution = yield* ResourceAttribution.ResourceAttribution; const layerTraceReferences = Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e2957dae9528..a6fd7998c196 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -1035,6 +1035,7 @@ describe("ClaudeAdapterV2 Auto-accept edits", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -1196,6 +1197,7 @@ const captureSdkExecutablePaths = Effect.fn("captureSdkExecutablePaths")(functio setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -1317,6 +1319,7 @@ describe("ClaudeAdapterV2 resume compaction", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -1544,6 +1547,7 @@ describe("ClaudeAdapterV2 attachments", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -1690,6 +1694,7 @@ describe("ClaudeAdapterV2 attachments", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -1786,6 +1791,7 @@ describe("ClaudeAdapterV2 native fork", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -2079,6 +2085,7 @@ describe("ClaudeAdapterV2 native session identity", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, @@ -2340,6 +2347,9 @@ describe("ClaudeAdapterV2 background wake turns", () => { readonly stopTask?: ( taskId: string, ) => Effect.Effect; + readonly backgroundTasks?: ( + toolUseId: string, + ) => Effect.Effect; readonly environment?: NodeJS.ProcessEnv; readonly subagentLaunchToolUseId?: string; readonly nativeSessionId?: string; @@ -2420,6 +2430,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)), stopTask: options?.stopTask ?? (() => Effect.void), interrupt: Effect.void, close: Queue.shutdown(processMessages), @@ -2460,6 +2471,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { Effect.sync(() => { permissionModeChanges.push(mode); }), + backgroundTasks: options?.backgroundTasks ?? (() => Effect.succeed(false)), stopTask: options?.stopTask ?? (() => Effect.void), interrupt: options?.interrupt ?? Effect.void, close: options?.close?.(sdkMessages) ?? Effect.void, @@ -2863,10 +2875,29 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - // Summarized thinking can't tell a progress update from reasoning, so both stay Thoughts. - it.effect.each(["claude-opus-5-5", "claude-fable-5-1", "claude-opus-5", "claude-sonnet-4-6"])( - "keeps %s thinking right before a tool call as reasoning", - (model) => + // Summarized display can't mark a progress update, so only the second of two + // thinking blocks before a tool call becomes text; a lone block is reasoning. + const plan = "Planning the check"; + const update = "Found it: the memory file is the cause."; + it.effect.each([ + { + model: "claude-opus-5-5", + texts: [plan, update], + expected: ["reasoning", "assistant_message"], + }, + { + model: "claude-fable-5-1", + texts: [plan, update], + expected: ["reasoning", "assistant_message"], + }, + { model: "claude-opus-5", texts: [plan, update], expected: ["reasoning", "reasoning"] }, + { model: "claude-sonnet-4-6", texts: [plan, update], expected: ["reasoning", "reasoning"] }, + { model: "claude-opus-5-5", texts: [plan], expected: ["reasoning"] }, + { model: "claude-opus-5-5", texts: [plan, " \n "], expected: ["reasoning", "reasoning"] }, + { model: "claude-opus-5-5", texts: [" \n ", update], expected: ["reasoning", "reasoning"] }, + ] as const)( + "shows $model thinking $texts before a tool call as $expected", + ({ model, texts, expected }) => Effect.gen(function* () { const harness = yield* makeWakeHarness; yield* harness.runtime.startTurn( @@ -2888,16 +2919,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { message: { id: "reply-message", model, content }, }); const frames = [ - snapshot("reasoning-snapshot", [ - { type: "thinking", thinking: "Planning the check", signature: "sig" }, - ]), - snapshot("reply-snapshot", [ - { - type: "thinking", - thinking: "Found it: the memory file is the cause.", - signature: "sig", - }, - ]), + ...texts.map((thinking, index) => + snapshot(`thinking-snapshot-${index}`, [ + { type: "thinking", thinking, signature: "sig" }, + ]), + ), snapshot("tool-snapshot", [ { type: "tool_use", id: "tool-1", name: "Bash", input: { command: "ls" } }, ]), @@ -2913,12 +2939,14 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ), ); + const items = [...latest.values()]; assert.deepEqual( - [...latest.values()].map((item) => [item.type, item.text]), - [ - ["reasoning", "Planning the check"], - ["reasoning", "Found it: the memory file is the cause."], - ], + items.map((item) => item.type), + [...expected], + ); + assert.deepEqual( + items.map((item) => item.text), + [...texts], ); }).pipe( Effect.scoped, @@ -4998,6 +5026,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, // The first CLI process keeps streaming until the test ends @@ -5275,6 +5304,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(queue), @@ -6634,6 +6664,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -6773,6 +6804,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -7140,6 +7172,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const harness = yield* makeWakeHarnessWithOptions({ close: (sdkMessages) => Deferred.await(closeGate).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Deferred.succeed(interruptStarted, undefined), }); @@ -7202,6 +7235,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const harness = yield* makeWakeHarnessWithOptions({ close: (sdkMessages) => Deferred.await(closeGate).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Deferred.succeed(interruptStarted, undefined), }); @@ -10652,6 +10686,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, // End this process stream so openQuery can replace it. @@ -10840,6 +10875,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -11080,6 +11116,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -11279,6 +11316,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -11460,6 +11498,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -11597,6 +11636,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Queue.shutdown(sdkMessages), @@ -14195,6 +14235,298 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each([ + { backgrounding: "succeeds" }, + { backgrounding: "fails" }, + { backgrounding: "never answers" }, + { backgrounding: "answers after the steer went out" }, + { backgrounding: "answers after the turn ended" }, + { backgrounding: "answers after the subagent ran again" }, + ] as const)( + "moves the root's foreground subagents to the background before a steer ($backgrounding)", + ({ backgrounding }) => + Effect.scoped( + Effect.gen(function* () { + const FOREGROUND_TOOL_USE_ID = "toolu-steer-foreground"; + const NESTED_TOOL_USE_ID = "toolu-steer-nested"; + const FINISHED_TOOL_USE_ID = "toolu-steer-finished"; + const calls: Array = []; + // What happens while the move is still unanswered. + let beforeAnswer: Effect.Effect = Effect.void; + const harness = yield* makeWakeHarnessWithOptions({ + backgroundTasks: (toolUseId) => + Effect.sync(() => calls.push(toolUseId)).pipe( + Effect.andThen( + backgrounding === "answers after the turn ended" || + backgrounding === "answers after the subagent ran again" + ? Effect.suspend(() => beforeAnswer).pipe(Effect.as(true)) + : backgrounding === "fails" + ? Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "backgroundTasks", + cause: new Error("Background tasks are disabled in this session."), + }), + ) + : backgrounding === "never answers" + ? Effect.never + : backgrounding === "answers after the steer went out" + ? Effect.sleep("6 seconds").pipe(Effect.as(true)) + : Effect.succeed(true), + ), + ), + }); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attemptId = RunAttemptId.make("attempt-steer-foreground-subagent"); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Audit the repo with a subagent.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + if (backgrounding === "answers after the turn ended") { + beforeAnswer = Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a10", result: "Done." }), + ).pipe( + Effect.andThen(awaitUntil(() => harness.terminalEvents().length === 1, "turn end")), + ); + } + const foregroundTaskStarted = (task: { + readonly spawnDepth?: number; + readonly taskId: string; + readonly toolUseId: string; + readonly uuid: string; + }) => + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: task.taskId, + tool_use_id: task.toolUseId, + description: task.taskId, + subagent_type: "general-purpose", + is_backgrounded: false, + task_type: "local_agent", + prompt: "Audit.", + ...(task.spawnDepth === undefined ? {} : { spawn_depth: task.spawnDepth }), + uuid: task.uuid, + session_id: WAKE_NATIVE_SESSION, + }); + for (const frame of [ + foregroundTaskStarted({ + taskId: "task-steer-finished", + toolUseId: FINISHED_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a01", + }), + makeSubagentNotificationFrame({ + taskId: "task-steer-finished", + toolUseId: FINISHED_TOOL_USE_ID, + summary: "Finished before the steer.", + uuid: "00000000-0000-4000-8000-000000000a02", + }), + foregroundTaskStarted({ + taskId: "task-steer-foreground", + toolUseId: FOREGROUND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a03", + }), + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_steer_nested_launch", + type: "message", + role: "assistant", + content: [ + { + type: "tool_use", + id: NESTED_TOOL_USE_ID, + name: "Agent", + input: { description: "Nested check", prompt: "Check." }, + }, + ], + }, + parent_tool_use_id: FOREGROUND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a04", + session_id: WAKE_NATIVE_SESSION, + }), + foregroundTaskStarted({ + taskId: "task-steer-nested", + toolUseId: NESTED_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a05", + }), + // Nested too, though its launch never reached the adapter. + foregroundTaskStarted({ + taskId: "task-steer-deep", + toolUseId: "toolu-steer-deep", + spawnDepth: 2, + uuid: "00000000-0000-4000-8000-000000000a11", + }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + const latestSubagent = (taskId: string) => + harness.events + .flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === taskId + ? [event.subagent] + : [], + ) + .at(-1); + yield* awaitUntil( + () => + latestSubagent("task-steer-nested")?.status === "running" && + latestSubagent("task-steer-deep")?.status === "running" && + latestSubagent("task-steer-foreground")?.status === "running" && + latestSubagent("task-steer-finished")?.status === "completed", + "subagents registered", + ); + + const offered = harness.offeredMessages.length; + const steer = harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-steer-foreground-subagent"), + text: "Also check the docs.", + attachments: [], + }, + }); + const RERUN_TOOL_USE_ID = "toolu-steer-rerun"; + if (backgrounding === "answers after the subagent ran again") { + // It ends and a SendMessage runs it again, in the foreground. + beforeAnswer = harness + .offerAndWait( + makeSubagentNotificationFrame({ + taskId: "task-steer-foreground", + toolUseId: FOREGROUND_TOOL_USE_ID, + summary: "First run done.", + uuid: "00000000-0000-4000-8000-000000000a12", + }), + ) + .pipe( + Effect.andThen( + harness.offerAndWait( + foregroundTaskStarted({ + taskId: "task-steer-foreground", + toolUseId: RERUN_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000a13", + }), + ), + ), + ); + } + const steering = yield* Effect.forkScoped(steer); + if ( + backgrounding === "never answers" || + backgrounding === "answers after the steer went out" + ) { + yield* awaitUntil(() => calls.length === 1, "background request"); + assert.equal(harness.offeredMessages.length, offered); + yield* TestClock.adjust("5 seconds"); + } + const steered = yield* Fiber.await(steering); + + // Only the root's running subagent moves: the nested ones follow + // their owner and the finished one has nothing left to move. + assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]); + if (backgrounding === "answers after the turn ended") { + // The steer is refused, so the orchestrator starts its follow-up turn. + assert.isTrue(Exit.isFailure(steered)); + assert.equal(harness.offeredMessages.length, offered); + return; + } + // A refused or unanswered move still lets the steer through. + assert.isTrue(Exit.isSuccess(steered)); + assert.equal(harness.offeredMessages.length, offered + 1); + assert.equal(harness.offeredMessages.at(-1)?.priority, "now"); + if (backgrounding === "never answers") { + // Later steers wait on the move still in flight instead of + // piling up another request for the same run. + for (let repeat = 1; repeat <= 2; repeat++) { + const again = yield* Effect.forkScoped(steer); + // The steer's 5 second wait starts once it reaches it; move the + // clock until the steer has gone out. + for (let tick = 0; tick < 100 && again.pollUnsafe() === undefined; tick++) { + yield* TestClock.adjust("1 second"); + yield* Effect.yieldNow; + } + assert.isTrue(Exit.isSuccess(yield* Fiber.await(again))); + assert.equal(harness.offeredMessages.length, offered + 1 + repeat); + } + assert.deepEqual(calls, [FOREGROUND_TOOL_USE_ID]); + } + if (backgrounding === "answers after the steer went out") { + yield* TestClock.adjust("1 second"); + } else if ( + backgrounding !== "succeeds" && + backgrounding !== "answers after the subagent ran again" + ) { + return; + } + // The move answered for the first run; the second runs in the + // foreground, so its end is the parent's tool result, not a wake. + const reran = backgrounding === "answers after the subagent ran again"; + + // The moved subagent outlives the steered turn. When it ends during + // the user's next turn, Claude's wake after that turn names it. + for (const frame of [ + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000a06", + result: "", + terminalReason: "aborted_tools", + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a07", result: "Docs too." }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* awaitUntil(() => harness.terminalEvents().length === 1, "steered turn terminal"); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-steer-next-turn"), + text: "Anything else?", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + for (const frame of [ + makeSubagentNotificationFrame({ + taskId: "task-steer-foreground", + toolUseId: reran ? RERUN_TOOL_USE_ID : FOREGROUND_TOOL_USE_ID, + summary: "AUDITED", + uuid: "00000000-0000-4000-8000-000000000a08", + }), + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000a09", result: "No." }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + yield* awaitUntil(() => harness.terminalEvents().length === 2, "next turn terminal"); + yield* Queue.offer(harness.sdkMessages, wakeTurnInit); + yield* awaitUntil(() => harness.continuationRequests.length === 1, "subagent wake"); + assert.equal( + harness.continuationRequests[0]?.notification?.summary, + reran ? undefined : 'Subagent "task-steer-foreground" finished', + ); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + describe("native goals", () => { const syntheticFrame = (uuid: string, text: string) => claudeSdkFrame({ diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts index c8fa9e25b944..9f75ffb90ee1 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts @@ -243,6 +243,7 @@ interface ClaudeSubagentFoundFrame { type ClaudeOutboundFrame = | { readonly type: "query.stop_task"; readonly taskId: string } + | { readonly type: "query.background_tasks"; readonly toolUseId: string } | ClaudeQueryOpenFrame | ClaudePromptOfferFrame | ClaudeQuerySetModelFrame @@ -843,6 +844,10 @@ function makeReplayQueryRunner( replayEffect(() => { assertNextOutboundFrame({ type: "query.stop_task", taskId }); }), + backgroundTasks: (toolUseId) => + replayEffect(() => { + assertNextOutboundFrame({ type: "query.background_tasks", toolUseId }); + }).pipe(Effect.as(true)), interrupt: replayEffect(() => { assertNextOutboundFrame({ type: "query.interrupt" }); }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 0ed39f6381c2..50eface9c8fe 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -96,6 +96,7 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Equal from "effect/Equal"; 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 Option from "effect/Option"; @@ -425,6 +426,10 @@ export interface ClaudeAgentSdkQuerySession { mode: PermissionMode, ) => Effect.Effect; readonly stopTask: (taskId: string) => Effect.Effect; + /** Moves the foreground task one tool call started to the background; false when none matched. */ + readonly backgroundTasks: ( + toolUseId: string, + ) => Effect.Effect; readonly interrupt: Effect.Effect; readonly close: Effect.Effect; } @@ -588,6 +593,14 @@ export type ClaudeAgentSdkProtocolLogEvent = readonly taskId: string; }; } + | { + readonly direction: "outgoing"; + readonly stage: "decoded"; + readonly payload: { + readonly type: "query.background_tasks"; + readonly toolUseId: string; + }; + } | { readonly direction: "outgoing"; readonly stage: "decoded"; @@ -921,6 +934,19 @@ export const layerQueryRunner: Layer.Layer< }), ), ), + backgroundTasks: (toolUseId) => + Effect.tryPromise({ + try: () => queryRuntime.backgroundTasks(toolUseId), + catch: (cause) => queryRunnerError(cause, "backgroundTasks"), + }).pipe( + Effect.tap(() => + logProtocolEvent({ + direction: "outgoing", + stage: "decoded", + payload: { type: "query.background_tasks", toolUseId }, + }), + ), + ), interrupt: Effect.tryPromise({ try: () => queryRuntime.interrupt(), catch: (cause) => queryRunnerError(cause, "interrupt"), @@ -1275,6 +1301,17 @@ function textFromClaudeContent(content: SDKAssistantMessage["message"]["content" return content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""); } +// Claude 5.1 and later return the text written ahead of a tool call as a +// thinking block, at most one per call, instead of a text block. Summarized +// display makes it look like reasoning, so only the second of two thinking +// blocks right before a tool call is treated as that text. +function claudeWritesUpdatesAsThinking(model: string): boolean { + const match = /claude-[a-z]+-(\d+)(?:-(\d{1,2}))?(?!\d)/u.exec(model); + if (match === null) return false; + const major = Number(match[1]); + return major > 5 || (major === 5 && Number(match[2] ?? 0) >= 1); +} + // In SDK mode Claude reports `/goal` only through the transcript (its // `active_goal` event is remote-only): synthetic command output names the // goal, and each unmet evaluator check returns as Stop hook feedback. @@ -3016,6 +3053,13 @@ interface ActiveClaudeTurnContext { readonly nextBlockIndex: Map; readonly snapshotBlockIndex: Map; readonly snapshots: Set; + // The latest snapshot block, when it was non-empty thinking. + lastThinking: { + readonly messageId: string; + readonly itemId: string; + readonly text: string; + readonly followsThinking: boolean; + } | null; readonly blocks: Map< string, { readonly startedAt: DateTime.Utc; readonly ordinal: number; text: string } @@ -3589,6 +3633,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // the turn that launched the subagent (wake drain, later turns) resolve // their subagent through this index into sessionSubagentsByTaskId. const sessionSubagentTaskIdsByToolUseId = yield* Ref.make(new Map()); + // Requests that move a running subagent to the background before a + // steer, by the tool call that started its run. Claude may never + // answer one, so a later steer waits on it rather than asking again. + const backgroundMovesByToolUseId = new Map>(); // A subagent's tool calls can outlive the turn that started them, so // they live here rather than on a turn context: a turn that ends while // one runs neither fails it nor hides it from the turn that follows. @@ -6976,18 +7024,45 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // The SDK emits one assistant snapshot per completed content block. // Count thinking blocks separately so snapshots share the streamed ID. for (const block of message.message.content) { - if (block.type !== "thinking") continue; + if (block.type !== "thinking") { + const update = context.reasoning.lastThinking; + context.reasoning.lastThinking = null; + if ( + block.type === "tool_use" && + update !== null && + update.messageId === message.message.id && + update.followsThinking && + claudeWritesUpdatesAsThinking(message.message.model) + ) { + // Same item ID, so the update replaces the Thought in place. + yield* emitAssistantTextArtifacts({ + context, + nativeItemId: update.itemId, + text: update.text, + }); + } + continue; + } const index = context.reasoning.snapshotBlockIndex.get(message.message.id) ?? 0; context.reasoning.snapshotBlockIndex.set(message.message.id, index + 1); const itemId = `${message.message.id}:thinking:${index}`; yield* ensureReasoningBlock(context, itemId); const finalText = block.thinking || context.reasoning.blocks.get(itemId)?.text; - yield* reasoningDeltas.complete({ + const completedText = yield* reasoningDeltas.complete({ turnId: context.nativeTurnId, itemId, ...(finalText ? { finalText } : {}), emitEmpty: false, }); + const previous = context.reasoning.lastThinking; + context.reasoning.lastThinking = completedText.trim() + ? { + messageId: message.message.id, + itemId, + text: completedText, + followsThinking: previous !== null && previous.messageId === message.message.id, + } + : null; } } @@ -8732,6 +8807,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( streamBlocks: new Map(), nextBlockIndex: new Map(), snapshotBlockIndex: new Map(), + lastThinking: null, snapshots: new Set(), blocks: new Map(), }, @@ -8999,6 +9075,82 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); + // A steer is sent with priority "now", which cancels the root turn's + // running tool calls. A subagent the root launched in the foreground is + // one of them, so it moves to the background first and keeps running; + // its result arrives as a task notification like any background agent. + // Subagents a subagent launched stay put: they follow their owner. + const backgroundForegroundSubagents = Effect.fnUntraced(function* ( + live: ClaudeLiveQueryContext, + ) { + const foreground: Array<{ + readonly taskId: string; + readonly toolUseId: string; + }> = []; + for (const [taskId, subagent] of yield* Ref.get(sessionSubagentsByTaskId)) { + const toolUseId = subagent.runToolUseId; + if ( + toolUseId === null || + subagent.task.status !== "running" || + subagent.task.parentNodeId !== subagent.rootNodeId || + live.subagentsFromEarlierProcesses.has(subagent) || + // A nested launch whose owner was not known yet falls back to + // the root as its parent node; its spawn depth still marks it. + (yield* isNestedSubagentTask(taskId)) + ) { + continue; + } + foreground.push({ taskId, toolUseId }); + } + // Backgrounding is refused when the session disables background + // tasks, and the SDK puts no deadline on the request. Either way the + // steer still goes through, as it did before. A move answered after + // the steer stopped waiting for it still marks the subagent, and a + // later steer waits on that same move instead of asking again. + for (const [toolUseId, move] of backgroundMovesByToolUseId) { + if (move.pollUnsafe() !== undefined) backgroundMovesByToolUseId.delete(toolUseId); + } + const moves: Array> = []; + for (const { taskId, toolUseId } of foreground) { + const inFlight = backgroundMovesByToolUseId.get(toolUseId); + if (inFlight !== undefined) { + moves.push(inFlight); + continue; + } + const move = yield* live.query.backgroundTasks(toolUseId).pipe( + // Now a background subagent: its end wakes the root like one + // Claude started in the background. One that already ended + // while the move was answered has nothing left to report. + Effect.flatMap((moved) => + moved + ? Ref.get(sessionSubagentsByTaskId).pipe( + Effect.flatMap((registry) => + registry.get(taskId)?.task.status === "running" && + // Not a later run of it that started meanwhile. + registry.get(taskId)?.runToolUseId === toolUseId + ? Ref.update(backgroundedSubagentTaskIds, (current) => + new Set(current).add(taskId), + ) + : Effect.void, + ), + ) + : Effect.void, + ), + Effect.catch((cause) => + Effect.logWarning("orchestration-v2.claude-steer-background-subagent-failed", { + taskId, + toolUseId, + cause, + }), + ), + Effect.forkIn(sessionScope), + ); + backgroundMovesByToolUseId.set(toolUseId, move); + moves.push(move); + } + yield* Fiber.joinAll(moves).pipe(Effect.timeoutOption("5 seconds")); + }); + const steerTurn = Effect.fn("ClaudeAdapterV2.steerTurn")( function* (turnInput: ProviderAdapter.ProviderAdapterV2SteerInput) { const existing = yield* Ref.get(queryContext); @@ -9026,6 +9178,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( fileSystem, skillNames: yield* userInvocableSkillNames(currentTurn.input.runtimePolicy.cwd), }); + yield* backgroundForegroundSubagents(existing); + // The turn can end while the moves are answered. A steer offered + // then would start a new turn the orchestrator never asked for, so + // the steer fails and the orchestrator starts the follow-up turn. + if ( + (yield* Ref.get(activeTurn))?.providerTurnId !== turnInput.providerTurnId || + (yield* Ref.get(queryContext)) !== existing + ) { + return yield* new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`, + }); + } yield* Ref.update(steeredTurns, (current) => { const next = new Set(current); next.add(turnInput.providerTurnId); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ae29f052617b..8f6d0edb7eb8 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -19,6 +19,7 @@ import { type OrchestrationV2ProviderTurn, type OrchestrationV2TurnItem, ProjectId, + type ProviderApprovalDecision, ProviderInstanceId, ProviderSessionId, ProviderThreadId, @@ -669,6 +670,7 @@ describe("CodexAdapterV2 process spawning", () => { mcp_servers: { "t3-code": { url: "http://127.0.0.1:43123/mcp", + tool_timeout_sec: 3_900, http_headers: { Authorization: "Bearer secret-codex-token", }, @@ -2786,6 +2788,216 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("stops asking for commands the user allowed for the session", () => + Effect.scoped( + Effect.gen(function* () { + const nativeThreadId = "session-approval-thread"; + const turnIds = [ + "session-approval-turn-1", + "session-approval-turn-2", + "session-approval-turn-3", + ]; + const turnPolicies = { + "approval-required": { + approvalPolicy: "untrusted", + approvalsReviewer: "user", + sandboxPolicy: { type: "readOnly" }, + }, + "full-access": { + approvalPolicy: "never", + approvalsReviewer: "user", + sandboxPolicy: { type: "dangerFullAccess" }, + }, + } as const; + const turnModes = ["approval-required", "full-access", "approval-required"] as const; + const turnText = (index: number) => `Review round ${index + 1}.`; + const startTurn = (index: number): ReadonlyArray => [ + { + type: "expect_outbound", + label: `turn ${index + 1} turn/start`, + frame: { + id: 3 + index, + method: "turn/start", + params: { + threadId: nativeThreadId, + input: [{ type: "text", text: turnText(index) }], + cwd: "/workspace", + model: "gpt-5.4", + ...turnPolicies[turnModes[index]!], + summary: "detailed", + }, + }, + }, + { + type: "emit_inbound", + label: `turn ${index + 1} turn/start`, + frame: { + id: 3 + index, + result: { turn: makeCodexReplayTurn({ id: turnIds[index]!, status: "inProgress" }) }, + }, + }, + turnEvent("turn/started", turnIds[index]!), + ]; + const approval = (input: { + readonly id: number; + readonly turnId: string; + readonly kind: "commandExecution" | "fileChange"; + readonly itemId: string; + readonly decision: string; + }): ReadonlyArray => [ + { + type: "emit_inbound", + label: `${input.itemId} approval`, + frame: { + id: input.id, + method: `item/${input.kind}/requestApproval`, + params: { + threadId: nativeThreadId, + turnId: input.turnId, + itemId: input.itemId, + startedAtMs: 1782622441000, + ...(input.kind === "commandExecution" ? { command: `cat ${input.itemId}` } : {}), + }, + }, + }, + { + type: "expect_outbound", + label: `${input.itemId} decision`, + frame: { id: input.id, result: { decision: input.decision } }, + }, + ]; + const turnEvent = ( + method: "turn/started" | "turn/completed", + turnId: string, + ): CodexReplay.CodexAppServerReplayEntry => ({ + type: "emit_inbound", + label: `${turnId} ${method}`, + frame: { + method, + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ + id: turnId, + status: method === "turn/started" ? "inProgress" : "completed", + }), + }, + }, + }); + const [patchRequest, patchDecision] = approval({ + id: 102, + turnId: turnIds[0]!, + kind: "fileChange", + itemId: "first-patch", + decision: "acceptForSession", + }); + const transcript = makeCodexReplayTranscript({ + scenario: "codex-session-approvals", + entries: [ + ...codexReplayPreamble({ + nativeThreadId, + nativeTurnId: turnIds[0]!, + prompt: turnText(0), + }).slice(0, -3), + ...startTurn(0), + ...approval({ + id: 100, + turnId: turnIds[0]!, + kind: "commandExecution", + itemId: "first-command", + decision: "acceptForSession", + }), + // Only commands were allowed, so a file change still asks. The user + // answers it after the turn ended and the mode changed. + patchRequest!, + // Answered without asking: Codex alone would ask for every new command. + ...approval({ + id: 101, + turnId: turnIds[0]!, + kind: "commandExecution", + itemId: "second-command", + decision: "acceptForSession", + }), + turnEvent("turn/completed", turnIds[0]!), + ...startTurn(1), + patchDecision!, + turnEvent("turn/completed", turnIds[1]!), + ...startTurn(2), + // Back in the first mode, neither allowance comes back. + ...approval({ + id: 103, + turnId: turnIds[2]!, + kind: "commandExecution", + itemId: "third-command", + decision: "accept", + }), + ...approval({ + id: 104, + turnId: turnIds[2]!, + kind: "fileChange", + itemId: "second-patch", + decision: "accept", + }), + turnEvent("turn/completed", turnIds[2]!), + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + const requests = () => [ + ...new Map( + harness.events.flatMap((event) => + event.type === "runtime_request.updated" + ? [[event.runtimeRequest.id, event.runtimeRequest] as const] + : [], + ), + ).values(), + ]; + const answer = ( + count: number, + kind: "command" | "file-change", + decision: ProviderApprovalDecision, + ) => + Effect.gen(function* () { + yield* awaitUntil(() => requests().length === count, `approval request ${count}`); + const request = requests()[count - 1]!; + assert.equal(request.kind, kind); + yield* harness.runtime.respondToRuntimeRequest({ requestId: request.id, decision }); + }); + + const runTurn = (index: number) => + Effect.gen(function* () { + yield* harness.runtime.startTurn({ + ...makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`session-approvals-${index + 1}`), + text: turnText(index), + }), + runOrdinal: index + 1, + providerTurnOrdinal: index + 1, + runtimePolicy: { ...CODEX_TEST_RUNTIME_POLICY, runtimeMode: turnModes[index]! }, + }); + }); + + yield* runTurn(0); + yield* answer(1, "command", "acceptForSession"); + yield* awaitUntil(() => requests().length === 2, "file change request"); + yield* awaitUntil(() => harness.terminalEvents().length === 1, "turn 1"); + yield* runTurn(1); + yield* answer(2, "file-change", "acceptForSession"); + yield* awaitUntil(() => harness.terminalEvents().length === 2, "turn 2"); + yield* runTurn(2); + yield* answer(3, "command", "accept"); + yield* answer(4, "file-change", "accept"); + yield* awaitUntil(() => harness.terminalEvents().length === 3, "turn 3"); + assert.lengthOf(requests(), 4); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ), + ); + it.effect("preserves T3 context on the wire and restores it after compaction", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index ec5b58666165..49779bde628f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1324,6 +1324,10 @@ export const CODEX_THREAD_CONFIG = { mcp_optional_startup_grace_ms: 10_000, } as const; +// T3 wait tools can block for up to an hour. Keep Codex's MCP timeout above +// that limit so the server's own wait timeout ends a long call. +const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; + export function codexThreadRuntimeParams(input: { readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; readonly modelSelection?: { readonly model: string }; @@ -1345,6 +1349,7 @@ export function codexThreadRuntimeParams(input: { mcp_servers: { "t3-code": { url: mcpSession.endpoint, + tool_timeout_sec: CODEX_T3_MCP_TOOL_TIMEOUT_SEC, http_headers: { Authorization: mcpSession.authorizationHeader, }, @@ -1880,6 +1885,45 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const pendingRuntimeRequests = yield* Ref.make( new Map(), ); + /** + * Approval kinds the user chose "Always allow this session" for, by + * native thread. Codex's own acceptForSession only skips the exact + * command or patch it answered, so every new command would ask again. + * A turn in another runtime mode ends the allowance, and so does the + * thread unloading, like Codex's own session approvals. + */ + const sessionApprovals = new Map< + string, + { readonly runtimeMode: RuntimeMode; readonly kinds: Set } + >(); + /** + * The allowed kinds for an approval request's turn. Read it when the + * request arrives and add to that same set when the user answers, so a + * late answer from a turn whose mode has since ended is dropped. + */ + /** Every native turn registers here. A turn in another mode ends the allowance. */ + const endSessionApprovalsOnModeChange = (context: ActiveCodexTurnContext) => { + const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; + if ( + nativeThreadId != null && + sessionApprovals.get(nativeThreadId)?.runtimeMode !== + context.input.runtimePolicy.runtimeMode + ) { + sessionApprovals.delete(nativeThreadId); + } + }; + const sessionAllowance = ( + nativeThreadId: string, + context: ActiveCodexTurnContext, + ): Set => { + const runtimeMode = context.input.runtimePolicy.runtimeMode; + const allowed = sessionApprovals.get(nativeThreadId); + if (allowed?.runtimeMode === runtimeMode) return allowed.kinds; + if (allowed !== undefined) return new Set(); + const kinds = new Set(); + sessionApprovals.set(nativeThreadId, { runtimeMode, kinds }); + return kinds; + }; /** * Turn contexts retained past turn/completed while background command * items started in that turn are still running, so late item events @@ -2030,6 +2074,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return next; }); beginTurnTokenUsage(context); + endSessionApprovalsOnModeChange(context); yield* Ref.update(activeTurns, (current) => { const updated = new Map(current); updated.set(input.nativeTurnId, context); @@ -2615,6 +2660,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( itemPositions: new Map(), }; beginTurnTokenUsage(activeContext); + endSessionApprovalsOnModeChange(activeContext); yield* Ref.update(activeTurns, (current) => { const updated = new Map(current); updated.set(turn.nativeTurnId, activeContext); @@ -5076,6 +5122,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } + const allowance = sessionAllowance(payload.threadId, context); + if (allowance.has("command")) { + return { + decision: "acceptForSession", + } satisfies CodexSchema.CommandExecutionRequestApprovalResponse; + } const nativeRequestId = payload.approvalId ?? payload.itemId; const artifacts = yield* buildApprovalRequestArtifacts({ @@ -5124,6 +5176,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ), ); + if (resolved === "acceptForSession" || resolved === "acceptAlways") { + allowance.add("command"); + } return { decision: resolved === "acceptAlways" ? "acceptForSession" : resolved, } satisfies CodexSchema.CommandExecutionRequestApprovalResponse; @@ -5139,6 +5194,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } + const allowance = sessionAllowance(payload.threadId, context); + if (allowance.has("file-change")) { + return { + decision: "acceptForSession", + } satisfies CodexSchema.FileChangeRequestApprovalResponse; + } const artifacts = yield* buildApprovalRequestArtifacts({ context, @@ -5184,6 +5245,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ), ); + if (resolved === "acceptForSession" || resolved === "acceptAlways") { + allowance.add("file-change"); + } return { decision: resolved === "acceptAlways" ? "acceptForSession" : resolved, } satisfies CodexSchema.FileChangeRequestApprovalResponse; @@ -5343,6 +5407,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } + const allowance = sessionAllowance(payload.conversationId, context); + if (allowance.has("command")) { + return { + decision: "approved_for_session", + } satisfies CodexSchema.ExecCommandApprovalResponse; + } const nativeRequestId = payload.approvalId ?? payload.callId; const artifacts = yield* buildApprovalRequestArtifacts({ @@ -5389,6 +5459,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ), ); + if (resolved === "acceptForSession" || resolved === "acceptAlways") { + allowance.add("command"); + } return { decision: approvalDecisionToLegacyReviewDecision(resolved), } satisfies CodexSchema.ExecCommandApprovalResponse; @@ -5404,6 +5477,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( payload, ); } + const allowance = sessionAllowance(payload.conversationId, context); + if (allowance.has("file-change")) { + return { + decision: "approved_for_session", + } satisfies CodexSchema.ApplyPatchApprovalResponse; + } const artifacts = yield* buildApprovalRequestArtifacts({ context, @@ -5449,6 +5528,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }), ), ); + if (resolved === "acceptForSession" || resolved === "acceptAlways") { + allowance.add("file-change"); + } return { decision: approvalDecisionToLegacyReviewDecision(resolved), } satisfies CodexSchema.ApplyPatchApprovalResponse; @@ -6706,6 +6788,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( unloadThread: (unloadInput) => Effect.gen(function* () { const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread); + sessionApprovals.delete(nativeThreadId); yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); }).pipe( Effect.mapError((cause) => diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts index f86e1b7402d9..65613079f550 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts @@ -16,7 +16,9 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as CheckpointRollbackService from "./CheckpointRollbackService.ts"; +import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { EventSinkV2 } from "./EventSink.ts"; @@ -105,6 +107,7 @@ it.effect.each([ NodeServices.layer, ThreadCommandExecutor.layer, IdAllocator.layer, + Layer.mock(GitWorkflowService.GitWorkflowService)({}), Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(Option.some({ workspaceRoot: parent } as never)), }), @@ -197,3 +200,25 @@ it.effect.each([ } }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + +it.effect("lets rollback recreate a worktree storage cleanup removed", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-v2-restore-removed-" }); + const worktreePath = path.join(parent, "worktree"); + const isolated = yield* isCheckpointRestoreIsolated( + { id: ThreadId.make("restore-removed"), worktreePath }, + { cwd: worktreePath }, + { + fileSystem, + path, + projections: { + getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }), + } as never, + projects: {} as never, + }, + ); + assert.isTrue(isolated); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts index 157db3c3478e..7a8dbad5cfb2 100644 --- a/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts +++ b/apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts @@ -33,8 +33,19 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi const worktreePath = thread.worktreePath; let shared = worktreePath == null; if (!shared && worktreePath !== null) { - const cwd = yield* fileSystem.realPath(scope.cwd); - const worktreeCwd = yield* fileSystem.realPath(worktreePath); + // Storage cleanup may have removed the worktree; rollback recreates it. + const resolve = (target: string) => + fileSystem + .realPath(target) + .pipe( + Effect.catch((error) => + error.reason._tag === "NotFound" + ? Effect.succeed(path.resolve(target)) + : Effect.fail(error), + ), + ); + const cwd = yield* resolve(scope.cwd); + const worktreeCwd = yield* resolve(worktreePath); shared = cwd !== worktreeCwd; if (!shared) { const shell = yield* projections.getShellSnapshot(); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index 018b4f8f49b1..dd51d168a3a8 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -4,18 +4,24 @@ import { CheckpointId, CheckpointScopeId, type OrchestrationV2ThreadProjection, + ProjectId, ProviderInstanceId, ProviderSessionId, ProviderThreadId, ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Option from "effect/Option"; import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; import * as Layer from "effect/Layer"; +import * as GitWorkflow from "../git/GitWorkflowService.ts"; +import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; +import { ProviderWorkspaceMissingError } from "../provider/Errors.ts"; import { resolveCodexRollbackTurnCount } from "./Adapters/CodexAdapterV2.ts"; import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts"; import * as CheckpointService from "./CheckpointService.ts"; @@ -38,76 +44,121 @@ const layerCheckpointRollbackService = CheckpointRollbackService.layer.pipe( Layer.provide( Layer.mergeAll( NodeServices.layer, + Layer.mock(GitWorkflow.GitWorkflowService)({}), Layer.mock(ProjectStore.ProjectStoreV2)({ get: () => Effect.succeed(unrelatedProject) }), ), ), ); -it.effect("rejects a non-ready checkpoint before opening a session or restoring files", () => { - const threadId = ThreadId.make("thread:rollback-non-ready"); - const providerThreadId = ProviderThreadId.make("provider-thread:rollback-non-ready"); - const providerSessionId = ProviderSessionId.make("provider-session:rollback-non-ready"); - const checkpointId = CheckpointId.make("checkpoint:rollback-non-ready"); - const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-non-ready"); - const providerInstanceId = ProviderInstanceId.make("provider_rollback_non_ready"); - const restore = vi.fn(() => Effect.die("checkpoint restore must not run")); - const open = vi.fn(() => Effect.die("provider session open must not run")); - const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run")); - const projection = { - thread: { - worktreePath: process.cwd(), - activeProviderThreadId: providerThreadId, - modelSelection: { instanceId: providerInstanceId, model: "test-model" }, - }, - providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }], - checkpoints: [{ id: checkpointId, scopeId, status: "stale" }], - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }], - } as unknown as OrchestrationV2ThreadProjection; - const layerTest = layerCheckpointRollbackService.pipe( - Layer.provide( - Layer.mergeAll( - ThreadCommandExecutor.layer, - Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }), - Layer.mock(EventSink.EventSinkV2)({}), - IdAllocator.layer, - Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadRecords: () => Effect.succeed(projection), - getShellSnapshot: () => - Effect.succeed({ - schemaVersion: 1, - snapshotSequence: 0, - threads: [], - archivedThreads: [], - }), - }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }), - Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy }), +it.effect.each(["initial", "waiting"])( + "rejects a non-ready checkpoint from %s before opening a session or restoring files", + (state) => { + const threadId = ThreadId.make("thread:rollback-non-ready"); + const providerThreadId = ProviderThreadId.make("provider-thread:rollback-non-ready"); + const providerSessionId = ProviderSessionId.make("provider-session:rollback-non-ready"); + const checkpointId = CheckpointId.make("checkpoint:rollback-non-ready"); + const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-non-ready"); + const providerInstanceId = ProviderInstanceId.make("provider_rollback_non_ready"); + const restore = vi.fn(() => Effect.die("checkpoint restore must not run")); + const open = vi.fn(() => Effect.die("provider session open must not run")); + const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run")); + const readEntered = Deferred.makeUnsafe(); + const release = Deferred.makeUnsafe(); + let readCount = 0; + let projection = { + thread: { + worktreePath: process.cwd(), + activeProviderThreadId: providerThreadId, + modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + }, + providerThreads: [{ id: providerThreadId, providerSessionId, providerInstanceId }], + checkpoints: [ + { + id: checkpointId, + scopeId, + status: state === "waiting" ? "ready" : "stale", + appRunOrdinal: 0, + }, + ], + checkpointScopes: [{ id: scopeId, cwd: process.cwd() }], + } as unknown as OrchestrationV2ThreadProjection; + const getThreadRecords = vi.fn( + () => { + const current = projection; + readCount++; + return readCount === 1 + ? Deferred.succeed(readEntered, undefined).pipe(Effect.as(current)) + : Effect.succeed(current); + }, + ); + const testLayer = layerCheckpointRollbackService.pipe( + Layer.provide( + Layer.mergeAll( + ThreadCommandExecutor.layer, + Layer.mock(CheckpointService.CheckpointServiceV2)({ restore }), + Layer.mock(EventSink.EventSinkV2)({}), + IdAllocator.layer, + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadRecords, + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 0, + threads: [], + archivedThreads: [], + }), + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open }), + Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: resolveRuntimePolicy }), + ), ), - ), - ); + ); - return Effect.gen(function* () { - const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; - const error = yield* service - .execute({ - threadId, - providerThreadId, - checkpointId, - scopeId, - }) - .pipe(Effect.flip); + return Effect.gen(function* () { + const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; + const holder = + state === "waiting" + ? yield* withWorkspaceLease(process.cwd(), Deferred.await(release)).pipe( + Effect.forkChild({ startImmediately: true }), + ) + : undefined; + const rollback = yield* service + .execute({ + threadId, + providerThreadId, + checkpointId, + scopeId, + }) + .pipe(Effect.flip, Effect.forkChild({ startImmediately: true })); + if (state === "waiting") { + yield* Deferred.await(readEntered); + projection = { + ...projection, + checkpoints: projection.checkpoints.map((checkpoint) => ({ + ...checkpoint, + status: "stale", + })), + }; + yield* Deferred.succeed(release, undefined); + if (holder !== undefined) yield* Fiber.join(holder); + } + const error = yield* Fiber.join(rollback); - assert.equal(error.reason, "rollback-target-invalid"); - assert.equal( - error.message, - `Rollback target ${checkpointId} for provider thread ${providerThreadId} on thread ${threadId} is incomplete or invalid.`, - ); - assert.equal(error.cause, undefined); - assert.equal(resolveRuntimePolicy.mock.calls.length, 0); - assert.equal(open.mock.calls.length, 0); - assert.equal(restore.mock.calls.length, 0); - }).pipe(Effect.provide(layerTest)); -}); + assert.equal(getThreadRecords.mock.calls.length, 2); + assert.deepEqual(getThreadRecords.mock.calls[0]?.[1], []); + assert.equal(getThreadRecords.mock.calls[1]?.[1].includes("checkpoints"), true); + assert.equal(error.reason, "rollback-target-invalid"); + assert.equal( + error.message, + `Rollback target ${checkpointId} for provider thread ${providerThreadId} on thread ${threadId} is incomplete or invalid.`, + ); + assert.equal(error.cause, undefined); + assert.equal(resolveRuntimePolicy.mock.calls.length, 0); + assert.equal(open.mock.calls.length, 0); + assert.equal(restore.mock.calls.length, 0); + }).pipe(Effect.provide(testLayer)); + }, +); it.effect("rejects a rollback when another provider thread became active", () => { const threadId = ThreadId.make("thread:rollback-inactive-provider-thread"); @@ -128,6 +179,7 @@ it.effect("rejects a rollback when another provider thread became active", () => const resolveRuntimePolicy = vi.fn(() => Effect.die("runtime policy resolution must not run")); const projection = { thread: { + worktreePath: null, activeProviderThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, }, @@ -268,7 +320,7 @@ it.effect("rejects a rollback when provider selection changed before execution", }).pipe(Effect.provide(layerTest)); }); -it.effect("reports a missing provider turn as a structured rollback failure", () => { +it.effect("rejects an unavailable rollback target before opening a session", () => { const threadId = ThreadId.make("thread:rollback-provider-turn-unavailable"); const providerThreadId = ProviderThreadId.make( "provider-thread:rollback-provider-turn-unavailable", @@ -280,9 +332,11 @@ it.effect("reports a missing provider turn as a structured rollback failure", () const scopeId = CheckpointScopeId.make("checkpoint-scope:rollback-provider-turn-unavailable"); const providerInstanceId = ProviderInstanceId.make("provider_rollback_provider_turn_unavailable"); const restore = vi.fn(() => Effect.die("checkpoint restore must not run")); + const open = vi.fn(() => Effect.die("provider session open must not run")); const projection = { thread: { - worktreePath: process.cwd(), + worktreePath: "/tmp/missing-invalid-rollback-worktree", + branch: "feature/rollback", activeProviderThreadId: providerThreadId, modelSelection: { instanceId: providerInstanceId, model: "test-model" }, }, @@ -312,7 +366,7 @@ it.effect("reports a missing provider turn as a structured rollback failure", () }), }), Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ - open: () => Effect.succeed({} as never), + open, }), Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never), @@ -324,14 +378,9 @@ it.effect("reports a missing provider turn as a structured rollback failure", () return Effect.gen(function* () { const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; const error = yield* service - .execute({ - threadId, - providerThreadId, - checkpointId, - scopeId, - }) + .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles: false }) .pipe(Effect.flip); - + assert.equal(open.mock.calls.length, 0); assert.equal(error.reason, "provider-turn-unavailable"); assert.equal( error.message, @@ -342,6 +391,169 @@ it.effect("reports a missing provider turn as a structured rollback failure", () }).pipe(Effect.provide(layerTest)); }); +it.effect.each([ + { order: "normal", restoreFiles: true }, + { order: "cleanup-first", restoreFiles: true }, + { order: "cleanup-first", restoreFiles: false }, + { order: "rollback-first", restoreFiles: true }, +])("locks rollback with %s", ({ order, restoreFiles }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-rollback-" }); + const worktreePath = path.join(workspaceRoot, "worktree"); + yield* fileSystem.makeDirectory(worktreePath); + const threadId = ThreadId.make("rollback-worktree"); + const projectId = ProjectId.make("rollback-worktree-project"); + const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread"); + const providerSessionId = ProviderSessionId.make("rollback-worktree-provider-session"); + const providerInstanceId = ProviderInstanceId.make("rollback-worktree-provider-instance"); + const checkpointId = CheckpointId.make("rollback-worktree-checkpoint"); + const scopeId = CheckpointScopeId.make("rollback-worktree-scope"); + const branch = "feature/rollback"; + const release = Deferred.makeUnsafe(); + const openEntered = Deferred.makeUnsafe(); + const calls: string[] = []; + let cleanupEntered = false; + const providerThread = { id: providerThreadId, providerSessionId, providerInstanceId }; + const projection = { + thread: { + id: threadId, + projectId, + worktreePath, + branch, + activeProviderThreadId: providerThreadId, + modelSelection: { instanceId: providerInstanceId, model: "test-model" }, + }, + providerThreads: [providerThread], + providerSessions: [], + checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: 0 }], + checkpointScopes: [{ id: scopeId, cwd: worktreePath }], + runs: [], + attempts: [], + nodes: [], + providerTurns: [], + } as unknown as OrchestrationV2ThreadProjection; + const testLayer = CheckpointRollbackService.layer.pipe( + Layer.provide( + Layer.mergeAll( + ThreadCommandExecutor.layer, + NodeServices.layer, + Layer.mock(ProjectStore.ProjectStoreV2)({ + get: (id) => { + assert.equal(id, projectId); + return Effect.succeed(Option.some({ workspaceRoot } as never)); + }, + }), + Layer.mock(GitWorkflow.GitWorkflowService)({ + pruneWorktrees: (input) => + Effect.sync(() => { + assert.deepEqual(input, { cwd: workspaceRoot }); + calls.push("prune"); + }), + createWorktree: (input) => + Effect.gen(function* () { + assert.deepEqual(input, { + cwd: workspaceRoot, + refName: branch, + path: worktreePath, + }); + calls.push("create"); + yield* fileSystem.makeDirectory(worktreePath).pipe(Effect.orDie); + return {} as never; + }), + }), + Layer.mock(CheckpointService.CheckpointServiceV2)({ + restore: () => + Effect.gen(function* () { + assert.isTrue(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)); + calls.push("files"); + }), + }), + Layer.mock(EventSink.EventSinkV2)({ + write: () => + Effect.sync(() => { + calls.push("projection"); + return []; + }), + }), + IdAllocator.layer, + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadRecords: () => Effect.succeed(projection), + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 0, + threads: [], + archivedThreads: [], + }), + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + open: (input) => + Effect.gen(function* () { + assert.equal(input.runtimePolicy.cwd, worktreePath); + if (!(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie))) { + return yield* new ProviderWorkspaceMissingError({ threadId, cwd: worktreePath }); + } + calls.push("session"); + yield* Deferred.succeed(openEntered, undefined); + if (order === "rollback-first") yield* Deferred.await(release); + return {} as never; + }), + }), + Layer.mock(RuntimePolicy.RuntimePolicyV2)({ + resolve: ({ thread }) => { + assert.equal(thread.worktreePath, worktreePath); + return Effect.succeed({ cwd: thread.worktreePath } as never); + }, + }), + ), + ), + ); + yield* Effect.gen(function* () { + const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; + const cleanupEffect = withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + cleanupEntered = true; + if (order === "cleanup-first") yield* Deferred.await(release); + yield* fileSystem.remove(worktreePath, { recursive: true, force: true }); + calls.push("cleanup"); + }), + ); + const cleanup = + order === "cleanup-first" + ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) + : undefined; + const rollback = yield* service + .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }) + .pipe(Effect.forkChild({ startImmediately: true })); + if (order === "cleanup-first") assert.deepEqual(calls, []); + if (order === "rollback-first") yield* Deferred.await(openEntered); + const laterCleanup = + order === "rollback-first" + ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) + : undefined; + if (order === "rollback-first") assert.isFalse(cleanupEntered); + yield* Deferred.succeed(release, undefined); + if (cleanup !== undefined) yield* Fiber.join(cleanup); + yield* Fiber.join(rollback); + if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup); + const rollbackCalls = restoreFiles + ? ["session", "files", "projection"] + : ["session", "projection"]; + assert.deepEqual( + calls, + order === "cleanup-first" + ? ["cleanup", "prune", "create", ...rollbackCalls] + : order === "rollback-first" + ? [...rollbackCalls, "cleanup"] + : rollbackCalls, + ); + }).pipe(Effect.provide(testLayer)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + it.effect.each([ { restoreFiles: true, shared: "none" }, { restoreFiles: false, shared: "root" }, @@ -350,143 +562,161 @@ it.effect.each([ { restoreFiles: false, shared: "worktree" }, { restoreFiles: true, shared: "historical" }, { restoreFiles: false, shared: "none", targetOrdinal: 1 }, -])("rewinds safely with %s", ({ restoreFiles, shared, targetOrdinal = 0 }) => { - const threadId = ThreadId.make("rewind-files"); - const providerThreadId = ProviderThreadId.make("rewind-provider"); - const providerSessionId = ProviderSessionId.make("rewind-session"); - const instanceId = ProviderInstanceId.make("rewind-instance"); - const checkpointId = CheckpointId.make("rewind-start"); - const scopeId = CheckpointScopeId.make("rewind-scope"); - const calls: string[] = []; - let lockedThreads = Effect.succeed>([]); - const layerThreadCommands = Layer.effect( - ThreadCommandExecutor.ThreadCommandExecutor, - Effect.tap(KeyedLock.make(), (lock) => - Effect.sync(() => { - lockedThreads = lock.activeKeys; - }), - ), - ); - const providerThread = { - id: providerThreadId, - providerSessionId, - providerInstanceId: instanceId, - }; - const projection = { - thread: { - worktreePath: shared === "root" ? null : process.cwd(), - activeProviderThreadId: providerThreadId, - modelSelection: { instanceId, model: "test" }, - }, - providerThreads: [providerThread], - providerSessions: [], - // Turn 3 remains in the audit history after an earlier rollback. - providerTurns: [1, 2, 3].map((ordinal) => ({ - id: `turn-${ordinal}`, - providerThreadId, - runAttemptId: `attempt-${ordinal}`, - ordinal, - status: "completed", - })), - nodes: [], - attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, runId: `run-${ordinal}` })), - checkpoints: [ - { id: checkpointId, scopeId, status: "ready", appRunOrdinal: targetOrdinal || null }, - ], - checkpointScopes: [{ id: scopeId, cwd: process.cwd() }], - runs: [1, 2, 3].map((ordinal) => ({ - id: `run-${ordinal}`, - ordinal, - status: ordinal === 3 ? "rolled_back" : "completed", - rootNodeId: null, - activeAttemptId: `attempt-${ordinal}`, - })), - } as unknown as OrchestrationV2ThreadProjection; - const layerTest = layerCheckpointRollbackService.pipe( - Layer.provide( - Layer.mergeAll( - layerThreadCommands, - Layer.mock(CheckpointService.CheckpointServiceV2)({ - restore: () => - Effect.sync(() => { - calls.push("files"); - }), - }), - Layer.mock(EventSink.EventSinkV2)({ - write: ({ events }) => - Effect.map(lockedThreads, (locked) => { - // A thread command that planned against the old provider thread - // must not commit after this and undo the rollback. - assert.include(locked, threadId); - assert.ok( - events.some( - (event) => event.type === "run.updated" && event.payload.status === "rolled_back", - ), - ); - calls.push("projection"); - return []; - }), - }), - IdAllocator.layer, - Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getThreadRecords: () => Effect.succeed(projection), - getThreadProviderContext: () => Effect.succeed({ providerSessions: [] } as never), - getCheckpointContext: () => - Effect.succeed({ - checkpointScopes: [{ cwd: process.cwd() }], - runs: [], - checkpoints: [], - } as never), - getShellSnapshot: () => - Effect.succeed({ - schemaVersion: 1, - snapshotSequence: 0, - threads: [], - archivedThreads: - shared === "worktree" || shared === "historical" - ? [ - { - id: ThreadId.make("other-thread"), - deletedAt: null, - worktreePath: shared === "worktree" ? process.cwd() : null, - } as never, - ] - : [], - }), - }), - Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ - open: () => - Effect.succeed({ - rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) => - Effect.gen(function* () { - const count = yield* resolveCodexRollbackTurnCount(input); - assert.equal(count, 2 - targetOrdinal); - calls.push("provider"); - return { providerThread }; - }), - } as never), + { restoreFiles: false, shared: "none", targetOrdinal: 1, multipleTurns: true }, +])( + "rewinds safely with %s", + ({ restoreFiles, shared, targetOrdinal = 0, multipleTurns = false }) => { + const threadId = ThreadId.make("rewind-files"); + const providerThreadId = ProviderThreadId.make("rewind-provider"); + const providerSessionId = ProviderSessionId.make("rewind-session"); + const instanceId = ProviderInstanceId.make("rewind-instance"); + const checkpointId = CheckpointId.make("rewind-start"); + const scopeId = CheckpointScopeId.make("rewind-scope"); + const calls: string[] = []; + let lockedThreads = Effect.succeed>([]); + const layerThreadCommands = Layer.effect( + ThreadCommandExecutor.ThreadCommandExecutor, + Effect.tap(KeyedLock.make(), (lock) => + Effect.sync(() => { + lockedThreads = lock.activeKeys; }), - Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }), ), - ), - ); - return Effect.gen(function* () { - const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; - if (restoreFiles && shared !== "none") { - const error = yield* Effect.flip( - service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }), - ); - assert.equal(error.reason, "shared-workspace"); - assert.deepEqual(calls, []); - return; - } - yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }); - assert.deepEqual( - calls, - restoreFiles ? ["provider", "files", "projection"] : ["provider", "projection"], ); - }).pipe(Effect.provide(layerTest)); -}); + const providerThread = { + id: providerThreadId, + providerSessionId, + providerInstanceId: instanceId, + }; + const projection = { + thread: { + worktreePath: shared === "root" ? null : process.cwd(), + activeProviderThreadId: providerThreadId, + modelSelection: { instanceId, model: "test" }, + }, + providerThreads: [providerThread], + providerSessions: [], + // Turn 3 remains in the audit history after an earlier rollback. + providerTurns: [ + ...(multipleTurns + ? [ + { + id: "turn-0", + providerThreadId, + runAttemptId: "attempt-1", + ordinal: 0, + status: "completed", + }, + ] + : []), + ...[1, 2, 3].map((ordinal) => ({ + id: `turn-${ordinal}`, + providerThreadId, + runAttemptId: `attempt-${ordinal}`, + ordinal, + status: "completed", + })), + ], + nodes: [], + attempts: [1, 2, 3].map((ordinal) => ({ id: `attempt-${ordinal}`, runId: `run-${ordinal}` })), + checkpoints: [ + { id: checkpointId, scopeId, status: "ready", appRunOrdinal: targetOrdinal || null }, + ], + checkpointScopes: [{ id: scopeId, cwd: process.cwd() }], + runs: [1, 2, 3].map((ordinal) => ({ + id: `run-${ordinal}`, + ordinal, + status: ordinal === 3 ? "rolled_back" : "completed", + rootNodeId: null, + activeAttemptId: `attempt-${ordinal}`, + })), + } as unknown as OrchestrationV2ThreadProjection; + const layerTest = layerCheckpointRollbackService.pipe( + Layer.provide( + Layer.mergeAll( + layerThreadCommands, + Layer.mock(CheckpointService.CheckpointServiceV2)({ + restore: () => + Effect.sync(() => { + calls.push("files"); + }), + }), + Layer.mock(EventSink.EventSinkV2)({ + write: ({ events }) => + Effect.map(lockedThreads, (locked) => { + // A thread command that planned against the old provider thread + // must not commit after this and undo the rollback. + assert.include(locked, threadId); + assert.ok( + events.some( + (event) => + event.type === "run.updated" && event.payload.status === "rolled_back", + ), + ); + calls.push("projection"); + return []; + }), + }), + IdAllocator.layer, + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadRecords: () => Effect.succeed(projection), + getThreadProviderContext: () => Effect.succeed({ providerSessions: [] } as never), + getCheckpointContext: () => + Effect.succeed({ + checkpointScopes: [{ cwd: process.cwd() }], + runs: [], + checkpoints: [], + } as never), + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 0, + threads: [], + archivedThreads: + shared === "worktree" || shared === "historical" + ? [ + { + id: ThreadId.make("other-thread"), + deletedAt: null, + worktreePath: shared === "worktree" ? process.cwd() : null, + } as never, + ] + : [], + }), + }), + Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ + open: () => + Effect.succeed({ + rollbackThread: (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) => + Effect.gen(function* () { + const count = yield* resolveCodexRollbackTurnCount(input); + assert.equal(count, 2 - targetOrdinal); + calls.push("provider"); + return { providerThread }; + }), + } as never), + }), + Layer.mock(RuntimePolicy.RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }), + ), + ), + ); + return Effect.gen(function* () { + const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2; + if (restoreFiles && shared !== "none") { + const error = yield* Effect.flip( + service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }), + ); + assert.equal(error.reason, "shared-workspace"); + assert.deepEqual(calls, []); + return; + } + yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles }); + assert.deepEqual( + calls, + restoreFiles ? ["provider", "files", "projection"] : ["provider", "projection"], + ); + }).pipe(Effect.provide(layerTest)); + }, +); it.effect.skipIf(!symlinksSupported)( "rejects an archived thread sharing a worktree through a symlink", diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index acacfed521c6..a0b7899c6661 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -11,9 +11,12 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as GitWorkflowService from "../git/GitWorkflowService.ts"; +import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import { isCheckpointRestoreIsolated, SHARED_WORKSPACE_RESTORE_MESSAGE, @@ -84,6 +87,7 @@ export const layer: Layer.Layer< CheckpointRollbackServiceV2, never, | CheckpointServiceV2 + | GitWorkflowService.GitWorkflowService | EventSinkV2 | IdAllocator.IdAllocatorV2 | ProjectionStoreV2 @@ -97,6 +101,7 @@ export const layer: Layer.Layer< CheckpointRollbackServiceV2, Effect.gen(function* () { const checkpoints = yield* CheckpointServiceV2; + const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; const eventSink = yield* EventSinkV2; const ids = yield* IdAllocator.IdAllocatorV2; const projections = yield* ProjectionStoreV2; @@ -158,6 +163,52 @@ export const layer: Layer.Layer< }); } + const targetOrdinal = checkpoint.appRunOrdinal ?? 0; + const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget = + targetOrdinal === 0 + ? { + type: "thread_start", + checkpointId: checkpoint.id, + appRunOrdinal: 0, + } + : yield* Effect.gen(function* () { + const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal); + const targetAttempt = projection.attempts.find( + (attempt) => attempt.id === targetRun?.activeAttemptId, + ); + // A goal run can span several native turns; roll back to its last. + const targetTurn = + latestProviderTurnForAttempt(projection.providerTurns, targetAttempt?.id) ?? + projection.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId); + if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) { + return yield* new CheckpointRollbackExecutionError({ + reason: "provider-turn-unavailable", + threadId: input.threadId, + providerThreadId: input.providerThreadId, + checkpointId: input.checkpointId, + }); + } + return { + type: "provider_turn" as const, + checkpointId: checkpoint.id, + appRunOrdinal: targetOrdinal, + providerTurn: targetTurn, + }; + }); + + const { worktreePath, branch } = projection.thread; + if (worktreePath != null && branch != null && !(yield* fileSystem.exists(worktreePath))) { + const project = yield* projects.get(projection.thread.projectId); + if (Option.isSome(project)) { + yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }); + yield* gitWorkflow.createWorktree({ + cwd: project.value.workspaceRoot, + refName: branch, + path: worktreePath, + }); + } + } + if ( input.restoreFiles !== false && !(yield* isCheckpointRestoreIsolated(projection.thread, scope, { @@ -199,7 +250,6 @@ export const layer: Layer.Layer< }), }); - const targetOrdinal = checkpoint.appRunOrdinal ?? 0; // Stopped and failed runs after the target leave the provider // conversation too, so they must not stay visible. const runsToRollback = projection.runs.filter( @@ -225,37 +275,6 @@ export const layer: Layer.Layer< turn.providerThreadId === providerThread.id && (turn.runAttemptId === null || !rolledBackAttemptIds.has(turn.runAttemptId)), ); - const rollbackTarget: ProviderAdapter.ProviderAdapterV2RollbackTarget = - targetOrdinal === 0 - ? { - type: "thread_start", - checkpointId: checkpoint.id, - appRunOrdinal: 0, - } - : yield* Effect.gen(function* () { - const targetRun = projection.runs.find((run) => run.ordinal === targetOrdinal); - const targetAttempt = projection.attempts.find( - (attempt) => attempt.id === targetRun?.activeAttemptId, - ); - // A goal run can span several native turns; roll back to its last. - const targetTurn = - latestProviderTurnForAttempt(projection.providerTurns, targetAttempt?.id) ?? - projection.providerTurns.find((turn) => turn.id === targetAttempt?.providerTurnId); - if (targetTurn === undefined || targetTurn.providerThreadId !== providerThread.id) { - return yield* new CheckpointRollbackExecutionError({ - reason: "provider-turn-unavailable", - threadId: input.threadId, - providerThreadId: input.providerThreadId, - checkpointId: input.checkpointId, - }); - } - return { - type: "provider_turn" as const, - checkpointId: checkpoint.id, - appRunOrdinal: targetOrdinal, - providerTurn: targetTurn, - }; - }); const snapshot = runsToRollback.length === 0 @@ -355,7 +374,13 @@ export const layer: Layer.Layer< return CheckpointRollbackServiceV2.of({ execute: (input) => - execute(input).pipe( + Effect.gen(function* () { + // Storage cleanup removes worktrees under the same lease. + const { thread } = yield* projections.getThreadRecords(input.threadId, []); + yield* thread.worktreePath === null + ? execute(input) + : withWorkspaceLease(path.resolve(thread.worktreePath), execute(input)); + }).pipe( Effect.mapError((cause) => isCheckpointRollbackExecutionError(cause) ? cause diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 3fd034abe4f2..308c02fef03b 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -161,6 +161,7 @@ it.effect.each(["child completion", "scheduled message", "user steering"] as con setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.die("automatic delivery must never interrupt"), close: Effect.void, diff --git a/apps/server/src/orchestration-v2/ClaudeBackgroundWorkAfterLimit.test.ts b/apps/server/src/orchestration-v2/ClaudeBackgroundWorkAfterLimit.test.ts index ea9ebfed6c1d..38c9fad31787 100644 --- a/apps/server/src/orchestration-v2/ClaudeBackgroundWorkAfterLimit.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeBackgroundWorkAfterLimit.test.ts @@ -104,6 +104,7 @@ const runtime = (cli: Ref.Ref, cwd: string) => setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.asVoid(close), diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index 003844efa720..f31d1bb5d36b 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -21,6 +21,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; import * as CheckpointStore from "../checkpointing/CheckpointStore.ts"; import * as ServerConfig from "../config.ts"; @@ -749,6 +750,24 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => { // Runtime reconciliation writes restart cancellations under this command // prefix, which the live terminal-run listener skips. +// Collects the SQL text of every statement run under the returned tracer. +const traceSqlStatements = () => { + const statements: Array = []; + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options); + const end = span.end.bind(span); + span.end = (endTime, exit) => { + end(endTime, exit); + const query = span.attributes.get("db.query.text"); + if (typeof query === "string") statements.push(query); + }; + return span; + }, + }); + return { statements, tracer }; +}; + const reconcileCommandId = (name: string) => CommandId.make(`command:runtime-reconcile:${name}`); const parentProviderThreadId = (threadId: ThreadId) => @@ -1578,6 +1597,111 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); + it.effect("settles only the current delivery of a parent with long delivery history", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:delivery-history"); + const runId = RunId.make("run:delivery-history"); + const taskId = NodeId.make("node:delivery-history-task"); + const currentMessageId = MessageId.make(`message:delegated-delivery:${threadId}`); + const currentRunId = RunId.make("run:delivery-history:current"); + const HISTORY = 40; + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make("project:delivery-history"), + runId, + rootNodeId: NodeId.make("node:delivery-history-root"), + taskId, + deliveryState: "claimed", + completionWake: "always", + deliveryTaskIds: [taskId], + now, + }); + const deliveryMessage = (id: MessageId, deliveryRunId: RunId) => ({ + id: EventId.make(`event:${deliveryRunId}:message`), + type: "message.updated" as const, + threadId, + runId: deliveryRunId, + occurredAt: now, + payload: { + id, + threadId, + runId: deliveryRunId, + nodeId: null, + role: "user" as const, + text: `Delegated task ${taskId} reached a terminal state.`, + attachments: [], + streaming: false, + createdBy: "agent" as const, + creationSource: "server" as const, + createdAt: now, + updatedAt: now, + delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [taskId] }, + }, + }); + // Earlier deliveries that already settled. Each one still owns a + // delegated message and a terminal run. + const history = Array.from({ length: HISTORY }, (_, index) => { + const historyRunId = RunId.make(`run:delivery-history:${index}`); + const messageId = MessageId.make(`message:delivery-history:${index}`); + return [ + deliveryMessage(messageId, historyRunId), + runEvent({ + threadId, + runId: historyRunId, + ordinal: index + 2, + status: "completed", + now, + providerThreadId: parentProviderThreadId(threadId), + userMessageId: messageId, + }), + ]; + }).flat(); + yield* eventSink.write({ + commandId: reconcileCommandId("delivery-history"), + events: [ + ...history, + deliveryMessage(currentMessageId, currentRunId), + runEvent({ + threadId, + runId: currentRunId, + ordinal: HISTORY + 2, + status: "completed", + now, + providerThreadId: parentProviderThreadId(threadId), + userMessageId: currentMessageId, + }), + ], + }); + + const { statements, tracer } = traceSqlStatements(); + yield* orchestrator.recoverDelegatedTasks.pipe(Effect.withTracer(tracer)); + + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + projection.subagents.find((row) => row.id === taskId)?.completionDelivery?.state, + "delivered", + ); + assert.isNull(projection.runs.find((row) => row.id === runId)?.delegatedCompletion?.delivery); + // Recovery reads the delivery message once, for the current delivery + // run only. History must not cost one thread reload per past delivery. + assert.lengthOf( + statements.filter((statement) => + statement.includes("FROM orchestration_v2_projection_messages AS message"), + ), + 1, + ); + + // A second recovery finds nothing open on this thread and changes nothing. + yield* orchestrator.recoverDelegatedTasks; + const again = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(again.runs, projection.runs); + assert.deepEqual(again.subagents, projection.subagents); + }), + ); + it.effect("settles a cancelled child whose held wakes wait behind it", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts b/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts new file mode 100644 index 000000000000..9d239d34b65f --- /dev/null +++ b/apps/server/src/orchestration-v2/DelegatedTaskQuestionReactor.ts @@ -0,0 +1,185 @@ +import { + CommandId, + MessageId, + type OrchestrationV2DomainEvent, + type OrchestrationV2RuntimeRequest, + type OrchestrationV2Subagent, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { reportLabel } from "@t3tools/provider-core/server/notification"; + +import { forkParked } from "../serverActivation.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; + +/** + * Wakes the parent of an app-owned delegated task when the task asks a question. The question + * blocks the task until someone answers it, and the user rarely watches child threads, so the + * parent agent is told to answer it or to ask the user. Only questions are routed: approvals + * cannot be answered through the pending request tools. + */ +export class DelegatedTaskQuestionReactor extends Context.Service< + DelegatedTaskQuestionReactor, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/orchestration-v2/DelegatedTaskQuestionReactor") {} + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + + const wakeParent = Effect.fnUntraced(function* ( + task: OrchestrationV2Subagent, + request: OrchestrationV2RuntimeRequest, + ) { + if (task.childThreadId === null) return; + const key = `${task.threadId}:${request.id}`; + const label = reportLabel(task.title?.trim() || task.prompt); + const situation = + request.responseCapability.type === "message" + ? `Delegated task ${task.id} asked a question and is still working.` + : `Delegated task ${task.id} is blocked on a question and cannot continue until it is answered.`; + yield* engine.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:delegated-task-question:${key}`), + threadId: task.threadId, + messageId: MessageId.make(`message:delegated-task-question:${key}`), + text: `${situation} Read it with t3_pending_request_read using threadId ${task.childThreadId} and requestId ${request.id}. Answer it with t3_pending_request_respond when the answer follows from the task or the user's instructions; otherwise ask the user, then answer it. If it is no longer pending, it was answered or dismissed.`, + notification: { + source: { kind: "delegated_task", taskIds: [task.id], childThreadId: task.childThreadId }, + outcome: "updated", + summary: `Delegated task${label === undefined ? "" : ` "${label}"`} has a question`, + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + }); + + const handle: DelegatedTaskQuestionReactor["Service"]["handle"] = (event) => + Effect.gen(function* () { + if (event.type === "run.updated") { + if (!["completed", "failed", "waiting"].includes(event.payload.status)) return; + const parent = yield* projections.getThreadRecords(event.threadId, ["subagents"]); + if (parent.thread.archivedAt !== null || parent.thread.deletedAt !== null) return; + for (const task of parent.subagents) { + if ( + task.origin !== "app_owned" || + task.runId !== event.payload.id || + task.completionWake !== "settled_only" || + task.completionDelivery?.state === "disposed" || + task.childThreadId === null || + ["completed", "failed", "cancelled", "interrupted"].includes(task.status) + ) { + continue; + } + const child = yield* projections.getThreadRecords(task.childThreadId, [ + "runtimeRequests", + ]); + for (const request of child.runtimeRequests) { + if ( + request.kind !== "user_input" || + request.status !== "pending" || + request.responseCapability.type !== "live" + ) { + continue; + } + yield* wakeParent(task, request).pipe( + Effect.catchCause((cause) => + Effect.logWarning("catching up a delegated task question failed", { + taskId: task.id, + requestId: request.id, + cause, + }), + ), + ); + } + } + return; + } + if (event.type !== "runtime-request.updated" || event.payload.kind !== "user_input") { + return; + } + const child = yield* projections.getThread(event.threadId); + const parentThreadId = child.lineage.parentThreadId; + if (parentThreadId === null) return; + const request = yield* projections.getRuntimeRequest(event.threadId, event.payload.id); + // Keyed by the request, so a request updated while still pending wakes the parent once. + const key = `${parentThreadId}:${event.payload.id}`; + const messageId = MessageId.make(`message:delegated-task-question:${key}`); + if (event.payload.status !== "pending" || request?.status !== "pending") { + const parent = yield* projections.getThreadRecords(parentThreadId, ["runs"]); + const queued = parent.runs.find( + (run) => run.status === "queued" && run.userMessageId === messageId, + ); + if (queued !== undefined) { + yield* engine.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make(`server:delegated-task-question-cancel:${key}`), + threadId: parentThreadId, + runId: queued.id, + }); + } + return; + } + const parent = yield* projections.getThreadRecords(parentThreadId, ["subagents", "runs"]); + const { runs } = yield* projections.getThreadRecords(child.id, ["runs"]); + const run = + runs.find((run) => run.id === event.runId) ?? + runs.toSorted((a, b) => b.ordinal - a.ordinal)[0]; + const taskId = + run?.delegatedTaskId ?? + (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined); + const task = parent.subagents.find( + (candidate) => candidate.origin === "app_owned" && candidate.id === taskId, + ); + if ( + task === undefined || + parent.thread.archivedAt !== null || + parent.thread.deletedAt !== null + ) { + return; + } + // A blocking delegate_task wait delivers the question itself. + if ( + task.completionWake === "settled_only" && + event.payload.responseCapability.type === "live" && + parent.runs.some( + (run) => + run.id === task.runId && + (run.status === "preparing" || run.status === "starting" || run.status === "running"), + ) + ) { + return; + } + yield* wakeParent(task, request); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("waking the parent of a delegated task question failed", { + threadId: event.threadId, + cause, + }), + ), + ); + + const start: DelegatedTaskQuestionReactor["Service"]["start"] = () => + forkParked( + Stream.runForEach(engine.streamDomainEvents, handle).pipe( + Effect.catchCause((cause) => + Effect.logWarning("delegated task question event stream failed", { cause }), + ), + ), + ); + + return { start, handle } satisfies DelegatedTaskQuestionReactor["Service"]; +}); + +export const layer = Layer.effect(DelegatedTaskQuestionReactor, make); diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 93cc4f6b6930..ecdd62577fac 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -105,6 +105,7 @@ function layerExecutorFor(input: { shutdown: Effect.void, open: () => Effect.die("unused open"), get: () => Effect.succeed(Option.none()), + isLive: () => Effect.succeed(false), close: () => Effect.void, closeInstance: () => Effect.void, release: () => record("release"), diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 8e5fca79cf55..de616556b4eb 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -4,6 +4,7 @@ import { MessageId, EventId, NodeId, + type OrchestrationV2DomainEvent, PlanId, ProjectId, ProviderDriverKind, @@ -23,6 +24,8 @@ import * as Layer from "effect/Layer"; import * as SqlClient from "effect/sql/SqlClient"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as DelegatedTaskQuestionReactor from "./DelegatedTaskQuestionReactor.ts"; +import * as EventSink from "./EventSink.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; @@ -624,3 +627,336 @@ it.effect("keeps delegated child pull-request links independent of the parent", assert.deepEqual(parentAfterChildLink.thread.pullRequests, parent.thread.pullRequests); }).pipe(Effect.provide(layerTest)), ); + +it.effect("wakes the parent once when its delegated task asks a question", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const reactor = yield* DelegatedTaskQuestionReactor.DelegatedTaskQuestionReactor; + const parentThreadId = ThreadId.make("thread:question-parent"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create-question-parent"), + threadId: parentThreadId, + projectId: ProjectId.make("project:question"), + title: "Parent", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start-question-parent"), + threadId: parentThreadId, + messageId: MessageId.make("message:question-parent"), + text: "Delegate the research", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const parentRun = (yield* projections.getThreadProjection(parentThreadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("delegate-question-task"), + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "Research the sources", + completionWake: "settled_only", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + createdBy: "agent", + creationSource: "mcp", + }); + const task = (yield* projections.getThreadProjection(parentThreadId)).subagents[0]!; + const childRun = (yield* projections.getThreadRecords(task.childThreadId!, ["runs"])).runs[0]!; + const now = yield* DateTime.now; + const requestEvent = ( + eventId: string, + requestId: string, + responseCapability: "live" | "message" = "message", + kind: "user_input" | "command" = "user_input", + run = childRun, + ) => + ({ + id: EventId.make(eventId), + type: "runtime-request.updated", + threadId: task.childThreadId!, + runId: run.id, + occurredAt: now, + payload: { + id: RuntimeRequestId.make(requestId), + nodeId: run.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind, + status: "pending", + responseCapability: + responseCapability === "live" + ? { type: "live", providerSessionId: ProviderSessionId.make("session:question") } + : { type: "message" }, + createdAt: now, + resolvedAt: null, + }, + }) satisfies OrchestrationV2DomainEvent; + const question = requestEvent("event:question", "request:question", "live"); + const asyncQuestion = requestEvent("event:async-question", "request:async-question"); + const answered = requestEvent("event:answered", "request:answered", "live"); + const approval = requestEvent("event:approval", "request:approval", "message", "command"); + const eventSink = yield* EventSink.EventSinkV2; + yield* eventSink.write({ + events: [question, asyncQuestion, answered, approval], + }); + + yield* reactor.handle(question); + assert.isFalse( + (yield* projections.getThreadProjection(parentThreadId)).messages.some( + (message) => message.notification !== undefined, + ), + ); + yield* reactor.handle(asyncQuestion); + assert.equal( + (yield* projections.getThreadProjection(parentThreadId)).messages.filter( + (message) => message.notification !== undefined, + ).length, + 1, + ); + yield* reactor.handle(asyncQuestion); + yield* reactor.handle(answered); + yield* eventSink.write({ + events: [ + { + ...answered, + id: EventId.make("event:answered-resolved"), + payload: { ...answered.payload, status: "resolved", resolvedAt: now }, + }, + ], + }); + yield* reactor.handle(answered); + yield* reactor.handle(approval); + + const wakes = (yield* projections.getThreadProjection(parentThreadId)).messages.filter( + (message) => message.notification !== undefined, + ); + assert.include(wakes[0]?.text, "asked a question and is still working"); + assert.deepEqual( + wakes.map((message) => message.notification), + [ + { + source: { + kind: "delegated_task", + taskIds: [task.id], + childThreadId: task.childThreadId!, + }, + outcome: "updated", + summary: 'Delegated task "Research the sources" has a question', + }, + ], + ); + + const wakeRun = (yield* projections.getThreadRecords(parentThreadId, ["runs"])).runs.find( + (run) => run.userMessageId === wakes[0]!.id, + )!; + assert.equal(wakeRun.status, "queued"); + const resolved = { + ...asyncQuestion, + id: EventId.make("event:question-resolved"), + payload: { ...asyncQuestion.payload, status: "resolved" as const, resolvedAt: now }, + }; + yield* eventSink.write({ events: [resolved] }); + yield* reactor.handle(resolved); + assert.equal( + (yield* projections.getThreadRecords(parentThreadId, ["runs"])).runs.find( + (run) => run.id === wakeRun.id, + )?.status, + "cancelled", + ); + const parentCompleted = { + id: EventId.make("event:question-parent-completed"), + type: "run.updated", + threadId: parentThreadId, + runId: parentRun.id, + occurredAt: now, + payload: { ...parentRun, status: "completed", completedAt: now }, + } satisfies OrchestrationV2DomainEvent; + for (const status of [ + "preparing", + "starting", + "running", + "queued", + "cancelled", + "rolled_back", + "interrupted", + ] as const) { + yield* reactor.handle({ ...parentCompleted, payload: { ...parentRun, status } }); + } + assert.equal( + (yield* projections.getThreadRecords(parentThreadId, ["messages"])).messages.length, + 2, + ); + yield* eventSink.write({ events: [parentCompleted] }); + for (const state of ["disposed", "pending"] as const) { + yield* eventSink.write({ + events: [ + { + id: EventId.make(`event:question-task-${state}`), + type: "subagent.updated", + threadId: parentThreadId, + occurredAt: now, + payload: { ...task, completionDelivery: { state, observedByRunId: null } }, + }, + ], + }); + yield* reactor.handle(parentCompleted); + if (state === "disposed") { + assert.equal( + (yield* projections.getThreadRecords(parentThreadId, ["messages"])).messages.length, + 2, + ); + } + } + yield* reactor.handle(parentCompleted); + const caughtUp = (yield* projections.getThreadProjection(parentThreadId)).messages.filter( + (message) => message.notification !== undefined, + ); + assert.equal(caughtUp.length, 2); + assert.equal( + caughtUp.filter((message) => message.text.includes(`requestId ${question.payload.id}.`)) + .length, + 1, + ); + assert.include(caughtUp[1]?.text, "is blocked on a question"); + assert.isFalse( + caughtUp.some((message) => message.text.includes(`requestId ${answered.payload.id}.`)), + ); + yield* reactor.handle(question); + assert.equal( + (yield* projections.getThreadProjection(parentThreadId)).messages.filter( + (message) => message.notification !== undefined, + ).length, + 2, + ); + const terminalQuestion = requestEvent( + "event:terminal-question", + "request:terminal-question", + "live", + ); + yield* eventSink.write({ events: [terminalQuestion] }); + yield* reactor.handle(terminalQuestion); + assert.equal( + (yield* projections.getThreadProjection(parentThreadId)).messages.filter( + (message) => message.notification !== undefined, + ).length, + 3, + ); + yield* eventSink.write({ + events: [ + { + id: EventId.make("event:question-parent-running-again"), + type: "run.updated", + threadId: parentThreadId, + runId: parentRun.id, + occurredAt: now, + payload: { ...parentRun, status: "running", completedAt: null }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "delegated_task.wake-policy", + commandId: CommandId.make("terminal-question-wait-ended"), + parentThreadId, + taskId: task.id, + completionWake: "always", + }); + const upgradedQuestion = requestEvent( + "event:upgraded-question", + "request:upgraded-question", + "live", + ); + yield* eventSink.write({ events: [upgradedQuestion] }); + yield* reactor.handle(upgradedQuestion); + assert.equal( + (yield* projections.getThreadProjection(parentThreadId)).messages.filter( + (message) => message.notification !== undefined, + ).length, + 4, + ); + const waitDelivered = requestEvent("event:wait-delivered", "request:wait-delivered", "live"); + const waitDeliveredParentCompleted = { + ...parentCompleted, + id: EventId.make("event:wait-delivered-parent-completed"), + }; + yield* eventSink.write({ events: [waitDelivered, waitDeliveredParentCompleted] }); + yield* reactor.handle(waitDeliveredParentCompleted); + assert.isFalse( + (yield* projections.getThreadProjection(parentThreadId)).messages.some((message) => + message.text.includes(`requestId ${waitDelivered.payload.id}.`), + ), + ); + yield* eventSink.write({ + commandId: CommandId.make("command:runtime-reconcile:question-followup"), + events: [ + { + id: EventId.make("event:question-child-completed"), + type: "run.updated", + threadId: task.childThreadId!, + occurredAt: now, + payload: { ...childRun, status: "completed", completedAt: now }, + }, + { + id: EventId.make("event:question-task-completed"), + type: "subagent.updated", + threadId: parentThreadId, + occurredAt: now, + payload: { + ...task, + status: "completed", + result: "Sources researched.", + completedAt: now, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("question-followup"), + threadId: task.childThreadId!, + messageId: MessageId.make("message:question-followup"), + text: "Check the sources again", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const followup = (yield* projections.getThreadRecords(task.childThreadId!, ["runs"])).runs.find( + (run) => run.userMessageId === "message:question-followup", + )!; + assert.isDefined(followup.delegatedTaskId); + assert.notEqual(followup.delegatedTaskId, task.id); + const followupQuestion = requestEvent( + "event:followup-question", + "request:followup-question", + "live", + "user_input", + followup, + ); + yield* eventSink.write({ events: [followupQuestion] }); + yield* reactor.handle(followupQuestion); + const followupWake = (yield* projections.getThreadRecords(parentThreadId, [ + "messages", + ])).messages.find((message) => + message.text.includes(`requestId ${followupQuestion.payload.id}`), + )!; + assert.deepEqual(followupWake.notification?.source, { + kind: "delegated_task", + taskIds: [followup.delegatedTaskId], + childThreadId: task.childThreadId!, + }); + }).pipe(Effect.provide(DelegatedTaskQuestionReactor.layer.pipe(Layer.provideMerge(layerTest)))), +); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 98e5f58d3340..15dfdaaea062 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -941,6 +941,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // Command decisions need control records, not historical assistant/tool output. // Handoff preparation explicitly reads its history after choosing a strategy. + // This runs inside the write transaction for every command, so finished leaf + // nodes of finished runs stay unread: busy threads hold thousands of them. const readCommandProjection = (threadId: ThreadId) => projectionStore .getThreadRecords( @@ -959,7 +961,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio "checkpointScopes", "contextTransfers", ], - { turnItemTypes: ["user_message", "error"], messageRoles: ["user"] }, + { + turnItemTypes: ["user_message", "error"], + messageRoles: ["user"], + omitSettledLeafNodes: true, + }, ) .pipe( Effect.map((records): OrchestrationV2ThreadProjection => ({ @@ -4074,10 +4080,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); - // A selection the provider applies on its next turn restarts the run when - // the provider can restart it. Otherwise the steer joins the running turn - // and the selection waits for the next one, rather than failing the steer. - const turnCapabilities = session.providerSession.capabilities.turns; + // A selection the provider applies on its next turn joins the running + // turn as a steer and waits for the next turn. Restarting the turn for it + // would end the turn's native subagents, which a steer must never do. const selectionMustApplyNow = selectionChanged && (providerInstanceChanged || selectionTransition?.type !== "apply_on_next_turn"); @@ -4087,12 +4092,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: input.command.threadId, providerInstanceId: targetRun.providerInstanceId, capabilities: session.providerSession.capabilities, - forceRestart: - input.forceRestart || - selectionMustApplyNow || - (selectionChanged && - turnCapabilities.supportsInterrupt && - turnCapabilities.supportsSteeringByInterruptRestart), + forceRestart: input.forceRestart || selectionMustApplyNow, }), ); @@ -10484,6 +10484,64 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(progress.resultRun === undefined ? {} : { resultRun: progress.resultRun }), }); } + + const { resultRun } = progress; + if (progress.state !== "result_available" || resultRun === undefined) return; + const status = delegatedTaskTerminalStatus(runOutcome(resultRun)); + if (status !== "cancelled" && status !== "interrupted") return; + if ( + yield* childAwaitsRestartContinuation( + childControls.runs, + resultRun, + options?.settledContinuationOf, + ) + ) + return; + // Cancelled or interrupted tasks must not leave async questions that resume the child. + // Callers hold the parent lock; dismiss takes the child lock, as follow-up intake does. + const { runtimeRequests } = yield* projectionStore.getThreadRecords(childThreadId, [ + "runtimeRequests", + ]); + const pendingQuestions = runtimeRequests.filter( + (request) => + request.status === "pending" && + request.kind === "user_input" && + request.responseCapability.type === "message", + ); + if (pendingQuestions.length === 0) return; + const { nodes } = yield* projectionStore.getThreadRecords(childThreadId, ["nodes"]); + const resultRunIds = new Set(); + let run: OrchestrationV2Run | undefined = resultRun; + while (run !== undefined && !resultRunIds.has(run.id)) { + resultRunIds.add(run.id); + const previousRunId: RunId | undefined = run.restartContinuationOfRunId; + run = + previousRunId === undefined + ? undefined + : childControls.runs.find((candidate) => candidate.id === previousRunId); + } + for (const request of pendingQuestions) { + if ( + nodes.some( + (node) => + node.id === request.nodeId && node.runId !== null && resultRunIds.has(node.runId), + ) + ) { + yield* dispatchWithReceipt({ + type: "thread.user-input.dismiss", + commandId: CommandId.make(`command:system:delegated-task-question:${request.id}`), + threadId: childThreadId, + requestId: request.id, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to dismiss task question", { + requestId: request.id, + cause, + }), + ), + ); + } + } }); const finalizeDelegatedCompletionDelivery = (threadId: ThreadId, runId: RunId) => @@ -11379,6 +11437,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // queue.resume command arrives. const recoverDelegatedTasks = Effect.gen(function* () { yield* projectionStore.getRecoveryThreadIds("subagent-results").pipe( + // Candidate counts let a startup trace show whether recovery scales + // with pending work or with history. + Effect.tap((threadIds) => + Effect.annotateCurrentSpan("recovery.subagentResultThreads", threadIds.length), + ), Effect.flatMap((threadIds) => Effect.forEach( threadIds, @@ -11406,6 +11469,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); yield* projectionStore.getRecoveryThreadIds("delegated-completions").pipe( + Effect.tap((threadIds) => + Effect.annotateCurrentSpan("recovery.delegatedCompletionThreads", threadIds.length), + ), Effect.flatMap((threadIds) => Effect.forEach( threadIds, @@ -11414,18 +11480,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .withLock( threadId, Effect.gen(function* () { - const projection = yield* projectionStore.getThreadRecords(threadId, [ - "runs", - "messages", - ]); + const projection = yield* projectionStore.getThreadRecords(threadId, ["runs"]); + // Only the run that consumed a cohort's current delivery + // message can settle it. A long-lived parent keeps every + // past delivery run, and finalizing each of them would + // reload the thread once per historical delivery. + const openDeliveryMessageIds = new Set( + projection.runs.flatMap((run) => + run.delegatedCompletion?.delivery == null + ? [] + : [run.delegatedCompletion.delivery.messageId], + ), + ); const terminalDeliveryRunIds = projection.runs - .filter((run) => delegatedTaskTerminalStatus(run.status) !== null) - .filter((run) => - projection.messages.some( - (message) => - message.id === run.userMessageId && - message.delegatedCompletion !== undefined, - ), + .filter( + (run) => + delegatedTaskTerminalStatus(run.status) !== null && + openDeliveryMessageIds.has(run.userMessageId), ) .map((run) => run.id); for (const runId of terminalDeliveryRunIds) { @@ -11434,9 +11505,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const refreshed = terminalDeliveryRunIds.length === 0 ? projection - : yield* projectionStore.getThreadRecords(threadId, ["runs", "messages"], { - messageRoles: ["user"], - }); + : yield* projectionStore.getThreadRecords(threadId, ["runs"]); for (const run of refreshed.runs) { if ( run.delegatedCompletion?.delivery !== null && diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index d2bd4a13ffec..0729b0a93f16 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -382,6 +382,89 @@ const threadWorktreePathsReadActiveThreads = Effect.gen(function* () { ]); }); +const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = yield* addRolledBackRecoveryCandidate("settled-leaf-nodes"); + const settledRun = (yield* store.getThreadProjection(threadId)).runs[0]!; + const activeRun = { + ...settledRun, + id: RunId.make("run:settled-leaf-nodes:active"), + ordinal: 2, + userMessageId: MessageId.make("message:settled-leaf-nodes:active"), + rootNodeId: NodeId.make("node:settled-leaf-nodes:active-root"), + status: "running" as const, + completedAt: null, + }; + yield* store.apply({ + id: EventId.make("event:settled-leaf-nodes:active-run"), + type: "run.created", + threadId, + runId: activeRun.id, + nodeId: activeRun.rootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: activeRun, + }); + const nodes = [ + ["settled-root", settledRun, "root_turn", "completed"], + ["settled-tool", settledRun, "tool_call", "completed"], + ["settled-message", settledRun, "assistant_message", "failed"], + ["settled-reasoning", settledRun, "reasoning", "cancelled"], + ["settled-subagent", settledRun, "subagent", "completed"], + ["settled-run-live-tool", settledRun, "tool_call", "running"], + ["active-run-done-tool", activeRun, "tool_call", "completed"], + ] as const; + for (const [name, run, kind, status] of nodes) { + const id = NodeId.make(`node:settled-leaf-nodes:${name}`); + yield* store.apply({ + id: EventId.make(`event:settled-leaf-nodes:${name}`), + type: "node.updated", + threadId, + runId: run.id, + nodeId: id, + driver, + occurredAt: now, + payload: { + id, + threadId, + runId: run.id, + rootNodeId: kind === "root_turn" ? id : run.rootNodeId!, + parentNodeId: kind === "root_turn" ? null : run.rootNodeId, + kind, + status, + countsForRun: kind === "root_turn", + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: status === "running" ? null : now, + }, + }); + } + const nodeNames = (records: { readonly nodes: ReadonlyArray<{ readonly id: string }> }) => + records.nodes + .map((node) => node.id.replace("node:settled-leaf-nodes:", "")) + .filter((name) => nodes.some(([candidate]) => candidate === name)) + .toSorted(); + + assert.deepEqual( + nodeNames(yield* store.getThreadRecords(threadId, ["nodes"], { omitSettledLeafNodes: true })), + ["active-run-done-tool", "settled-root", "settled-run-live-tool", "settled-subagent"], + ); + assert.deepEqual( + nodeNames(yield* store.getThreadRecords(threadId, ["nodes"])), + nodes.map(([name]) => name).toSorted(), + ); +}); + +it.effect("memory command reads skip finished leaf nodes of finished runs", () => + commandReadsSkipSettledLeafNodes.pipe(Effect.provide(ProjectionStore.layerMemory)), +); + it.effect("memory worktree path lookup reads only active threads", () => threadWorktreePathsReadActiveThreads.pipe(Effect.provide(ProjectionStore.layerMemory)), ); @@ -657,6 +740,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { assert.deepEqual(recovery?.restartCancelledBackgroundWork, work); }), ); + it.effect( + "command reads skip finished leaf nodes of finished runs", + () => commandReadsSkipSettledLeafNodes, + ); it.effect("limits turn-start history to the requested runs, including an empty selection", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 7443eb7aab8d..ad92e25c8516 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -304,7 +304,39 @@ export interface ProjectionRecordFilter { readonly runIds?: ReadonlyArray; readonly turnItemTypes?: ReadonlyArray; readonly turnItemStatuses?: ReadonlyArray; + // Skips finished tool call, assistant message and reasoning nodes of finished + // runs. Command decisions only read root, subagent and active-run nodes. + readonly omitSettledLeafNodes?: boolean; } + +type ProjectionNode = OrchestrationV2ThreadProjection["nodes"][number]; +type ProjectionRun = OrchestrationV2ThreadProjection["runs"][number]; +const settledLeafNodeKinds: ReadonlySet = new Set([ + "tool_call", + "assistant_message", + "reasoning", +]); +const settledNodeStatuses: ReadonlySet = new Set([ + "completed", + "interrupted", + "failed", + "cancelled", + "rolled_back", +]); +const activeRunStatuses: ReadonlySet = new Set([ + "preparing", + "queued", + "starting", + "running", + "waiting", +]); + +// In-memory twin of the omitSettledLeafNodes SQL clause in readCanonicalProjection. +const isSettledLeafNode = (node: ProjectionNode, runs: ReadonlyArray) => + settledLeafNodeKinds.has(node.kind) && + settledNodeStatuses.has(node.status) && + node.runId !== null && + !runs.some((run) => run.id === node.runId && activeRunStatuses.has(run.status)); export type ProjectionRecordField = Exclude< keyof OrchestrationV2ThreadProjection, "thread" | "updatedAt" | "visibleTurnItems" @@ -3069,9 +3101,23 @@ export const layer: Layer.Layer = : window === undefined ? sql` SELECT payload_json - FROM orchestration_v2_projection_nodes - WHERE thread_id = ${threadId} - ORDER BY COALESCE(started_at, ''), node_id ASC + FROM orchestration_v2_projection_nodes AS node + WHERE node.thread_id = ${threadId} + ${ + filter?.omitSettledLeafNodes === true + ? sql`AND NOT ( + node.kind IN ('tool_call', 'assistant_message', 'reasoning') + AND node.status IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back') + AND node.run_id IS NOT NULL + AND NOT EXISTS ( + SELECT 1 FROM orchestration_v2_projection_runs AS run + WHERE run.run_id = node.run_id + AND run.status IN ('preparing', 'queued', 'starting', 'running', 'waiting') + ) + )` + : sql`` + } + ORDER BY COALESCE(node.started_at, ''), node.node_id ASC ` : sql` -- Keep retained IDs outermost so SQLite looks up each node by its @@ -6423,6 +6469,10 @@ export const layerMemory: Layer.Layer = Layer.effect( filter.turnItemStatuses.includes(row.status)) && (filter?.turnItemRunId === undefined || filter.turnItemRunId === row.runId), ), + nodes: + filter?.omitSettledLeafNodes === true + ? projection.nodes.filter((node) => !isSettledLeafNode(node, projection.runs)) + : projection.nodes, }; return Object.fromEntries([ ["thread", projection.thread], diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 7a5bc9e478d7..f781c1fadd07 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2925,6 +2925,25 @@ it.effect( }), ); +it.effect("ProviderSessionManagerV2 checks liveness without delaying idle release", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const { providerSessionId } = yield* openSessionWithBackgroundCommand( + "provider-session-manager-is-live", + ); + yield* TestClock.adjust("600 millis"); + assert.isTrue(yield* manager.isLive(providerSessionId)); + yield* TestClock.adjust("600 millis"); + yield* Effect.yieldNow; + assert.isFalse(yield* manager.isLive(providerSessionId)); + }); + + yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 1000 }))); + }), +); + it.effect("ProviderSessionManagerV2 clears the background roster of an idle-released session", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 1890e8d2822b..107f2eef2173 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -169,6 +169,8 @@ export interface ProviderSessionManagerV2Shape { Option.Option, ProviderSessionManagerV2Error >; + /** Whether the session's runtime is running. Unlike `get`, not activity. */ + readonly isLive: (providerSessionId: ProviderSessionId) => Effect.Effect; readonly close: ( providerSessionId: ProviderSessionId, ) => Effect.Effect; @@ -2361,6 +2363,10 @@ export const layerWithOptions = ( return exposedRuntime; }), ), + isLive: (providerSessionId) => + Ref.get(sessions).pipe( + Effect.map((current) => current.has(sessionKey(providerSessionId))), + ), get: (providerSessionId) => Effect.gen(function* () { const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index fc3465e6885f..52515e72baa4 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -273,6 +273,7 @@ it.effect( Effect.succeed( providerSessionId === oldSessionId ? Option.some(runtime) : Option.none(), ), + isLive: (providerSessionId) => Effect.succeed(providerSessionId === oldSessionId), close: () => Effect.void, closeInstance: () => Effect.void, release: () => Effect.void, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 2097550090c1..04d323155b4f 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -1,3 +1,4 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it, vi } from "vite-plus/test"; import { it as effectIt } from "@effect/vitest"; import { @@ -22,12 +23,16 @@ import * as NodeOS from "node:os"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import * as GitWorkflow from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; @@ -99,7 +104,8 @@ it("does not commit running state when inherited background routing cannot be re Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({}), Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }), IdAllocator.layer, - Layer.succeed(FileSystem.FileSystem, { exists: () => Effect.succeed(false) } as never), + Path.layer, + FileSystem.layerNoop({ exists: () => Effect.succeed(false) }), Layer.mock(GitWorkflow.GitWorkflowService)({ pruneWorktrees, createWorktree }), Layer.mock(ProjectService.ProjectService)({ getById: () => @@ -108,6 +114,10 @@ it("does not commit running state when inherited background routing cannot be re ), }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadRecords: () => { + projectionReadCount += 1; + return Effect.succeed(projection); + }, getTurnStartContext: () => { projectionReadCount += 1; return Effect.succeed({ @@ -145,7 +155,7 @@ it("does not commit running state when inherited background routing cannot be re .pipe(Effect.flip); expect(error._tag).toBe("ProviderTurnStartError"); - expect(projectionReadCount).toBe(2); + expect(projectionReadCount).toBe(3); expect(pruneWorktrees).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project" }); expect(createWorktree).toHaveBeenCalledWith({ cwd: "/tmp/provider-turn-start-project", @@ -159,6 +169,8 @@ it("does not commit running state when inherited background routing cannot be re function makeLocalCommandHarness(input: { readonly text: string; + readonly worktreePath?: string; + readonly fileSystem?: FileSystem.FileSystem; readonly previousNativeSession?: boolean; readonly previousMessages?: ReadonlyArray; readonly logoutFailure?: string; @@ -251,8 +263,9 @@ function makeLocalCommandHarness(input: { thread: { id: threadId, activeProviderThreadId: providerThreadId, - branch: null, - worktreePath: null, + projectId: ProjectId.make("project-native-account-command"), + branch: input.worktreePath === undefined ? null : "feature/restore", + worktreePath: input.worktreePath ?? null, lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, } as OrchestrationV2ThreadProjection["thread"], runs: [ @@ -606,6 +619,28 @@ function makeLocalCommandHarness(input: { return { committed, storedEvents: [] }; }), ); + const resolveRuntimePolicy = vi.fn( + ({ thread }: Parameters[0]) => + Effect.succeed({ + cwd: + thread.worktreePath ?? + (input.deliverTurn === undefined ? "/tmp/native-account-command" : NodeOS.tmpdir()), + } as never), + ); + const createWorktree = vi.fn(() => Effect.succeed({} as never)); + const getThreadRecords = vi.fn(() => + Effect.succeed(projection), + ); + const getTurnStartContext = vi.fn(() => + Effect.succeed({ + ...projection, + hasConversation: projection.messages.some( + (m) => + m.role === "user" && + (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), + ), + }), + ); const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( @@ -644,19 +679,21 @@ function makeLocalCommandHarness(input: { }), }), IdAllocator.layer, - FileSystem.layerNoop({}), - Layer.mock(GitWorkflow.GitWorkflowService)({}), - Layer.mock(ProjectService.ProjectService)({}), + Path.layer, + input.fileSystem === undefined + ? FileSystem.layerNoop({ exists: () => Effect.succeed(true) }) + : Layer.succeed(FileSystem.FileSystem, input.fileSystem), + Layer.mock(GitWorkflow.GitWorkflowService)({ + pruneWorktrees: () => Effect.void, + createWorktree, + }), + Layer.mock(ProjectService.ProjectService)({ + getById: () => + Effect.succeed(Option.some({ workspaceRoot: "/tmp/native-account-project" } as never)), + }), Layer.mock(ProjectionStore.ProjectionStoreV2)({ - getTurnStartContext: () => - Effect.succeed({ - ...projection, - hasConversation: projection.messages.some( - (m) => - m.role === "user" && - (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), - ), - }), + getThreadRecords, + getTurnStartContext, getRuntimeRecoveryProjection: () => Effect.as(failReadIfRunning, { ...projection, @@ -680,15 +717,19 @@ function makeLocalCommandHarness(input: { Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }), Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }), Layer.mock(RuntimePolicy.RuntimePolicyV2)({ - resolve: () => - Effect.succeed( - (input.deliverTurn === undefined ? {} : { cwd: NodeOS.tmpdir() }) as never, - ), + resolve: resolveRuntimePolicy, }), ), ), ); return { + getThreadRecords, + getTurnStartContext, + setProjection: (next: OrchestrationV2ThreadProjection) => { + projection = next; + }, + resolveRuntimePolicy, + createWorktree, open, deliveredTexts, resumedNativeIds, @@ -713,6 +754,163 @@ function makeLocalCommandHarness(input: { }; } +effectIt.effect.each(["cleanup-first", "startup-first"])( + "coordinates provider startup with %s", + (order) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspaceRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-start-" }); + const worktreePath = path.join(workspaceRoot, "worktree"); + yield* fileSystem.makeDirectory(worktreePath); + const release = yield* Deferred.make(); + const openEntered = yield* Deferred.make(); + const harness = makeLocalCommandHarness({ + text: "Continue", + worktreePath, + fileSystem, + failReadsAfterRunning: true, + }); + harness.createWorktree.mockImplementation(() => + fileSystem.makeDirectory(worktreePath).pipe(Effect.as({} as never), Effect.orDie), + ); + const open = harness.open.getMockImplementation()!; + harness.open.mockImplementation(() => + Effect.gen(function* () { + expect(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)).toBe(true); + yield* Deferred.succeed(openEntered, undefined); + if (order === "startup-first") yield* Deferred.await(release); + return yield* open(); + }), + ); + let cleanupEntered = false; + const cleanupEffect = withWorkspaceLease( + worktreePath, + Effect.gen(function* () { + cleanupEntered = true; + if (order === "cleanup-first") yield* Deferred.await(release); + else { + expect(harness.projection().providerSessions).toHaveLength(1); + expect(harness.projection().runs.at(-1)?.status).toBe("running"); + } + yield* fileSystem.remove(worktreePath, { recursive: true, force: true }); + }), + ); + const cleanup = + order === "cleanup-first" + ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) + : undefined; + const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); + if (order === "cleanup-first") expect(harness.open).not.toHaveBeenCalled(); + if (order === "startup-first") yield* Deferred.await(openEntered); + const laterCleanup = + order === "startup-first" + ? yield* cleanupEffect.pipe(Effect.forkChild({ startImmediately: true })) + : undefined; + if (order === "startup-first") expect(cleanupEntered).toBe(false); + yield* Deferred.succeed(release, undefined); + if (cleanup !== undefined) yield* Fiber.join(cleanup); + yield* Fiber.join(startup); + if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup); + if (order === "cleanup-first") { + expect(harness.createWorktree).toHaveBeenCalledWith({ + cwd: "/tmp/native-account-project", + refName: "feature/restore", + path: worktreePath, + }); + } + expect(harness.resolveRuntimePolicy).toHaveBeenCalledWith( + expect.objectContaining({ + thread: expect.objectContaining({ worktreePath }), + }), + ); + expect(harness.open).toHaveBeenCalledWith( + expect.objectContaining({ + runtimePolicy: expect.objectContaining({ cwd: worktreePath }), + }), + ); + expect(harness.startRootRun).toHaveBeenCalledWith( + expect.objectContaining({ + appThread: expect.objectContaining({ worktreePath }), + runtimePolicy: expect.objectContaining({ cwd: worktreePath }), + }), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +effectIt.effect("reads only thread state before taking the startup lease", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ text: "/logout", previousNativeSession: true }); + yield* harness.start; + expect(harness.getThreadRecords).toHaveBeenCalledExactlyOnceWith( + harness.projection().thread.id, + [], + ); + expect(harness.getTurnStartContext).toHaveBeenCalledOnce(); + expect(harness.projection().runs.at(-1)?.status).toBe("completed"); + }), +); + +effectIt.effect("reads current startup state after waiting for the workspace lease", () => + Effect.gen(function* () { + const worktreePath = "/tmp/provider-start-fresh-state"; + const release = yield* Deferred.make(); + const readEntered = yield* Deferred.make(); + const harness = makeLocalCommandHarness({ + text: "Continue", + worktreePath, + failReadsAfterRunning: true, + }); + harness.getThreadRecords.mockImplementationOnce(() => + Deferred.succeed(readEntered, undefined).pipe(Effect.as(harness.projection())), + ); + const holder = yield* withWorkspaceLease(worktreePath, Deferred.await(release)).pipe( + Effect.forkChild({ startImmediately: true }), + ); + const startup = yield* harness.start.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(readEntered); + expect(harness.getTurnStartContext).not.toHaveBeenCalled(); + const projection = harness.projection(); + harness.setProjection({ + ...projection, + runs: projection.runs.map((run) => ({ ...run, status: "running" })), + }); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(holder); + yield* Fiber.join(startup); + expect(harness.open).not.toHaveBeenCalled(); + expect(harness.startRootRun).not.toHaveBeenCalled(); + }), +); + +effectIt.effect("starts another provider in the same checkout while a turn is pending", () => + Effect.gen(function* () { + const worktreePath = "/tmp/provider-start-shared-checkout"; + const turnEntered = yield* Deferred.make(); + const releaseTurn = yield* Deferred.make(); + const first = makeLocalCommandHarness({ + text: "Continue", + worktreePath, + failReadsAfterRunning: true, + }); + const second = makeLocalCommandHarness({ + text: "Continue", + worktreePath, + failReadsAfterRunning: true, + }); + first.startRootRun.mockImplementation(() => + Deferred.succeed(turnEntered, undefined).pipe(Effect.andThen(Deferred.await(releaseTurn))), + ); + const pending = yield* first.start.pipe(Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(turnEntered); + yield* second.start; + expect(second.startRootRun).toHaveBeenCalledOnce(); + expect(second.projection().runs.at(-1)?.status).toBe("running"); + yield* Deferred.succeed(releaseTurn, undefined); + yield* Fiber.join(pending); + }), +); + effectIt.effect("terminalizes a starting run when its provider session cannot open", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index bb77c639f722..3873fc548d8e 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -19,9 +19,11 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; +import { withWorkspaceLease } from "../workspace/workspaceLease.ts"; import * as GitWorkflowService from "../git/GitWorkflowService.ts"; import * as ProjectService from "../project/ProjectService.ts"; import * as ProviderAuthService from "../provider/ProviderAuthService.ts"; @@ -94,6 +96,7 @@ export const layer: Layer.Layer< | ContextHandoffService.ContextHandoffServiceV2 | IdAllocator.IdAllocatorV2 | FileSystem.FileSystem + | Path.Path | GitWorkflowService.GitWorkflowService | ProjectService.ProjectService | ProviderAuthService.ProviderAuthService @@ -108,6 +111,7 @@ export const layer: Layer.Layer< const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2; const idAllocator = yield* IdAllocator.IdAllocatorV2; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const gitWorkflow = yield* GitWorkflowService.GitWorkflowService; const projects = yield* ProjectService.ProjectService; const providerAuth = yield* ProviderAuthService.ProviderAuthService; @@ -1284,7 +1288,7 @@ export const layer: Layer.Layer< !noteContinuation ? session : makeDeliverySession(session, startWithHandoffs); - yield* runExecution.startRootRun({ + return runExecution.startRootRun({ commandId: CommandId.make(`command:effect:provider-turn.start:${run.id}`), appThread: projection.thread, providerSessionId, @@ -1333,7 +1337,15 @@ export const layer: Layer.Layer< return ProviderTurnStartServiceV2.of({ start: (input) => - start(input).pipe( + Effect.gen(function* () { + // Storage cleanup removes worktrees under the same lease. Only startup + // holds it; the provider turn runs after it is released. + const { thread } = yield* projectionStore.getThreadRecords(input.threadId, []); + const providerTurn = yield* thread.worktreePath === null + ? start(input) + : withWorkspaceLease(path.resolve(thread.worktreePath), start(input)); + if (providerTurn !== undefined) yield* providerTurn; + }).pipe( Effect.mapError((cause) => isProviderTurnStartError(cause) ? cause diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 730b72feea6b..f99328d1fc66 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -405,8 +405,9 @@ it.effect.each( ), ); -// Claude and Pi steer live but cannot interrupt-and-restart, so a changed -// selection waits for the next turn as the thread's saved selection. +// A changed selection the provider applies on its next turn waits there as the +// thread's saved selection. That holds for a provider that can restart the +// turn (Codex) too: restarting it would end the turn's native subagents. const runSelection = { instanceId, model: "test-model", @@ -417,7 +418,10 @@ const composerSelection = { options: [...runSelection.options, { id: "fastMode", value: false }], }; -const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* (name: string) { +const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* ( + name: string, + canRestart = false, +) { const cwd = yield* checkpointWorkspace(name); const events = yield* Queue.unbounded(); const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = []; @@ -427,7 +431,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* turns: { ...CodexProviderCapabilitiesV2.turns, supportsActiveSteering: true, - supportsSteeringByInterruptRestart: false, + supportsSteeringByInterruptRestart: canRestart, }, }; const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = { @@ -560,79 +564,82 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* return { events, started, steered, layer, startFirstTurn }; }); -it.effect("steers a changed turn-scoped selection into a provider that cannot restart", () => - Effect.scoped( - Effect.gen(function* () { - const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "steering-selection-change", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const steer = (id: string, selection: ModelSelection) => - orchestrator - .dispatch({ - type: "message.dispatch", - commandId: CommandId.make(id), - threadId, - messageId: MessageId.make(`message:${id}`), - text: id, - attachments: [], - modelSelection: selection, - dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, - createdBy: "user", - creationSource: "web", - }) - .pipe(Effect.andThen(worker.drain())); +it.effect.each([{ canRestart: false }, { canRestart: true }])( + "steers a changed turn-scoped selection into the running turn (canRestart=$canRestart)", + ({ canRestart }) => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + `steering-selection-change-${canRestart}`, + canRestart, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const steer = (id: string, selection: ModelSelection) => + orchestrator + .dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId, + messageId: MessageId.make(`message:${id}`), + text: id, + attachments: [], + modelSelection: selection, + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "user", + creationSource: "web", + }) + .pipe(Effect.andThen(worker.drain())); - yield* steer("steer-changed", composerSelection); - const changed = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, ["steer-changed"]); - assert.equal(started.length, 1); - assert.lengthOf(changed.attempts, 1); - assert.equal(changed.runs[0]?.status, "running"); - assert.deepEqual(changed.runs[0]?.modelSelection, runSelection); - assert.deepEqual(changed.thread.modelSelection, composerSelection); + yield* steer("steer-changed", composerSelection); + const changed = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["steer-changed"]); + assert.equal(started.length, 1); + assert.lengthOf(changed.attempts, 1); + assert.equal(changed.runs[0]?.status, "running"); + assert.deepEqual(changed.runs[0]?.modelSelection, runSelection); + assert.deepEqual(changed.thread.modelSelection, composerSelection); - // Choosing the running run's selection again replaces the saved choice. - yield* steer("steer-reverted", runSelection); - const reverted = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, ["steer-changed", "steer-reverted"]); - assert.lengthOf(reverted.attempts, 1); - assert.deepEqual(reverted.thread.modelSelection, runSelection); + // Choosing the running run's selection again replaces the saved choice. + yield* steer("steer-reverted", runSelection); + const reverted = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["steer-changed", "steer-reverted"]); + assert.lengthOf(reverted.attempts, 1); + assert.deepEqual(reverted.thread.modelSelection, runSelection); - // The saved choice moves to another instance while the run keeps going. - // Steering with the run's selection brings the thread's instance back too. - const otherSelection = { - instanceId: ProviderInstanceId.make("codex-work"), - model: "other", - }; - const sink = yield* EventSink.EventSinkV2; - yield* sink.write({ - events: [ - { - id: EventId.make("switched-away"), - type: "thread.provider-switched", - threadId, - providerInstanceId: otherSelection.instanceId, - occurredAt: yield* DateTime.now, - payload: { - ...reverted.thread, + // The saved choice moves to another instance while the run keeps going. + // Steering with the run's selection brings the thread's instance back too. + const otherSelection = { + instanceId: ProviderInstanceId.make("codex-work"), + model: "other", + }; + const sink = yield* EventSink.EventSinkV2; + yield* sink.write({ + events: [ + { + id: EventId.make("switched-away"), + type: "thread.provider-switched", + threadId, providerInstanceId: otherSelection.instanceId, - modelSelection: otherSelection, + occurredAt: yield* DateTime.now, + payload: { + ...reverted.thread, + providerInstanceId: otherSelection.instanceId, + modelSelection: otherSelection, + }, }, - }, - ], - }); - yield* steer("steer-back", runSelection); - const back = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]); - assert.equal(back.thread.providerInstanceId, instanceId); - assert.deepEqual(back.thread.modelSelection, runSelection); - }).pipe(Effect.provide(layer)); - }), - ), + ], + }); + yield* steer("steer-back", runSelection); + const back = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["steer-changed", "steer-reverted", "steer-back"]); + assert.equal(back.thread.providerInstanceId, instanceId); + assert.deepEqual(back.thread.modelSelection, runSelection); + }).pipe(Effect.provide(layer)); + }), + ), ); it.effect("starts a steer that missed the turn on the saved next-turn selection", () => diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 3a95634cde5b..8f5f8fbcb5c5 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -23,9 +23,11 @@ import { type OrchestrationV2Run, type OrchestrationV2ThreadShellSnapshot, type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadTranscript, type OrchestrationV2ThreadShell, type OrchestrationV2TurnItem, ProjectId, + PROVIDER_SEND_TURN_MAX_FILE_BYTES, ProviderInstanceId, resolveProjectProviderInstanceEnabled, RunId, @@ -33,6 +35,7 @@ import { ThreadId, type TurnItemId, } from "@t3tools/contracts"; +import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; @@ -46,6 +49,8 @@ import * as Stream from "effect/Stream"; import { makeLocalRunRefusal } from "./cloudOnlyHost.ts"; import * as CommandReceiptStore from "./CommandReceiptStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { projectedRowEncodedBytes } from "./threadHistoryPaging.ts"; import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts"; import { DispatchModeLimit, exceededDispatchModeLimit } from "./DispatchModeLimit.ts"; @@ -187,6 +192,15 @@ export class ThreadManagementThreadNotFoundError extends Schema.TaggedError()( + "ThreadTranscriptTooLargeError", + { threadId: ThreadId }, +) { + override get message(): string { + return "The thread transcript exceeds the file attachment limit."; + } +} + export class ThreadManagementRunNotFoundError extends Schema.TaggedError()( "ThreadManagementRunNotFoundError", { @@ -337,6 +351,13 @@ export interface ThreadManagementServiceShape { ) => Effect.Effect; readonly getCheckpointContext: Orchestrator.OrchestratorV2["Service"]["getCheckpointContext"]; readonly getThreadSnapshot: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshot"]; + readonly getThreadTranscript: ( + threadId: ThreadId, + ) => Effect.Effect< + OrchestrationV2ThreadTranscript, + Orchestrator.OrchestratorV2Error | ThreadTranscriptTooLargeError, + ServerEnvironment.ServerEnvironmentIdentity + >; readonly getThreadSnapshotWindow: Orchestrator.OrchestratorV2["Service"]["getThreadSnapshotWindow"]; readonly getProjectThreadRecords: ( input: { readonly projectId: ProjectId; readonly threadId: ThreadId }, @@ -629,6 +650,32 @@ const make = Effect.gen(function* () { ensureProjectionTranscript(threadId).pipe( Effect.andThen(orchestrator.getThreadSnapshot(threadId)), ); + const getThreadTranscript = Effect.fn("orchestrationV2.threadManagement.getThreadTranscript")( + function* (threadId: ThreadId) { + const { projection } = yield* getThreadSnapshot(threadId); + const environment = yield* ServerEnvironment.ServerEnvironmentIdentity; + const transcript = { + threadId: projection.thread.id, + title: projection.thread.title, + updatedAt: projection.updatedAt, + items: projection.visibleTurnItems, + }; + let sizeBytes = Buffer.byteLength( + threadTranscriptHeader(yield* environment.getEnvironmentId, transcript), + "utf8", + ); + if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) { + return yield* new ThreadTranscriptTooLargeError({ threadId }); + } + for (const row of transcript.items) { + sizeBytes += projectedRowEncodedBytes(row) + 1; + if (sizeBytes > PROVIDER_SEND_TURN_MAX_FILE_BYTES) { + return yield* new ThreadTranscriptTooLargeError({ threadId }); + } + } + return transcript; + }, + ); const getThreadSnapshotWindow: ThreadManagementServiceShape["getThreadSnapshotWindow"] = ( threadId, options, @@ -1164,6 +1211,7 @@ const make = Effect.gen(function* () { getThreadProjection, getCheckpointContext, getThreadSnapshot, + getThreadTranscript, getThreadSnapshotWindow, getProjectThreadRecords, getProjectThread, diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index ccf74f7d193e..7016a17dcd89 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -251,6 +251,38 @@ describe("threadHasQueuedTurnStart", () => { }); describe("resolveAutoSettlementAt", () => { + it("keeps threads with a PR from inactivity settlement only when asked", () => { + const input = { + thread: shell({ + latestUserMessageAt: at(-4 * DAY_MS), + linkedPullRequest: { + projectId: ProjectId.make("project-1"), + repository: "owner/repo", + number: 1, + url: "https://example.test/owner/repo/pull/1", + }, + }), + pullRequest: null, + nowMs: NOW_MS, + autoSettleAfterDays: 3, + autoSettleOnMerge: true, + autoSettleKeepPullRequests: true, + }; + expect(ThreadSettlementService.resolveAutoSettlementAt(input)).toBeNull(); + expect( + ThreadSettlementService.resolveAutoSettlementAt({ + ...input, + autoSettleKeepPullRequests: false, + }), + ).toEqual(at(-4 * DAY_MS)); + expect( + ThreadSettlementService.resolveAutoSettlementAt({ + ...input, + pullRequest: { state: "merged", mergedAt: DateTime.formatIso(at(-1)) }, + }), + ).toEqual(at(-4 * DAY_MS)); + }); + it("uses the latest activity time when the inactivity window elapses", () => { const idle = shell({ latestUserMessageAt: at(-4 * DAY_MS), diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index bd7a7fd58dcb..4a3540ef0291 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -202,6 +202,7 @@ export function resolveAutoSettlementAt(input: { readonly nowMs: number; readonly autoSettleAfterDays: number | null; readonly autoSettleOnMerge: boolean; + readonly autoSettleKeepPullRequests?: boolean; }): DateTime.Utc | null { const { thread } = input; let pullRequest = input.pullRequest; @@ -236,6 +237,9 @@ export function resolveAutoSettlementAt(input: { if (pullRequest !== null && pullRequestSettles(thread, pullRequest, input.autoSettleOnMerge)) { return activityAtMs === null ? thread.createdAt : DateTime.makeUnsafe(activityAtMs); } + const hasPullRequest = + pullRequest !== null || thread.linkedPullRequest != null || thread.branchPullRequest != null; + if (input.autoSettleKeepPullRequests === true && hasPullRequest) return null; if (input.autoSettleAfterDays === null || activityAtMs === null) return null; // A passed wake timer restarts inactivity. An earlier wake can only delay settlement. const snoozedUntilMs = toMillis(thread.snoozedUntil); @@ -275,6 +279,7 @@ export function autoSettlementSettingsKey( return JSON.stringify([ settings.sidebarAutoSettleOnMerge, settings.sidebarAutoSettleAfterDays, + settings.sidebarAutoSettleKeepPullRequests, // Only entries that touch settlement, in a stable order, so a project // override on an unrelated key does not queue a sweep. JSON drops // undefined, so inherit (absent) and never (null) need distinct marks. @@ -282,7 +287,8 @@ export function autoSettlementSettingsKey( .filter( ([, entry]) => entry.sidebarAutoSettleOnMerge !== undefined || - entry.sidebarAutoSettleAfterDays !== undefined, + entry.sidebarAutoSettleAfterDays !== undefined || + entry.sidebarAutoSettleKeepPullRequests !== undefined, ) .sort(([left], [right]) => left.localeCompare(right)) .map(([projectId, entry]) => [ @@ -291,6 +297,7 @@ export function autoSettlementSettingsKey( entry.sidebarAutoSettleAfterDays === undefined ? "inherit" : entry.sidebarAutoSettleAfterDays, + entry.sidebarAutoSettleKeepPullRequests ?? "inherit", ]), ]); } @@ -343,6 +350,7 @@ export const make = Effect.gen(function* () { nowMs: DateTime.toEpochMillis(decisionNow), autoSettleAfterDays: currentSettings.sidebarAutoSettleAfterDays, autoSettleOnMerge: currentSettings.sidebarAutoSettleOnMerge, + autoSettleKeepPullRequests: currentSettings.sidebarAutoSettleKeepPullRequests, }); if (settledAt === null) return thread; const uuid = yield* crypto.randomUUIDv4(); @@ -445,6 +453,7 @@ export const make = Effect.gen(function* () { nowMs: DateTime.toEpochMillis(decisionNow), autoSettleAfterDays: settings.sidebarAutoSettleAfterDays, autoSettleOnMerge: settings.sidebarAutoSettleOnMerge, + autoSettleKeepPullRequests: settings.sidebarAutoSettleKeepPullRequests, }) !== null ); }); diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index 2357c1490901..1e141cea588e 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -9,6 +9,7 @@ import { ProviderInstanceId, ProviderSessionId, ProviderTurnId, + RuntimeRequestId, ThreadId, TurnItemId, } from "@t3tools/contracts"; @@ -539,6 +540,78 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)( }).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))), ); +it.effect.each([ + { ending: "cancelled", question: "resolved" }, + { ending: "interrupted", question: "resolved" }, + { ending: "completed", question: "pending" }, + { ending: "failed", question: "pending" }, +] as const)( + "a $ending delegated task leaves its async question $question", + ({ ending, question }) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const parentThreadId = ThreadId.make(`thread:stop-question-parent:${ending}`); + yield* createWatchingThread(parentThreadId, 20); + yield* send(parentThreadId, "first", "start_immediately"); + const childThreadId = yield* delegate(parentThreadId, `question task ${ending}`); + const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!; + assert.equal( + (yield* orchestrator.getThreadProjection(childThreadId)).nodes.find( + (node) => node.id === childRun.rootNodeId, + )?.runId, + childRun.id, + ); + const now = yield* DateTime.now; + yield* projections.apply({ + id: EventId.make("event:stop-question:request"), + type: "runtime-request.updated", + threadId: childThreadId, + runId: childRun.id, + occurredAt: now, + payload: { + id: RuntimeRequestId.make("request:stop-question"), + nodeId: childRun.rootNodeId!, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { type: "message" }, + createdAt: now, + resolvedAt: null, + }, + }); + const request = Effect.map( + orchestrator.getThreadProjection(childThreadId), + (projection) => projection.runtimeRequests[0], + ); + + // While the task runs, its question stays open. + yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id); + assert.equal((yield* request)?.status, "pending"); + if (ending === "interrupted") { + // What task_cancel dispatches. + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-question-child"), + threadId: childThreadId, + }); + } else { + yield* projections.apply({ + id: EventId.make(`event:stop-question:${ending}`), + type: "run.updated", + threadId: childThreadId, + runId: childRun.id, + occurredAt: now, + payload: { ...childRun, status: ending, startedAt: now, completedAt: now }, + }); + } + yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id); + assert.equal((yield* request)?.status, question); + assert.equal((yield* request)?.decision, question === "resolved" ? "cancel" : undefined); + }).pipe(Effect.provide(layerTest)), +); + it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts b/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts index a86b19be95f7..46c99b95f3aa 100644 --- a/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts +++ b/apps/server/src/orchestration-v2/boundedSnapshotTransport.test.ts @@ -5,6 +5,7 @@ import { EnvironmentAuthenticatedAuth, EnvironmentAuthenticatedPrincipal, EnvironmentHttpApi, + EnvironmentId, EventId, MessageId, NodeId, @@ -34,6 +35,7 @@ import * as HttpApi from "effect/http-api/HttpApi"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import { Etag, HttpRouter } from "effect/http"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; @@ -226,6 +228,9 @@ const seed = Effect.gen(function* () { // thread routes never touch projects. const TestLayer = Layer.mergeAll( management, + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(EnvironmentId.make("compact-transport")), + }), Layer.effectDiscard(seed), Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({}), Layer.mock(ProjectStore.ProjectStoreV2)({}), diff --git a/apps/server/src/orchestration-v2/http.test.ts b/apps/server/src/orchestration-v2/http.test.ts new file mode 100644 index 000000000000..74476d658ed0 --- /dev/null +++ b/apps/server/src/orchestration-v2/http.test.ts @@ -0,0 +1,244 @@ +import { + AuthSessionId, + type AuthEnvironmentScope, + EnvironmentAuthenticatedAuth, + EnvironmentAuthenticatedPrincipal, + EnvironmentHttpApi, + EnvironmentId, + EventId, + ORCHESTRATION_PROTOCOL_HEADER, + ORCHESTRATION_PROTOCOL_VERSION_TEXT, + OrchestrationV2AppThread, + OrchestrationV2TurnItem, + OrchestrationV2ThreadTranscript, + PROVIDER_SEND_TURN_MAX_FILE_BYTES, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import { threadTranscriptHeader } from "@t3tools/shared/threadTranscript"; +import * as Effect from "effect/Effect"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as HttpRouter from "effect/http/HttpRouter"; +import * as HttpPlatform from "effect/http/HttpPlatform"; +import * as Etag from "effect/http/Etag"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as HttpApi from "effect/http-api/HttpApi"; +import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; + +import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; +import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts"; +import * as OrchestrationHttp from "./http.ts"; +import { EventSinkV2 } from "./EventSink.ts"; +import * as ProjectStore from "./ProjectStore.ts"; +import * as CommandReceiptStore from "./CommandReceiptStore.ts"; +import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; + +class TranscriptTestApi extends HttpApi.make("environment").add( + EnvironmentHttpApi.groups.orchestration, +) {} +const decodeTranscript = Schema.decodeUnknownEffect( + Schema.toCodecJson(OrchestrationV2ThreadTranscript), +); + +const now = DateTime.makeUnsafe("2026-09-29T00:00:00.000Z"); +const environmentId = EnvironmentId.make("source-بيئة"); +const output = "Full tool output. ".repeat(4_000); +const thread = Schema.decodeUnknownSync(OrchestrationV2AppThread)({ + id: "source-thread", + projectId: "source-project", + title: "Source 界\nconversation", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { rootThreadId: "source-thread", parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, +}); +const items = Schema.decodeUnknownSync(Schema.Array(OrchestrationV2TurnItem))( + Array.from({ length: 200 }, (_, position) => ({ + id: `item-${position}`, + threadId: "source-thread", + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: position, + type: "command_execution", + status: "completed", + title: "Read notes", + input: "cat notes.md", + output: position === 0 ? output : "Done", + startedAt: now, + completedAt: now, + updatedAt: now, + })), +); + +it.effect("exports full history with size, scope, and missing-thread checks", () => + Effect.gen(function* () { + let allowed = true; + const runtime = ProviderReplayHarness.layerWithRegistry( + { name: "thread-transcript" }, + ProviderAdapterRegistry.layerFromAdapters([]), + { runEffectWorker: false }, + ); + const services = yield* Layer.build( + Layer.mergeAll( + runtime, + ThreadManagementService.layer.pipe( + Layer.provide( + Layer.mergeAll(runtime, CommandReceiptStore.layer, ServerSettings.layerTest({})), + ), + ), + OrchestrationEventStore.layer, + ProjectStore.layer, + ).pipe(Layer.provideMerge(SqlitePersistence.layerMemory)), + ); + const eventSink = Context.get(services, EventSinkV2); + yield* eventSink.write({ + events: [ + { + id: EventId.make("create-source"), + type: "thread.created", + threadId: thread.id, + occurredAt: now, + payload: thread, + }, + ], + }); + const routes = HttpApiBuilder.layer(TranscriptTestApi).pipe( + Layer.provide(OrchestrationHttp.layer), + Layer.provide( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(environmentId), + }), + ), + Layer.provide( + Layer.succeed(EnvironmentAuthenticatedAuth, (effect) => + Effect.suspend(() => + effect.pipe( + Effect.provideService(EnvironmentAuthenticatedPrincipal, { + sessionId: AuthSessionId.make("test-session"), + subject: "test", + method: "bearer-access-token", + scopes: new Set(allowed ? ["orchestration:read"] : []), + }), + ), + ), + ), + ), + Layer.provide(Layer.succeedContext(services)), + Layer.provide(Layer.mock(ProjectEnrichmentService)({})), + Layer.provide(HttpPlatform.layer), + Layer.provide(Etag.layerWeak), + Layer.provide(NodeServices.layer), + ); + const { handler, dispose } = HttpRouter.toWebHandler(routes, { disableLogger: true }); + yield* Effect.addFinalizer(() => Effect.promise(dispose)); + const read = (threadId: ThreadId) => + Effect.promise(() => + handler( + new Request(`http://localhost/api/orchestration/threads/${threadId}/transcript`, { + headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT }, + }), + ), + ); + + const emptyResponse = yield* read(thread.id); + expect(emptyResponse.status).toBe(200); + expect( + (yield* decodeTranscript(yield* Effect.promise(() => emptyResponse.json()))).items, + ).toEqual([]); + yield* eventSink.write({ + events: items.map((item) => ({ + id: EventId.make(`create-${item.id}`), + type: "turn-item.updated" as const, + threadId: thread.id, + occurredAt: now, + payload: item, + })), + }); + + const response = yield* read(thread.id); + expect(response.status).toBe(200); + const transcript = yield* decodeTranscript(yield* Effect.promise(() => response.json())); + expect(transcript.items).toHaveLength(200); + expect(transcript.items[0]?.item).toMatchObject({ output }); + expect(transcript.items[0]?.visibility).toBe("local"); + expect(transcript.items[199]?.position).toBe(199); + + const emptyOutputRows = transcript.items.map((row, position) => + position === 0 ? { ...row, item: { ...row.item, output: "" } } : row, + ); + const header = threadTranscriptHeader(environmentId, transcript); + const baseSize = + Buffer.byteLength(header, "utf8") + + emptyOutputRows.reduce( + (size, row) => size + Buffer.byteLength(`${JSON.stringify(row)}\n`, "utf8"), + 0, + ); + const boundaryOutput = "界" + "x".repeat(PROVIDER_SEND_TURN_MAX_FILE_BYTES - baseSize - 3); + for (const [suffix, expectedStatus] of [ + ["", 200], + ["x", 400], + ] as const) { + yield* eventSink.write({ + events: [ + { + id: EventId.make(`boundary-${expectedStatus}`), + type: "turn-item.updated", + threadId: thread.id, + occurredAt: now, + payload: { + ...items.find((item) => item.type === "command_execution")!, + output: boundaryOutput + suffix, + }, + }, + ], + }); + const response = yield* read(thread.id); + expect(response.status).toBe(expectedStatus); + if (expectedStatus === 400) { + const error = yield* Context.get(services, ThreadManagementService.ThreadManagementService) + .getThreadTranscript(thread.id) + .pipe( + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(environmentId), + }), + Effect.flip, + ); + expect(error).toBeInstanceOf(ThreadManagementService.ThreadTranscriptTooLargeError); + expect(yield* Effect.promise(() => response.json())).toMatchObject({ + _tag: "EnvironmentRequestInvalidError", + reason: "thread_transcript_too_large", + }); + } + } + + expect((yield* read(ThreadId.make("missing"))).status).toBe(404); + allowed = false; + expect((yield* read(thread.id)).status).toBe(403); + }), +); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 8f67002333ba..cccec8e919c1 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -5,6 +5,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Predicate from "effect/Predicate"; +import * as Schema from "effect/Schema"; import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; import * as SqlClient from "effect/sql/SqlClient"; @@ -15,6 +16,7 @@ import { failEnvironmentNotFound, requireEnvironmentScope, } from "../auth/http.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import { traceLocalHandlerWork } from "../cloud/traceRelayRequest.ts"; import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; @@ -32,6 +34,10 @@ import { buildActiveShellSnapshot, loadShellSnapshotParts } from "./ShellStream. import { boundedSnapshotResponseFields } from "./ThreadStream.ts"; import { projectThreadProjectionForWire } from "./WireProjection.ts"; +const isThreadTranscriptTooLargeError = Schema.is( + ThreadManagementService.ThreadTranscriptTooLargeError, +); + function isThreadNotFound(error: unknown): boolean { return ( Predicate.hasProperty(error, "cause") && @@ -51,6 +57,7 @@ export const layer = HttpApiBuilder.group( "orchestration", Effect.fnUntraced(function* (handlers) { const sql = yield* SqlClient.SqlClient; + const environment = yield* ServerEnvironment.ServerEnvironmentIdentity; const threadManagement = yield* ThreadManagementService.ThreadManagementService; const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; const projectStore = yield* ProjectStore.ProjectStoreV2; @@ -177,6 +184,31 @@ export const layer = HttpApiBuilder.group( }; }), ) + .handle( + "threadTranscript", + Effect.fn("environment.orchestration.threadTranscript")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationReadScope); + return yield* threadManagement.getThreadTranscript(args.params.threadId).pipe( + Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, environment), + traceLocalHandlerWork, + Effect.catch( + Effect.fnUntraced(function* (error) { + if (isThreadTranscriptTooLargeError(error)) { + return yield* failEnvironmentInvalidRequest("thread_transcript_too_large"); + } + if (isThreadNotFound(error)) { + return yield* failEnvironmentNotFound("thread_not_found"); + } + return yield* failEnvironmentInternal( + "orchestration_thread_snapshot_failed", + error, + ); + }), + ), + ); + }), + ) .handle( "threadBoundedSnapshot", Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) { diff --git a/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs b/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs index 5824c507a418..0828e92b837a 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs +++ b/apps/server/src/orchestration-v2/testkit/ProviderTurnStartMemory.fixture.mjs @@ -7,10 +7,11 @@ const mode = process.argv[3]; const withHandoff = mode.startsWith("handoff"); const require = NodeModule.createRequire(root + "/apps/server/package.json"); const load = (name) => import(NodeURL.pathToFileURL(require.resolve("effect/" + name))); -const [Effect, Layer, FileSystem] = await Promise.all([ +const [Effect, Layer, FileSystem, Path] = await Promise.all([ load("Effect"), load("Layer"), load("FileSystem"), + load("Path"), ]); const app = (file) => import(NodeURL.pathToFileURL(root + "/apps/server/src/" + file + ".ts")); const providerCore = (file) => @@ -31,6 +32,7 @@ const [Start, Projection, Run, Sessions, Policy, Id, Sink, Handoff, Git, Project ]); let current; let fullReads = 0; +let threadReads = 0; const liveRuns = []; const refs = []; const checkpoints = []; @@ -52,6 +54,7 @@ const dependencies = Layer.mergeAll( Layer.mock(Handoff.ContextHandoffServiceV2)({}), Id.layer, FileSystem.layerNoop({}), + Path.layer, Layer.mock(Git.GitWorkflowService)({}), Layer.mock(Project.ProjectService)({}), Layer.mock(Auth.ProviderAuthService)({}), @@ -62,6 +65,13 @@ const dependencies = Layer.mergeAll( throw new Error("full transcript read"); }), hasUnpairedRunInterruptRequest: () => Effect.succeed(false), + getThreadRecords: (threadId, fields) => + Effect.sync(() => { + NodeAssert.equal(threadId, current.thread.id); + NodeAssert.deepEqual(fields, []); + threadReads++; + return { thread: current.thread }; + }), getTurnStartContext: () => Effect.sync(() => { fullReads++; @@ -191,8 +201,10 @@ await Effect.runPromise( NodeAssert.equal(yield* controls.shouldFinalizeRun(), false); NodeAssert.deepEqual(yield* controls.loadInheritedBackgroundTurnItems(), []); NodeAssert.equal(fullReads, i + 1); + NodeAssert.equal(threadReads, i + 1); NodeAssert.equal(yield* controls.hasUnpairedRunInterruptRequest(), false); NodeAssert.equal(fullReads, i + 1); + NodeAssert.equal(threadReads, i + 1); current = null; if (i === Math.floor(count / 2) - 1 || i === count - 1) { yield* Effect.promise(async () => { diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson index 66eafcdb7006..78f74648311d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/multi_turn/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.3"},"userAgent":"muse-build/1.4.3 (non-interactive; macos-aarch64; build 5c1bccecf3f125ff8fdc53f63558f6527ee70e56)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:4cb671082574037fc1070a136db7c0c8dc24e65e78cf3d209a10944ff9f9845f"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","commandId":"01a11a6b-707e-7001-b2f4-23db74e60097"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","permissionProfile":":unrestricted","commandId":"01a11a6b-707e-7001-b2f4-23db74e60097"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6b-707e-7000-9bb5-4079c7772ad0/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:30:11.238412Z","updatedAt":"2026-10-08T07:30:11.238416Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444611408}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6b-707e-7000-9bb5-4079c7772ad0/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:30:11.238412Z","updatedAt":"2026-10-08T07:30:11.238416Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6b-707e-7000-9bb5-4079c7772ad0","viewCursor":"v:01a11a6b-707e-7000-9bb5-4079c7772ad0:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6b-707e-7000-9bb5-4079c7772ad0"},"first":{"id":"37b19bd1-b212-4532-a0c9-a6677f303e26","sequence":5},"last":{"id":"37b19bd1-b212-4532-a0c9-a6677f303e26","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a11a6b-707e-7001-b2f4-23db74e60097","clientName":"t3_code"},"emittedAtMs":1791444611412}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson index a9d154ca13f3..33bc408411cd 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_permission/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.3"},"userAgent":"muse-build/1.4.3 (non-interactive; macos-aarch64; build 5c1bccecf3f125ff8fdc53f63558f6527ee70e56)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:4cb671082574037fc1070a136db7c0c8dc24e65e78cf3d209a10944ff9f9845f"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"promptUnmatched","commandId":"01a11a6d-39bb-7001-923e-425cc6129ce7"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"promptUnmatched","permissionProfile":":ask-me","commandId":"01a11a6d-39bb-7001-923e-425cc6129ce7"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-39bb-7000-8c93-4594c98e6a11/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:08.30084Z","updatedAt":"2026-10-08T07:32:08.300844Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444728496}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-39bb-7000-8c93-4594c98e6a11/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:08.30084Z","updatedAt":"2026-10-08T07:32:08.300844Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6d-39bb-7000-8c93-4594c98e6a11","viewCursor":"v:01a11a6d-39bb-7000-8c93-4594c98e6a11:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-39bb-7000-8c93-4594c98e6a11"},"first":{"id":"b05fb8ec-7b58-4cf7-a369-379938395230","sequence":5},"last":{"id":"b05fb8ec-7b58-4cf7-a369-379938395230","sequence":5}},"mode":"promptUnmatched","source":"approvalReconfigure","commandId":"01a11a6d-39bb-7001-923e-425cc6129ce7","clientName":"t3_code"},"emittedAtMs":1791444728501}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson index 6fb50f0d7627..21b68a4ba72e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_approval/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.4"},"userAgent":"muse-build/1.4.4 (serve; macos-aarch64; build 1e1635eda6610b6dec0803bc76c1ceb0dbff7caa)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:7c94f153c41659cb3f1bd3c3e04438be254644cb2a97d65d48edc7449b74858a"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"promptUnmatched","commandId":"01a12d1d-a1b8-7000-8d6c-f1324b724cdb"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"promptUnmatched","permissionProfile":":ask-me","commandId":"01a12d1d-a1b8-7000-8d6c-f1324b724cdb"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","path":"~/.local/share/muse/sessions/2026/10/11/01a12d1d-a1b7-7000-9697-d430c2e2afd8/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:37:59.14136Z","updatedAt":"2026-10-11T22:37:59.141364Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791758279294}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","path":"~/.local/share/muse/sessions/2026/10/11/01a12d1d-a1b7-7000-9697-d430c2e2afd8/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:37:59.14136Z","updatedAt":"2026-10-11T22:37:59.141364Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"promptUnmatched","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d1d-a1b7-7000-9697-d430c2e2afd8","viewCursor":"v:01a12d1d-a1b7-7000-9697-d430c2e2afd8:1","sourceRange":{"stream":{"kind":"session","id":"01a12d1d-a1b7-7000-9697-d430c2e2afd8"},"first":{"id":"ed95a9db-eada-4751-a7e6-22ccc9bdabd5","sequence":5},"last":{"id":"ed95a9db-eada-4751-a7e6-22ccc9bdabd5","sequence":5}},"mode":"promptUnmatched","source":"approvalReconfigure","commandId":"01a12d1d-a1b8-7000-8d6c-f1324b724cdb","clientName":"t3_code"},"emittedAtMs":1791758279297}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson index 26f5b056c60a..1d663c7a9a15 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_subagent_interrupt/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.4"},"userAgent":"muse-build/1.4.4 (serve; macos-aarch64; build 1e1635eda6610b6dec0803bc76c1ceb0dbff7caa)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:7c94f153c41659cb3f1bd3c3e04438be254644cb2a97d65d48edc7449b74858a"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","commandId":"01a12d28-7788-7001-a223-c10e52187cdf"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","permissionProfile":":unrestricted","commandId":"01a12d28-7788-7001-a223-c10e52187cdf"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","path":"~/.local/share/muse/sessions/2026/10/11/01a12d28-7788-7000-a946-c407f380868e/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:49:49.235205Z","updatedAt":"2026-10-11T22:49:49.235209Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791758989388}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","path":"~/.local/share/muse/sessions/2026/10/11/01a12d28-7788-7000-a946-c407f380868e/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:49:49.235205Z","updatedAt":"2026-10-11T22:49:49.235209Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d28-7788-7000-a946-c407f380868e","viewCursor":"v:01a12d28-7788-7000-a946-c407f380868e:1","sourceRange":{"stream":{"kind":"session","id":"01a12d28-7788-7000-a946-c407f380868e"},"first":{"id":"29d4e769-78f7-48fa-90cd-3ac9f8fa04bf","sequence":5},"last":{"id":"29d4e769-78f7-48fa-90cd-3ac9f8fa04bf","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a12d28-7788-7001-a223-c10e52187cdf","clientName":"t3_code"},"emittedAtMs":1791758989391}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson index fe407ddffa2a..bf8a2da7960e 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/muse_workflow/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.6"},"userAgent":"muse-build/1.4.6 (serve; macos-aarch64; build db2475a6bd32831a854b97282a12b867123d6520)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:eae467ab60cb9a5d5af4de616830f065e59375c987fd59269c8cc33ed2a1137f"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","commandId":"01a12d5d-4060-7000-b6cd-aaabe26f80de"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","permissionProfile":":unrestricted","commandId":"01a12d5d-4060-7000-b6cd-aaabe26f80de"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","path":"~/.local/share/muse/sessions/2026/10/11/01a12d5d-405f-7000-89a3-5aa62af6ea23/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T23:47:28.587276Z","updatedAt":"2026-10-11T23:47:28.587281Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791762448802}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","path":"~/.local/share/muse/sessions/2026/10/11/01a12d5d-405f-7000-89a3-5aa62af6ea23/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T23:47:28.587276Z","updatedAt":"2026-10-11T23:47:28.587281Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:2"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d5d-405f-7000-89a3-5aa62af6ea23","viewCursor":"v:01a12d5d-405f-7000-89a3-5aa62af6ea23:1","sourceRange":{"stream":{"kind":"session","id":"01a12d5d-405f-7000-89a3-5aa62af6ea23"},"first":{"id":"0c13b14b-877c-4c5b-b05f-8ad250dfd381","sequence":5},"last":{"id":"0c13b14b-877c-4c5b-b05f-8ad250dfd381","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a12d5d-4060-7000-b6cd-aaabe26f80de","clientName":"t3_code"},"emittedAtMs":1791762448807}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson index 9810c4378d46..593a6f98ab53 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/simple/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.3"},"userAgent":"muse-build/1.4.3 (non-interactive; macos-aarch64; build 5c1bccecf3f125ff8fdc53f63558f6527ee70e56)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:4cb671082574037fc1070a136db7c0c8dc24e65e78cf3d209a10944ff9f9845f"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","commandId":"01a11a6a-bbb6-7000-b1a4-a01ea59676ef"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","permissionProfile":":unrestricted","commandId":"01a11a6a-bbb6-7000-b1a4-a01ea59676ef"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6a-bbb5-7000-ad0b-0c9e728406e5/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:29:25.018803Z","updatedAt":"2026-10-08T07:29:25.018807Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444565334}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6a-bbb5-7000-ad0b-0c9e728406e5/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:29:25.018803Z","updatedAt":"2026-10-08T07:29:25.018807Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5","viewCursor":"v:01a11a6a-bbb5-7000-ad0b-0c9e728406e5:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6a-bbb5-7000-ad0b-0c9e728406e5"},"first":{"id":"cfd043e8-8728-493d-ba28-252ef91e8a80","sequence":5},"last":{"id":"cfd043e8-8728-493d-ba28-252ef91e8a80","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a11a6a-bbb6-7000-b1a4-a01ea59676ef","clientName":"t3_code"},"emittedAtMs":1791444565340}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson index b2360ef73a59..3b8ebe4065b0 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.4"},"userAgent":"muse-build/1.4.4 (serve; macos-aarch64; build 1e1635eda6610b6dec0803bc76c1ceb0dbff7caa)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:7c94f153c41659cb3f1bd3c3e04438be254644cb2a97d65d48edc7449b74858a"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","commandId":"01a12d17-75fa-7001-a940-79b5d7c648a4"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","permissionProfile":":unrestricted","commandId":"01a12d17-75fa-7001-a940-79b5d7c648a4"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","path":"~/.local/share/muse/sessions/2026/10/11/01a12d17-75fa-7000-9157-e8365ce94492/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:31:14.73121Z","updatedAt":"2026-10-11T22:31:14.731214Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791757874894}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","path":"~/.local/share/muse/sessions/2026/10/11/01a12d17-75fa-7000-9157-e8365ce94492/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-11T22:31:14.73121Z","updatedAt":"2026-10-11T22:31:14.731214Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"sideFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a12d17-75fa-7000-9157-e8365ce94492","viewCursor":"v:01a12d17-75fa-7000-9157-e8365ce94492:1","sourceRange":{"stream":{"kind":"session","id":"01a12d17-75fa-7000-9157-e8365ce94492"},"first":{"id":"94d1e1ed-1d3e-4cd5-91bf-a51394fc8a0a","sequence":5},"last":{"id":"94d1e1ed-1d3e-4cd5-91bf-a51394fc8a0a","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a12d17-75fa-7001-a940-79b5d7c648a4","clientName":"t3_code"},"emittedAtMs":1791757874898}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson index 04a42c403b09..d155dfaef693 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/turn_interrupt/muse_transcript.ndjson @@ -3,7 +3,7 @@ {"type":"expect_outbound","label":"initialize","frame":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"clientInfo":{"name":"t3_code","title":"T3 Code","version":"1"},"capabilities":{"requestedCapabilities":["sessionMcp"]}}}} {"type":"emit_inbound","label":"response:initialize","frame":{"jsonrpc":"2.0","id":1,"result":{"serverInfo":{"name":"muse","version":"1.4.3"},"userAgent":"muse-build/1.4.3 (non-interactive; macos-aarch64; build 5c1bccecf3f125ff8fdc53f63558f6527ee70e56)","museHome":"~/.local/share/muse","platformFamily":"unix","platformOs":"macos","schema":{"version":1,"fingerprint":"sha256:4cb671082574037fc1070a136db7c0c8dc24e65e78cf3d209a10944ff9f9845f"},"grantedCapabilities":["sessionMcp"],"experimentalApi":false,"sessionDurability":"durable"}}} {"type":"expect_outbound","label":"initialized","frame":{"jsonrpc":"2.0","method":"initialized"}} -{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","commandId":"01a11a6d-2d3e-7000-b0e7-f04c53ee070b"}}} +{"type":"expect_outbound","label":"session/start","frame":{"jsonrpc":"2.0","id":2,"method":"session/start","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","workspaceRoot":"","modelId":"muse-spark-1.3-contributor","providerId":"meta","approvalMode":"allowAll","permissionProfile":":unrestricted","commandId":"01a11a6d-2d3e-7000-b0e7-f04c53ee070b"}}} {"type":"emit_inbound","label":"session/started","frame":{"jsonrpc":"2.0","method":"session/started","params":{"session":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-2d3d-7000-8178-411fdb90bc34/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:05.094285Z","updatedAt":"2026-10-08T07:32:05.094289Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"}},"emittedAtMs":1791444725265}} {"type":"emit_inbound","label":"response:session/start","frame":{"jsonrpc":"2.0","id":2,"result":{"session":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","path":"~/.local/share/muse/sessions/2026/10/08/01a11a6d-2d3d-7000-8178-411fdb90bc34/session.jsonl","status":"idle","activeTurnId":null,"createdAt":"2026-10-08T07:32:05.094285Z","updatedAt":"2026-10-08T07:32:05.094289Z","workspaceRoot":"","providerId":"meta","modelId":"muse-spark-1.3-contributor","turnCount":0,"forkedFrom":null,"approvalMode":{"mode":"allowAll","source":"startup","lastCommandId":null},"createdByClient":{"name":"t3_code","version":"1"},"kind":"root"},"viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:1"}}} {"type":"emit_inbound","label":"session/approvalModeChanged","frame":{"jsonrpc":"2.0","method":"session/approvalModeChanged","params":{"sessionId":"01a11a6d-2d3d-7000-8178-411fdb90bc34","viewCursor":"v:01a11a6d-2d3d-7000-8178-411fdb90bc34:1","sourceRange":{"stream":{"kind":"session","id":"01a11a6d-2d3d-7000-8178-411fdb90bc34"},"first":{"id":"9865268e-0a39-43a0-89d0-251a820ec8a3","sequence":5},"last":{"id":"9865268e-0a39-43a0-89d0-251a820ec8a3","sequence":5}},"mode":"allowAll","source":"approvalReconfigure","commandId":"01a11a6d-2d3e-7000-b0e7-f04c53ee070b","clientName":"t3_code"},"emittedAtMs":1791444725268}} diff --git a/apps/server/src/preview/ServerBrowser.test.ts b/apps/server/src/preview/ServerBrowser.test.ts index 385223a42d39..dec1e52d4c9c 100644 --- a/apps/server/src/preview/ServerBrowser.test.ts +++ b/apps/server/src/preview/ServerBrowser.test.ts @@ -60,14 +60,43 @@ vi.mock("./ServerBrowserContexts.ts", () => ({ }, })); -function makeSession() { +/** A frame in its own process. Only its own session reaches the copy it holds. */ +function makeFrame() { + const frame = { + copy: "", + detached: false, + isDetached: () => frame.detached, + recording: Promise.withResolvers(), + }; + return frame; +} + +function makeSession(frame?: ReturnType) { + const events = new NodeEvents.EventEmitter(); return { - on: vi.fn(), + on: vi.fn((name: string, listener: () => void) => events.on(name, listener)), + emit: (name: string) => events.emit(name), detach: vi.fn(async () => {}), - send: vi.fn(async (method: string, _input?: unknown): Promise> => { + send: vi.fn(async (method: string, input?: unknown): Promise> => { if (method === "Page.getNavigationHistory") return { currentIndex: 0, entries: [{}] }; if (method === "Page.getLayoutMetrics") return { cssVisualViewport: { pageX: 0, pageY: 0 } }; if (method === "Page.captureScreenshot") return { data: "ZnJhbWU=" }; + if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } }; + if (method === "Page.createIsolatedWorld") return { executionContextId: 7 }; + if (method === "Page.addScriptToEvaluateOnNewDocument") frame?.recording.resolve(); + // A copy or cut key copies keyCopy in the focused frame, or the page's process if none; + // one that copies nothing leaves the frames as they were. + if (method === "Input.dispatchKeyEvent" && (input as { commands?: unknown }).commands) { + if (focusedFrame) focusedFrame.copy = keyCopy || focusedFrame.copy; + else pageCopy = keyCopy || pageCopy; + } + // The clipboard world hands over what the session's frames copied, once. + if (method === "Runtime.evaluate" && (input as { contextId?: number }).contextId === 7) { + const value = frame ? frame.copy : pageCopy; + if (frame) frame.copy = ""; + else pageCopy = ""; + return { result: { value } }; + } return { result: { value: "evaluated" } }; }), }; @@ -91,6 +120,7 @@ function makeContext(onClose?: (context: BrowserContext) => void) { setDefaultNavigationTimeout: vi.fn(), context: () => context, mainFrame: () => page, + frames: () => [page], url: () => url, title: vi.fn(async () => "test page"), viewportSize: () => viewport, @@ -130,12 +160,10 @@ function makeContext(onClose?: (context: BrowserContext) => void) { sessions, newPage: async () => page as unknown as Page, grantPermissions: vi.fn(async () => {}), - exposeBinding: vi.fn(async (_name: string, binding: ClipboardBinding) => { - clipboardBinding = binding; - }), - addInitScript: vi.fn(async () => {}), - newCDPSession: async () => { - const session = makeSession(); + newCDPSession: async (target: unknown) => { + const session = makeSession( + target === page ? undefined : (target as ReturnType), + ); sessions.push(session); return session; }, @@ -153,8 +181,12 @@ const contexts: ReturnType[] = []; /** The profile and isolation each headless tab asked its context for. */ const contextRequests: Array<{ profileId: string; isolated: boolean }> = []; let contextGate: PromiseWithResolvers | null = null; -type ClipboardBinding = (source: { page: unknown }, text: unknown) => void; -let clipboardBinding: ClipboardBinding | null = null; +/** The text the page's frames hold from their latest copy. */ +let pageCopy = ""; +/** The text the next copy or cut key copies. */ +let keyCopy = ""; +/** The frame in its own process that has focus; otherwise keys copy in the page's process. */ +let focusedFrame: ReturnType | null = null; let contextFailure: Error | null = null; /** Server tabs the fake desktop renders, and the endpoints the server connected to. */ let desktopRendersNext = false; @@ -272,6 +304,9 @@ beforeEach(() => { contextRequests.length = 0; contextGate = null; contextFailure = null; + pageCopy = ""; + keyCopy = ""; + focusedFrame = null; desktopTabs.clear(); desktopRendersNext = false; releasedDesktopTabs.length = 0; @@ -1007,11 +1042,10 @@ it.live("closing a tab while a viewer is still opening it does not leave its pag ).pipe(Effect.provide(layer)), ); -it.live("page copies reach only the controlling viewer right after its input", () => +it.live("only the controlling viewer's copy and cut keys reach its clipboard", () => Effect.scoped( Effect.gen(function* () { const { browser, tabId } = yield* ready; - const page = contexts[0]!.page; const watcher = yield* browser.attachViewer(viewerInput(tabId, false)); const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); yield* viewer.input({ type: "takeControl" }); @@ -1019,22 +1053,68 @@ it.live("page copies reach only the controlling viewer right after its input", ( Queue.clear(queue).pipe( Effect.map((items) => items.filter((item) => item._tag === "clipboard")), ); - // A page writing on its own, without a recent gesture, stays on the server. - clipboardBinding!({ page }, "unprompted"); + // What the page copied on its own stays on the server through other input. + pageCopy = "unprompted"; + yield* viewer.input({ type: "mouse", action: "move", x: 10, y: 10 }); + yield* viewer.input({ type: "wheel", x: 10, y: 10, deltaY: 40 }); + yield* viewer.input({ type: "key", action: "down", key: "v", code: "KeyV", modifiers: 4 }); + yield* viewer.input({ type: "unknown" }); expect(yield* clipboard(viewer.output)).toEqual([]); + keyCopy = "copied"; yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }); const cdp = contexts[0]!.sessions.at(-1)!; expect(cdp.send).toHaveBeenCalledWith( "Input.dispatchKeyEvent", expect.objectContaining({ key: "c", commands: ["copy"] }), ); - clipboardBinding!({ page }, "copied"); expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "copied" }]); + keyCopy = "cut"; + yield* viewer.input({ type: "key", action: "down", key: "x", code: "KeyX", modifiers: 2 }); + expect(yield* clipboard(viewer.output)).toEqual([{ _tag: "clipboard", text: "cut" }]); + // A copy key with nothing copied sends nothing, not what a frame kept from before. + pageCopy = "left over"; + keyCopy = ""; + yield* viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }); + expect(yield* clipboard(viewer.output)).toEqual([]); expect(yield* clipboard(watcher.output)).toEqual([]); }), ).pipe(Effect.provide(layer)), ); +it.live("copy keys reach the viewer from a frame in its own process", () => + Effect.scoped( + Effect.gen(function* () { + const { browser, tabId } = yield* ready; + const viewer = yield* browser.attachViewer(viewerInput(tabId, true)); + yield* viewer.input({ type: "takeControl" }); + const copy = () => + viewer.input({ type: "key", action: "down", key: "c", code: "KeyC", modifiers: 4 }).pipe( + Effect.andThen(Queue.clear(viewer.output)), + Effect.map((items) => items.filter((item) => item._tag === "clipboard")), + ); + const frame = makeFrame(); + contexts[0]!.page.emit("framenavigated", frame); + yield* Effect.promise(() => frame.recording.promise); + const frameSession = contexts[0]!.sessions.at(-1)!; + focusedFrame = frame; + keyCopy = "framed"; + expect(yield* copy()).toEqual([{ _tag: "clipboard", text: "framed" }]); + // What the frame kept from before is cleared, not sent by a key elsewhere. + frame.copy = "left over"; + focusedFrame = null; + keyCopy = ""; + expect(yield* copy()).toEqual([]); + expect(frame.copy).toBe(""); + // A frame that went away is no longer read. + frame.detached = true; + frame.copy = "gone"; + frameSession.emit("close"); + expect(yield* copy()).toEqual([]); + expect(frame.copy).toBe("gone"); + }), + ).pipe(Effect.provide(layer)), +); + it.live("a page download is saved, offered to the controller, and listed for the agent", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/preview/ServerBrowser.ts b/apps/server/src/preview/ServerBrowser.ts index 939d112c4908..87789692eb3e 100644 --- a/apps/server/src/preview/ServerBrowser.ts +++ b/apps/server/src/preview/ServerBrowser.ts @@ -66,6 +66,7 @@ import type { Dialog, Download, FileChooser, + Frame, Page, } from "playwright-core"; @@ -262,8 +263,6 @@ interface ViewerState { readonly pause: () => Promise; readonly resume: () => Promise; scrolledAt: number; - /** Last input from this viewer; page copies reach its clipboard only right after. */ - inputAt: number; /** Panel bounds, retained in fixed mode; passive viewers never request a size. */ requestedSize: { width: number; height: number; order: number } | null; } @@ -290,6 +289,8 @@ interface ServerTab { readonly tabId: string; readonly page: Page; readonly cdp: CDPSession; + /** Sessions of the page's frames that run in their own process. */ + readonly frameSessions: Map; readonly createdAt: number; /** The agent's latest request on this tab; idle agent tabs close. */ usedAt: number; @@ -434,43 +435,50 @@ const editingCommand = (key: string, modifiers: number) => { }; const CLIPBOARD_TEXT_LIMIT = 1024 * 1024; -/** Copies reach the viewer only this soon after it last touched the page. */ -const CLIPBOARD_GESTURE_MS = 5_000; -const CLIPBOARD_BINDING = "__t3PreviewClipboard"; -// Headless Chromium shares one clipboard between every context, so pages -// report their own copies instead of the clipboard being read back. +const CLIPBOARD_WORLD = "t3-preview-clipboard"; +// Headless Chromium shares one clipboard between every context, so the copy +// a viewer's copy or cut key makes is read from this world instead of the +// clipboard. Page scripts cannot see the world, and only a copy made while a +// real key is handled counts. const CLIPBOARD_SCRIPT = `(() => { - const send = (text) => { - if (typeof text !== "string" || text.length === 0) return; - try { globalThis.${CLIPBOARD_BINDING}?.(text.slice(0, ${CLIPBOARD_TEXT_LIMIT})); } catch {} - }; + let keying = false; + let copied = ""; + // The same Ctrl or Cmd + C or X that editingCommand sends as copy or cut. + addEventListener("keydown", (event) => { + if (!event.isTrusted || event.altKey || event.ctrlKey === event.metaKey) return; + const key = event.key.toLowerCase(); + if (key !== "c" && key !== "x") return; + keying = true; + copied = ""; + setTimeout(() => { keying = false; }); + }, true); const selection = () => { - const field = document.activeElement; + let field = document.activeElement; + while (field?.shadowRoot?.activeElement) field = field.shadowRoot.activeElement; if ((field instanceof HTMLInputElement || field instanceof HTMLTextAreaElement) && field.selectionStart !== null) return field.value.slice(field.selectionStart, field.selectionEnd ?? field.selectionStart); return String(document.getSelection() ?? ""); }; - // Bubbling to window runs after page handlers, before cut removes the selection. - const copied = (event) => - send(event.defaultPrevented ? event.clipboardData?.getData("text/plain") : selection()); - addEventListener("copy", copied); - addEventListener("cut", copied); - const proto = globalThis.Clipboard?.prototype; - if (!proto) return; - const writeText = proto.writeText; - proto.writeText = function (text) { - const result = writeText.call(this, text); - result.then(() => send(String(text)), () => {}); - return result; + const record = (text) => { + copied = String(text ?? "").slice(0, ${CLIPBOARD_TEXT_LIMIT}); + }; + // Capturing at window runs before page handlers can stop the event, and + // before cut removes the selection. + const snapshot = (event) => { + if (keying && event.isTrusted) record(selection()); + }; + // Bubbling back to window picks up text a page handler set instead. + const replace = (event) => { + if (keying && event.isTrusted && event.defaultPrevented) record(event.clipboardData?.getData("text/plain")); }; - const write = proto.write; - proto.write = function (items) { - const result = write.call(this, items); - result.then(async () => { - const item = [...items].find((candidate) => candidate.types.includes("text/plain")); - if (item) send(await (await item.getType("text/plain")).text()); - }, () => {}); - return result; + for (const type of ["copy", "cut"]) { + addEventListener(type, snapshot, true); + addEventListener(type, replace); + } + globalThis.takeCopy = () => { + const text = copied; + copied = ""; + return text; }; })();`; @@ -763,13 +771,14 @@ const make = Effect.gen(function* () { isolatedContext ? tabKey(snapshot.threadId, snapshot.tabId) : undefined, )); if (adopted?.page.isClosed()) throw new Error("The popup closed before it opened."); - // The desktop page already has its own clipboard; the bridge script is for headless tabs. + // The desktop page already has its own clipboard. if (!desktop) await prepareContext(context); const page = adopted?.page ?? desktop?.page ?? (await context.newPage()); const cdp = await context.newCDPSession(page); // The desktop's page is already a normal browser. A popup's first request // went out before it became a tab; everything after presents as Chrome. if (!desktop) await presentAsChrome(cdp, host); + if (!desktop) await recordCopies(cdp); page.setDefaultTimeout(NAVIGATION_TIMEOUT_MS); page.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS); const control = new SessionControl(snapshot.automationOwner ?? null, () => @@ -780,6 +789,7 @@ const make = Effect.gen(function* () { tabId: snapshot.tabId, page, cdp, + frameSessions: new Map(), createdAt: Date.now(), usedAt: Date.now(), viewers: new Set(), @@ -828,7 +838,10 @@ const make = Effect.gen(function* () { page.on("framenavigated", (frame) => { // Same-document navigations (SPA routes) fire no load event. if (frame === page.mainFrame() && !tab.loading) void reportLoaded(tab); + if (!desktop) void recordFrameCopies(tab, frame); }); + // An adopted popup's frames may have loaded before the tab listened. + if (adopted) for (const frame of page.frames()) void recordFrameCopies(tab, frame); page.on("requestfailed", (request) => { const errorText = request.failure()?.errorText ?? ""; pushBounded(tab.networkEntries, { @@ -1129,16 +1142,81 @@ const make = Effect.gen(function* () { if (preparedContexts.has(context)) return; preparedContexts.add(context); await context.grantPermissions(["clipboard-write"]); - await context.exposeBinding(CLIPBOARD_BINDING, ({ page }, text: unknown) => { - if (typeof text !== "string") return; - const tab = [...tabs.values()].find((candidate) => candidate.page === page); - const controller = tab - ? [...tab.viewers].find((viewer) => viewer.id === tab.control.controller) - : undefined; - if (!controller || Date.now() - controller.inputAt > CLIPBOARD_GESTURE_MS) return; - controller.push({ _tag: "clipboard", text: text.slice(0, CLIPBOARD_TEXT_LIMIT) }); + }; + + /** Records the copies made in each frame a session reaches. */ + const recordCopies = async (cdp: CDPSession) => { + // Scripts for new documents run only while this session's Page domain is on. + await cdp.send("Page.enable"); + await cdp.send("Page.addScriptToEvaluateOnNewDocument", { + source: CLIPBOARD_SCRIPT, + worldName: CLIPBOARD_WORLD, + runImmediately: true, + }); + }; + + /** + * A frame in its own process, such as one with an `Origin-Agent-Cluster` + * header, is out of the page session's reach, so it records copies through + * its own session until that target closes. + */ + const recordFrameCopies = async (tab: ServerTab, frame: Frame) => { + if (frame === tab.page.mainFrame() || tab.frameSessions.has(frame)) return; + // A frame in its parent's process has no session of its own. + const cdp = await tab.page + .context() + .newCDPSession(frame) + .catch(() => null); + if (!cdp) return; + if (tab.frameSessions.has(frame) || frame.isDetached()) { + await cdp.detach().catch(constVoid); + return; + } + tab.frameSessions.set(frame, cdp); + cdp.on("close", () => { + if (tab.frameSessions.get(frame) !== cdp) return; + tab.frameSessions.delete(frame); + // A frame that moved to another process records through its new target. + if (!frame.isDetached()) void recordFrameCopies(tab, frame); }); - await context.addInitScript(CLIPBOARD_SCRIPT); + await recordCopies(cdp).catch(constVoid); + }; + + /** Clears and returns the copy of each frame a session reaches. */ + const takeSessionCopies = async (cdp: CDPSession) => { + // An out-of-process frame that closed meanwhile copied nothing. + const tree = await cdp.send("Page.getFrameTree").catch(() => null); + if (!tree) return []; + const frameIds = (node: typeof tree.frameTree): Array => [ + node.frame.id, + ...(node.childFrames ?? []).flatMap(frameIds), + ]; + return Promise.all( + frameIds(tree.frameTree).map((frameId) => + cdp + .send("Page.createIsolatedWorld", { frameId, worldName: CLIPBOARD_WORLD }) + .then(({ executionContextId }) => + cdp.send("Runtime.evaluate", { + contextId: executionContextId, + expression: "globalThis.takeCopy?.()", + returnByValue: true, + }), + ) + .then( + ({ result }) => (typeof result.value === "string" ? result.value : ""), + // A frame that detached meanwhile copied nothing. + () => "", + ), + ), + ); + }; + + /** Clears every frame's copy and returns what the key just handled copied or cut. */ + const takeCopiedText = async (tab: ServerTab) => { + const copies = await Promise.all( + [tab.cdp, ...tab.frameSessions.values()].map(takeSessionCopies), + ); + return copies.flat().find((text) => text.length > 0); }; const adoptPopup = async (opener: ServerTab, popup: Page) => { @@ -2058,7 +2136,6 @@ const make = Effect.gen(function* () { ) => { const message = asRecord(raw); if (!message) return; - viewer.inputAt = Date.now(); const modifiers = modifiersOf(message); switch (message.type) { case "mouse": { @@ -2104,19 +2181,29 @@ const make = Effect.gen(function* () { viewer.pressedKeys.delete(code || key); return; } + const command = editingCommand(key, modifiers); + // Only the controlling viewer's own copy and cut reach its clipboard. + const copying = + !tab.desktop && (command?.commands[0] === "copy" || command?.commands[0] === "cut"); + // Clear what any frame kept from an earlier key, so only this key's copy is read. + if (copying) await takeCopiedText(tab); await session.send("Input.dispatchKeyEvent", { type: text ? "keyDown" : "rawKeyDown", key, code, modifiers, ...(text ? { text, unmodifiedText: text } : {}), - ...editingCommand(key, modifiers), + ...command, windowsVirtualKeyCode: num( message.keyCode, key.length === 1 ? key.toUpperCase().charCodeAt(0) : 0, ), }); viewer.pressedKeys.set(code || key, { key, code }); + if (copying) { + const copied = await takeCopiedText(tab); + if (copied) viewer.push({ _tag: "clipboard", text: copied }); + } return; } case "text": @@ -2251,7 +2338,6 @@ const make = Effect.gen(function* () { }, resume: () => startScreencast(screencastScale), scrolledAt: 0, - inputAt: 0, requestedSize: null, }; yield* Effect.acquireRelease( diff --git a/apps/server/src/process/externalLauncher.test.ts b/apps/server/src/process/externalLauncher.test.ts index 98a867d4591a..63e89541e1cd 100644 --- a/apps/server/src/process/externalLauncher.test.ts +++ b/apps/server/src/process/externalLauncher.test.ts @@ -1,5 +1,4 @@ -// @effect-diagnostics nodeBuiltinImport:off - the Windows reveal smoke test drives a real PowerShell through Node process and filesystem APIs. -import * as NodeChildProcess from "node:child_process"; +// @effect-diagnostics nodeBuiltinImport:off - the Windows launch smoke tests use filesystem notifications to observe real PowerShell launches. import * as NodeFS from "node:fs"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; @@ -124,6 +123,50 @@ it.effect("launches the default browser through the platform command", () => { ); }); +it.effect.each(["win32", "linux"] as const)( + "launches the browser through PowerShell on %s", + (platform) => { + let spawned: ChildProcess.StandardCommand | undefined; + return Effect.gen(function* () { + const launcher = yield* ExternalLauncher.ExternalLauncher; + + yield* launcher.launchBrowser("https://example.com/some path"); + + assert.ok(spawned); + assert.equal( + spawned.command, + platform === "win32" + ? "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" + : "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", + ); + assert.deepEqual(spawned.args.slice(0, -1), [ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", + "Bypass", + "-EncodedCommand", + ]); + const encodedCommand = spawned.args[spawned.args.length - 1] ?? ""; + const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); + assert.equal( + decodedCommand, + "$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path'", + ); + assert.equal(spawned.options.detached, platform !== "win32"); + }).pipe( + Effect.provide( + layerTest({ + platform, + env: { SYSTEMROOT: "C:\\Windows", WSL_DISTRO_NAME: "Ubuntu" }, + onSpawn: (command) => { + spawned = command; + }, + }), + ), + ); + }, +); + it.effect("launches an installed editor with platform-safe arguments", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -163,6 +206,7 @@ it.effect("launches an installed editor with platform-safe arguments", () => ); assert.deepEqual(spawned.args, []); assert.equal(spawned.options.shell, true); + assert.equal(spawned.options.detached, true); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -291,6 +335,7 @@ it.effect.skipIf(windowsHost)("reveals a file in Finder with open -R on macOS", assert.ok(spawned); assert.equal(spawned.command, "open"); assert.deepEqual(spawned.args, ["-R", "/workspace/media/linux-mini-v2.mp4"]); + assert.equal(spawned.options.detached, true); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); @@ -349,65 +394,95 @@ it.effect("reveals a file in File Explorer through PowerShell on Windows", () => "$ProgressPreference = 'SilentlyContinue'; Start-Process 'explorer.exe' -ArgumentList ('/select,\"' + 'C:\\workspace with spaces\\media\\author''s clip.mp4' + '\"')", ); assert.equal(spawned.options.shell, false); + assert.equal(spawned.options.detached, false); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); -// Real-chain smoke check for the Explorer selection contract: runs the exact -// PowerShell source the reveal launch encodes, against a stub that records -// the raw argument tail it receives, and asserts a spaced path arrives as the -// single `/select,""` switch. Mock argv assertions cannot prove this — -// only Windows' own PowerShell -> CreateProcess quoting chain can, so the -// test runs only where that chain exists. -// oxlint-disable-next-line t3code/no-global-process-runtime -- the skip decision needs the real host platform, outside any Effect runtime. -it.skipIf(process.platform !== "win32")( - "delivers the raw /select switch for spaced paths through real PowerShell", - { timeout: 60_000 }, - async () => { - const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-reveal-smoke-")); - try { - const recorderPath = NodePath.join(tempDir, "recorder.cmd"); - const outputPath = NodePath.join(tempDir, "argv.txt"); - NodeFS.writeFileSync(recorderPath, `@echo off\r\n>"${outputPath}" echo(%*\r\n`); - - const target = "C:/workspace with spaces/media/author's clip.mp4"; - const explorerTarget = target.replaceAll("/", "\\"); - const source = ExternalLauncher.buildFileExplorerRevealPowerShellSource( - recorderPath, - explorerTarget, - ); - const powerShellPath = `${process.env.SYSTEMROOT ?? "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`; - NodeChildProcess.execFileSync( - powerShellPath, - [ - "-NoProfile", - "-NonInteractive", - "-ExecutionPolicy", - "Bypass", - "-EncodedCommand", - Buffer.from(source, "utf16le").toString("base64"), - ], - { timeout: 30_000 }, - ); - - // Start-Process returns before the recorder runs; wait for its output. - // The waits run outside the Effect runtime on purpose: the test - // exercises the real Windows process chain in real time. - // @effect-diagnostics-next-line globalTimers:off - const sleep = (millis: number) => new Promise((resolve) => setTimeout(resolve, millis)); - // @effect-diagnostics-next-line globalDate:off - const deadline = Date.now() + 20_000; - // @effect-diagnostics-next-line globalDate:off - while (!NodeFS.existsSync(outputPath) && Date.now() < deadline) { - await sleep(100); - } - await sleep(200); - const recorded = NodeFS.readFileSync(outputPath, "utf8").trim(); - assert.equal(recorded, `/select,"${explorerTarget}"`); - } finally { - NodeFS.rmSync(tempDir, { recursive: true, force: true }); - } - }, -); +// Exercise real spawning, ignored stdio, unref, and scope cleanup. Only the +// destination application is replaced, so tests never open Explorer or a browser. +for (const kind of ["browser", "reveal"] as const) { + it.live.skipIf(!windowsHost)( + `completes a ${kind} launch through real PowerShell after the launcher scope closes`, + () => + Effect.gen(function* () { + const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-reveal-smoke-")); + const outputPath = NodePath.join(tempDir, "argv.txt"); + const watcher = NodeFS.watch(tempDir, { signal: AbortSignal.timeout(20_000) }); + try { + const recorderPath = NodePath.join(tempDir, "recorder.cmd"); + const stagingPath = NodePath.join(tempDir, "argv.tmp"); + NodeFS.writeFileSync( + recorderPath, + `@echo off\r\n>"${stagingPath}" echo(%*\r\nmove /y "${stagingPath}" "${outputPath}" >nul\r\n`, + ); + // The rename publishes a complete result; no sleeps or file polling. + const recorded = new Promise((resolve, reject) => { + watcher.on("change", () => { + if (NodeFS.existsSync(outputPath)) { + resolve(NodeFS.readFileSync(outputPath, "utf8").trim()); + } + }); + watcher.on("error", reject); + watcher.on("close", () => + reject(new Error("PowerShell did not run the recording stub")), + ); + }); + + const target = "C:/workspace with spaces/media/author's clip.mp4"; + yield* Effect.all( + [ + Effect.gen(function* () { + const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const recordingSpawner = ChildProcessSpawner.make((command) => { + assert.ok(ChildProcess.isStandardCommand(command)); + const source = Buffer.from(command.args.at(-1) ?? "", "base64") + .toString("utf16le") + .replace("'explorer.exe'", `'${recorderPath.replaceAll("'", "''")}'`); + return realSpawner.spawn( + ChildProcess.make( + command.command, + [ + ...command.args.slice(0, -1), + Buffer.from(source, "utf16le").toString("base64"), + ], + command.options, + ), + ); + }); + const launcher = yield* ExternalLauncher.make.pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, recordingSpawner), + ); + if (kind === "browser") { + yield* launcher.launchBrowser(recorderPath); + } else { + yield* launcher.launchEditor({ + editor: "file-manager", + cwd: target, + reveal: true, + }); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + Effect.promise(() => + recorded.then((value) => { + assert.equal( + value, + kind === "browser" ? "" : `/select,"${target.replaceAll("/", "\\")}"`, + ); + }), + ), + ], + { concurrency: "unbounded" }, + ); + } finally { + watcher.close(); + // The recording stub's cmd.exe can still hold the directory for a + // moment after it publishes its output, which Windows reports as EPERM. + NodeFS.rmSync(tempDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }); + } + }), + { timeout: 30_000 }, + ); +} it.effect("does not advertise reveal on Windows when PowerShell is missing", () => Effect.gen(function* () { @@ -488,6 +563,7 @@ it.effect.skipIf(windowsHost)( // The reveal routes through interop PowerShell so Explorer receives its // raw `/select,""` switch even for spaced paths. assert.equal(spawned.command, "powershell.exe"); + assert.equal(spawned.options.detached, true); const encodedCommand = spawned.args[spawned.args.length - 1] ?? ""; const decodedCommand = Buffer.from(encodedCommand, "base64").toString("utf16le"); assert.equal( diff --git a/apps/server/src/process/externalLauncher.ts b/apps/server/src/process/externalLauncher.ts index 8ab130b01e38..3f2dab8f4499 100644 --- a/apps/server/src/process/externalLauncher.ts +++ b/apps/server/src/process/externalLauncher.ts @@ -62,6 +62,8 @@ interface EditorLaunch { readonly target: string; readonly command: string; readonly args: ReadonlyArray; + /** Defaults to true. See WINDOWS_POWERSHELL_DETACHED. */ + readonly detached?: boolean; } interface ProcessLaunch { @@ -93,6 +95,12 @@ const POWERSHELL_ARGUMENTS_PREFIX = [ "-EncodedCommand", ] as const; +// Windows PowerShell started with DETACHED_PROCESS exits 0 without running its +// command, so native Windows launches through it stay attached. The child is +// still unref'd with ignored stdio, so nothing waits on it. WSL interop +// PowerShell starts from a Linux process and keeps the detached launch. +const WINDOWS_POWERSHELL_DETACHED = false; + const DETACHED_IGNORE_STDIO_OPTIONS = { detached: true, stdin: "ignore", @@ -219,7 +227,11 @@ function shouldUseWindowsHostFromWsl( ); } -function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch { +function resolveWindowsBrowserLaunch( + target: string, + command: string, + detached: boolean, +): ProcessLaunch { const encodedCommand = encodeUtf16LeBase64( `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`, ); @@ -227,7 +239,7 @@ function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLa command, args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand], options: { - detached: true, + detached, shell: false, stdin: "ignore", stdout: "ignore", @@ -407,11 +419,15 @@ function buildBrowserLaunch( } if (platform === "win32") { - return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env)); + return resolveWindowsBrowserLaunch( + target, + resolvePowerShellPath(env), + WINDOWS_POWERSHELL_DETACHED, + ); } if (shouldUseWindowsHostFromWsl(platform, env)) { - return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath()); + return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath(), true); } return { @@ -588,14 +604,8 @@ const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* ( * when the path has spaces and Explorer misparses it, silently opening a * fallback folder. A single `-ArgumentList` string in Windows PowerShell 5.1 * reaches the child's command line verbatim, preserving the raw switch. - * - * Exported so the Windows smoke test can drive the identical source through a - * real PowerShell against a recording stub instead of Explorer. */ -export function buildFileExplorerRevealPowerShellSource( - explorerCommand: string, - target: string, -): string { +function buildFileExplorerRevealPowerShellSource(explorerCommand: string, target: string): string { return `$ProgressPreference = 'SilentlyContinue'; Start-Process ${escapePowerShellStringLiteral(explorerCommand)} -ArgumentList ('/select,"' + ${escapePowerShellStringLiteral(target)} + '"')`; } @@ -636,11 +646,14 @@ const resolveFileManagerRevealLaunch = Effect.fn("resolveFileManagerRevealLaunch } if (platform === "win32") { - return fileExplorerRevealLaunch( - target, - normalizeWindowsFileManagerPath(target), - resolvePowerShellPath(env), - ); + return { + ...fileExplorerRevealLaunch( + target, + normalizeWindowsFileManagerPath(target), + resolvePowerShellPath(env), + ), + detached: WINDOWS_POWERSHELL_DETACHED, + }; } if ( @@ -744,7 +757,7 @@ const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(fu command: spawnCommand.command, args: spawnCommand.args, options: { - detached: true, + detached: launch.detached ?? true, shell: spawnCommand.shell, stdin: "ignore", stdout: "ignore", diff --git a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts index 657e377a7fd9..69dcf3039a53 100644 --- a/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts +++ b/apps/server/src/provider/ClaudeCapabilitiesProbe.test.ts @@ -41,6 +41,7 @@ it("isolates Claude capability probes without dropping workspace setting sources FORCE_CODE_TERMINAL: "1", }, cwd: "/workspace/project", + managedMcpConfig: false, }); assert.deepEqual(options.mcpServers, {}); @@ -59,6 +60,21 @@ it("isolates Claude capability probes without dropping workspace setting sources assert.equal(options.env?.CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL, "1"); }); +it("drops strict MCP mode, and only that, next to an administrator's managed-mcp.json", () => { + const options = buildClaudeCapabilitiesProbeQueryOptions({ + executablePath: "/usr/bin/claude", + abortController: new AbortController(), + environment: { HOME: "/home/user" }, + cwd: undefined, + managedMcpConfig: true, + }); + + // Claude exits before initializing when handed --strict-mcp-config here. + assert.equal(options.strictMcpConfig, undefined); + assert.deepEqual(options.mcpServers, {}); + assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false"); +}); + it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => { it.effect( "discovers commands and skills separately for each cwd without replacing machine metadata", diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index 9fa7d647bd0f..c4737264a491 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -35,7 +35,7 @@ import { type ServerProviderDraft, } from "@t3tools/provider-core/server/snapshotProbe"; import { resolveClaudeSdkExecutablePath } from "./Drivers/ClaudeExecutable.ts"; -import { makeClaudeEnvironment } from "./Drivers/ClaudeHome.ts"; +import { hasClaudeManagedMcpConfig, makeClaudeEnvironment } from "./Drivers/ClaudeHome.ts"; import { discoverClaudeSkills } from "./Drivers/ClaudeSkills.ts"; import type { ProviderWorkspaceSnapshot } from "@t3tools/provider-core/server/driver"; import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits"; @@ -224,6 +224,8 @@ export function buildClaudeCapabilitiesProbeQueryOptions(input: { readonly abortController: AbortController; readonly environment: NodeJS.ProcessEnv; readonly cwd: string | undefined; + /** An administrator's `managed-mcp.json` is installed; see `hasClaudeManagedMcpConfig`. */ + readonly managedMcpConfig: boolean; }): ClaudeQueryOptions { return { persistSession: false, @@ -236,9 +238,10 @@ export function buildClaudeCapabilitiesProbeQueryOptions(input: { settings: { disableAllHooks: true }, allowedTools: [], // Ignore MCP definitions from every filesystem setting source above. The - // SDK combines this empty explicit map with --strict-mcp-config. + // SDK combines this empty explicit map with --strict-mcp-config, which + // Claude refuses next to a managed-mcp.json that already excludes them. mcpServers: {}, - strictMcpConfig: true, + ...(input.managedMcpConfig ? {} : { strictMcpConfig: true }), env: { ...input.environment, // Connected claude.ai MCP servers are discovered outside filesystem @@ -385,6 +388,7 @@ const probeClaudeCapabilities = ( claudeSettings.binaryPath, claudeEnvironment, ); + const managedMcpConfig = yield* hasClaudeManagedMcpConfig(); return yield* Effect.tryPromise(async () => { const q = claudeQuery({ // Never yield — we only need initialization data, not a conversation. @@ -398,6 +402,7 @@ const probeClaudeCapabilities = ( abortController: abort, environment: claudeEnvironment, cwd, + managedMcpConfig, }), }); const init = await q.initializationResult(); diff --git a/apps/server/src/provider/Drivers/ClaudeHome.ts b/apps/server/src/provider/Drivers/ClaudeHome.ts index 78bb34c2fd9e..ebd19acb8dc7 100644 --- a/apps/server/src/provider/Drivers/ClaudeHome.ts +++ b/apps/server/src/provider/Drivers/ClaudeHome.ts @@ -1,5 +1,6 @@ import type { ClaudeSettings } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; @@ -53,6 +54,25 @@ export const makeClaudeEnvironment = Effect.fn("makeClaudeEnvironment")(function }; }); +/** + * Whether an administrator installed Claude Code's `managed-mcp.json`. While it + * exists Claude refuses `--strict-mcp-config` and exits before initializing, + * but it already ignores user, project and `--mcp-config` servers on its own, + * so callers that pass the flag for isolation can drop it. Paths match the + * ones Claude Code checks. + */ +export const hasClaudeManagedMcpConfig = Effect.fn("hasClaudeManagedMcpConfig")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const platform = yield* HostProcess.Platform; + const managedMcpConfigPath = + platform === "darwin" + ? "/Library/Application Support/ClaudeCode/managed-mcp.json" + : platform === "win32" + ? "C:\\Program Files\\ClaudeCode\\managed-mcp.json" + : "/etc/claude-code/managed-mcp.json"; + return yield* fileSystem.exists(managedMcpConfigPath).pipe(Effect.orElseSucceed(() => false)); +}); + export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationGroupKey")( function* ( config: Pick, diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index 20c815fc9b32..d05038ca86cc 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -1,8 +1,9 @@ // @effect-diagnostics-next-line nodeBuiltinImport:off - Effect's File.Info has no ctime or sub-millisecond mtime, which the cache tests compare. import * as NodeFSP from "node:fs/promises"; +import * as NodeSqlite from "node:sqlite"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { assert, describe, it } from "@effect/vitest"; +import { assert, describe, it, vi } from "@effect/vitest"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -10,6 +11,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as SqlClient from "effect/sql/SqlClient"; +import * as Tracer from "effect/Tracer"; import { makeAntigravityUsageCache, readAntigravityUsage } from "./antigravityUsageReader.ts"; @@ -445,4 +447,141 @@ describe("readAntigravityUsage", () => { assert.strictEqual(records(result)[0]?.totals.uncachedInputTokens, 10); }).pipe(Effect.provide(NodeServices.layer)), ); + + /** Counts the rows each StatementSync.all() call returns, by its SQL. */ + const recordReads = Effect.gen(function* () { + const reads: Array<{ sql: string; rows: number }> = []; + const all = NodeSqlite.StatementSync.prototype.all; + yield* Effect.acquireRelease( + Effect.sync(() => + vi.spyOn(NodeSqlite.StatementSync.prototype, "all").mockImplementation(function ( + this: NodeSqlite.StatementSync, + ...params + ) { + const result = all.apply(this, params); + reads.push({ sql: this.sourceSQL, rows: result.length }); + return result; + }), + ), + (spy) => Effect.sync(() => spy.mockRestore()), + ); + return reads; + }); + + const stepUsage = (responseId: string) => + new Uint8Array(protoBytes(9, [...protoNumber(2, 10), ...protoText(11, responseId)])); + + it.effect("reads one Antigravity generation or one page of steps per statement", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const dir = yield* tempDir; + yield* seedDatabase(path.join(dir, "session-1.db"), (db) => + Effect.gen(function* () { + // Antigravity's keys and indexes: idx is the INTEGER PRIMARY KEY, and steps has indexes. + yield* db.exec( + "CREATE TABLE `gen_metadata` (`idx` integer,`data` blob,`size` integer NOT NULL DEFAULT 0,PRIMARY KEY (`idx`))", + ); + yield* db.exec( + "CREATE TABLE `steps` (`idx` integer,`step_type` integer NOT NULL DEFAULT 0,`status` integer NOT NULL DEFAULT 0,`metadata` blob,PRIMARY KEY (`idx`))", + ); + yield* db.exec("CREATE INDEX `idx_steps_status` ON `steps`(`status`)"); + yield* db.exec("CREATE INDEX `idx_steps_step_type` ON `steps`(`step_type`)"); + yield* db.exec("BEGIN"); + for (let idx = 0; idx < 3; idx++) { + yield* db.run("INSERT INTO gen_metadata (idx, data) VALUES (?, ?)", [ + idx, + antigravityGeneration(`g-${idx}`), + ]); + } + // A run of steps without metadata sits between steps with usage. + for (let idx = 0; idx < 250; idx++) { + yield* db.run("INSERT INTO steps (idx, metadata) VALUES (?, ?)", [ + idx, + idx >= 75 && idx < 175 ? null : stepUsage(`s-${idx}`), + ]); + } + yield* db.exec("COMMIT"); + }), + ); + const reads = yield* recordReads; + const spans: Tracer.NativeSpan[] = []; + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + spans.push(span); + return span; + }, + }); + const result = yield* readAntigravityUsage(dir, 0).pipe( + Effect.provideService(Tracer.Tracer, tracer), + ); + assert.deepStrictEqual(result.errors, []); + assert.deepStrictEqual( + records(result).map((record) => record.dedupeKey), + [ + ...Array.from({ length: 75 }, (_, idx) => `antigravity:11:s-${idx}`), + ...Array.from({ length: 75 }, (_, idx) => `antigravity:11:s-${idx + 175}`), + ...Array.from({ length: 3 }, (_, idx) => `antigravity:11:g-${idx}`), + ], + ); + // Page statements are untraced, so the trace does not grow with the tables. + assert.isTrue(spans.some((span) => span.name === "sqlite")); + assert.deepStrictEqual( + spans.flatMap((span) => { + const query = span.attributes.get("db.query.text"); + return typeof query === "string" && query.includes("rowid > ?") ? [query] : []; + }), + [], + ); + // Every row, with metadata or not, comes back through a bounded statement. + for (const [table, total, most] of [ + ["steps", 250, 64], + ["gen_metadata", 3, 1], + ] as const) { + const rows = reads + .filter((read) => read.sql.includes(`FROM ${table} `)) + .map((read) => read.rows); + assert.strictEqual( + rows.reduce((sum, count) => sum + count, 0), + total, + table, + ); + assert.isAtMost(Math.max(...rows), most, table); + } + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("returns Antigravity records in idx order however the rows are stored", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const dir = yield* tempDir; + yield* seedDatabase(path.join(dir, "session-1.db"), (db) => + Effect.gen(function* () { + yield* createTables(db); + yield* db.exec("BEGIN"); + // Stored in reverse idx order, so rowid order is the opposite of idx order. + for (let idx = 99; idx >= 0; idx--) { + yield* db.run("INSERT INTO steps VALUES (?, ?)", [idx, stepUsage(`s-${idx}`)]); + } + for (const idx of [1, 0]) { + yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ + idx, + antigravityGeneration(`g-${idx}`), + ]); + } + yield* db.exec("COMMIT"); + }), + ); + const result = yield* readAntigravityUsage(dir, 0); + assert.deepStrictEqual(result.errors, []); + assert.deepStrictEqual( + records(result).map((record) => record.dedupeKey), + [ + ...Array.from({ length: 100 }, (_, idx) => `antigravity:11:s-${idx}`), + "antigravity:11:g-0", + "antigravity:11:g-1", + ], + ); + }).pipe(Effect.provide(NodeServices.layer)), + ); }); diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index e48609cf874d..5239d5d551c3 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -132,11 +132,12 @@ function metadata(bytes: Uint8Array, step: boolean): Metadata { const data = step ? root : nested(root, 1); const model = step ? nested(data, 24) : data; const usage = bytesAt(data, step ? 9 : 4); - const usages = usage === undefined ? [] : [fields(usage)]; + // Copy the usage bytes: subarrays kept in usages would hold each row's whole blob alive. + const usages = usage === undefined ? [] : [fields(usage.slice())]; for (const retry of data.get(step ? 28 : 17) ?? []) { if (!(retry instanceof Uint8Array)) throw new Error("Invalid retry metadata"); const retryUsage = bytesAt(fields(retry), 2); - if (retryUsage !== undefined) usages.push(fields(retryUsage)); + if (retryUsage !== undefined) usages.push(fields(retryUsage.slice())); } return { model: modelName( @@ -171,6 +172,14 @@ class AntigravityDatabaseDecodeError extends Schema.TaggedError = []; - for (const row of yield* sql.unsafe>(query)) { - const idx = row.idx; - if (typeof idx !== "number") { - return yield* new AntigravityDatabaseDecodeError({ path }); + // Below every rowid. + let after = -Infinity; + while (true) { + // Untraced: a cold read runs one of these per generation. + const rows = yield* sql + .unsafe<{ + readonly row_id: number; + readonly idx: unknown; + readonly data: unknown; + }>(query, [after, pageRows]) + .pipe(Effect.withTracerEnabled(false)); + for (const row of rows) { + // Skipped here rather than in SQL, so a statement never scans past + // more than one page of steps that have no metadata. + if (step && row.data === null) continue; + const idx = row.idx; + if (typeof idx !== "number") { + return yield* new AntigravityDatabaseDecodeError({ path }); + } + entries.push({ idx, entry: yield* decode(() => metadata(blob(row.data), step)) }); } - entries.push({ idx, entry: yield* decode(() => metadata(blob(row[column]), step)) }); - if (entries.length % 256 === 0) yield* Effect.yieldNow; + if (rows.length < pageRows) break; + after = rows[rows.length - 1]!.row_id; + yield* Effect.yieldNow; } - return entries; + return entries.sort((a, b) => a.idx - b.idx); }); const generations = tables.has("gen_metadata") - ? yield* readMetadata("SELECT idx, data FROM gen_metadata ORDER BY idx", "data", false) + ? yield* readMetadata( + "SELECT rowid AS row_id, idx, data FROM gen_metadata WHERE rowid > ? ORDER BY rowid LIMIT ?", + GENERATION_PAGE_ROWS, + false, + ) : []; let trajectoryTimestamp: number | null = null; if (tables.has("trajectory_metadata_blob")) { @@ -221,8 +255,8 @@ const readDatabase = Effect.fn("readDatabase")(function* ( } const steps = tables.has("steps") ? yield* readMetadata( - "SELECT idx, metadata FROM steps WHERE metadata IS NOT NULL ORDER BY idx", - "metadata", + "SELECT rowid AS row_id, idx, metadata AS data FROM steps WHERE rowid > ? ORDER BY rowid LIMIT ?", + STEP_PAGE_ROWS, true, ) : []; diff --git a/apps/server/src/provider/ProviderAccountSwitch.test.ts b/apps/server/src/provider/ProviderAccountSwitch.test.ts index 928894d26118..2571af74dc01 100644 --- a/apps/server/src/provider/ProviderAccountSwitch.test.ts +++ b/apps/server/src/provider/ProviderAccountSwitch.test.ts @@ -138,6 +138,7 @@ const claudeDriver = ( setModel: () => Effect.void, applyFlagSettings: () => Effect.void, setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), stopTask: () => Effect.void, interrupt: Effect.void, close: Effect.void, diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 370967c0fb29..708659738542 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -13,7 +13,9 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Redacted from "effect/Redacted"; import * as Stream from "effect/Stream"; +import { HttpClient, HttpClientResponse } from "effect/http"; import * as TestClock from "effect/testing/TestClock"; import type { OrchestrationProjectShell, @@ -34,6 +36,12 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPr import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli"; import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider"; +import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials"; +import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; +import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider"; +import * as GitHubQuota from "@t3tools/source-control-github/server/GitHubQuota"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; import { PullRequestProviderError, type ProviderChangeRequest, @@ -1624,6 +1632,196 @@ it.effect("refreshes every reader before a queued merge confirmation finishes", ), ); +it.effect("runs branch deletion only when the host and viewer support it, never for a stack", () => + Effect.gen(function* () { + let actions = 0; + let supported = false; + let allowed = true; + const base = fakeProvider(SourceControlProviderKind.make("github")); + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [ + { + ...base, + capabilities: { + ...base.capabilities, + actions: ["delete-branch"], + stackActions: true, + get deleteBranch() { + return supported; + }, + }, + getViewerPermissions: () => + Effect.succeed({ + actions: allowed ? ["delete-branch"] : [], + comment: true, + resolve: true, + verdicts: [], + requestReviewers: false, + }), + runAction: (input) => + Effect.sync(() => { + assert.strictEqual(input.action, "delete-branch"); + actions++; + }), + }, + ], + }); + const input = { + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + action: "delete-branch" as const, + }; + assert.strictEqual( + (yield* Effect.flip(service.runAction(input)))._tag, + "PullRequestOperationError", + ); + assert.strictEqual(actions, 0); + supported = true; + assert.strictEqual( + (yield* Effect.flip( + service.runAction({ + ...input, + stackNumber: 2, + expectedStackHeads: [{ number: 1, headSha: "abc123" }], + }), + ))._tag, + "PullRequestOperationError", + ); + assert.strictEqual(actions, 0); + allowed = false; + assert.strictEqual( + (yield* Effect.flip(service.runAction(input)))._tag, + "PullRequestOperationError", + ); + assert.strictEqual(actions, 0); + allowed = true; + yield* service.runAction(input); + assert.strictEqual(actions, 1); + }), +); + +it.effect("keeps branch deletion on the credential that passed source repository permissions", () => + Effect.gen(function* () { + let activeToken = "account-a"; + const requests: Array<{ operation: string; authorization: string | undefined }> = []; + const credentials = Layer.succeed( + GitHubCredentials.GitHubCredentials, + GitHubCredentials.GitHubCredentials.of({ + get: (host) => + Effect.sync(() => ({ + host, + token: Redacted.make(activeToken), + source: "gh" as const, + fingerprint: `${host}:${activeToken}`, + })), + invalidate: () => Effect.void, + }), + ); + const http = Layer.succeed( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.sync(() => { + const operation = request.url.endsWith("/user") + ? "user" + : request.body._tag === "Uint8Array" + ? new TextDecoder().decode(request.body.body) + : ""; + requests.push({ operation, authorization: request.headers["authorization"] }); + let body; + if (operation === "user") { + body = { id: activeToken === "account-a" ? 101 : 202, login: activeToken }; + } else if (operation.includes("query PullRequestBranchToDelete")) { + body = { + data: { + repository: { + pullRequest: { + state: "MERGED", + headRefName: "feature", + baseRefName: "main", + headRefOid: "abc123", + headRepository: { id: "FORK_REPO" }, + }, + }, + }, + }; + } else if (operation.includes("query PullRequestSourceBranch")) { + body = { + data: { + node: { + defaultBranchRef: { name: "main" }, + ref: { target: { oid: "abc123" } }, + }, + }, + }; + } else if (operation.includes("updateRefs(")) { + body = { data: { updateRefs: {} } }; + } else { + activeToken = "account-b"; + body = { + data: { + repository: { + mergeCommitAllowed: true, + squashMergeAllowed: true, + rebaseMergeAllowed: true, + viewerPermission: "READ", + pullRequest: { + viewerCanUpdate: false, + viewerDidAuthor: false, + headRepository: { viewerPermission: "WRITE" }, + }, + }, + }, + }; + } + return HttpClientResponse.fromWeb(request, new Response(JSON.stringify(body))); + }), + ), + ); + const provider = yield* GitHubPullRequestProvider.make.pipe( + Effect.provide( + GitHubPullRequestApi.layer.pipe( + Layer.provide( + GitHubApi.layer.pipe( + Layer.provide(Layer.mergeAll(credentials, http)), + Layer.provide(GitHubQuota.layer), + Layer.provide(SourceControlRateLimit.layer), + ), + ), + Layer.provide(TestSourceControlHost.layer()), + Layer.provide(NodeServices.layer), + ), + ), + ); + const service = yield* makeService({ + projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })], + providers: [provider], + }); + yield* service.runAction({ + projectId: "p1" as ProjectId, + repository: "acme/web", + number: 1, + action: "delete-branch", + }); + assert.strictEqual(activeToken, "account-b"); + assert.strictEqual( + requests.filter(({ operation }) => operation.includes("updateRefs(")).length, + 1, + ); + assert.deepStrictEqual( + requests.map(({ authorization }) => authorization), + [ + "Bearer account-a", + "Bearer account-a", + "Bearer account-a", + "Bearer account-a", + "Bearer account-a", + ], + ); + }), +); + it.effect("refuses an action this viewer may not take, and says what access it takes", () => Effect.gen(function* () { let ran: string | null = null; diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index dd60462d5f8c..659e0605f66e 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -356,6 +356,7 @@ const ACTION_ACCESS_REFUSALS: Record = { "disable-auto-merge": "You need write access on this repository to stop it being merged for you once it is ready.", revert: "You need write access on this repository to open a revert pull request.", + "delete-branch": "You need write access on the source repository to delete its branch.", "approve-workflows": "You need write access on this repository to approve workflows from a fork pull request.", }; @@ -2019,6 +2020,14 @@ export const make = Effect.gen(function* () { const runAction = (input: PullRequestActionInput): Effect.Effect => requireProject(input).pipe( Effect.flatMap((project): Effect.Effect => { + if (input.action === "delete-branch" && project.api.capabilities.deleteBranch !== true) { + return Effect.fail( + new PullRequestOperationError({ + operation: "runAction", + detail: "This host cannot delete a change request's source branch.", + }), + ); + } if ( input.stackNumber !== undefined && (project.api.capabilities.stackActions !== true || @@ -2073,7 +2082,7 @@ export const make = Effect.gen(function* () { // What the host can do and what this account may ask of it are two questions, and both // have to say yes. The second is asked last, because it costs a request and the checks // above do not. - return viewerPermissionsOf( + const operation = viewerPermissionsOf( project, input, "runAction", @@ -2158,6 +2167,17 @@ export const make = Effect.gen(function* () { ); }), ); + return input.action === "delete-branch" && project.api.withVerifiedCredential !== undefined + ? project.api + .withVerifiedCredential( + { cwd: project.project.workspaceRoot, host: project.host }, + () => operation.pipe(Effect.result), + ) + .pipe( + Effect.mapError(toPullRequestError("runAction")), + Effect.flatMap(Effect.fromResult), + ) + : operation; }), ); diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.ts index 681f2381bb9f..944f58c7970e 100644 --- a/apps/server/src/relay/AgentAwarenessRelay.test.ts +++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts @@ -203,6 +203,7 @@ const makeTestRelay = Effect.fnUntraced(function* ( getThreadProjection: unused, getCheckpointContext: unused, getThreadSnapshot: unused, + getThreadTranscript: unused, getThreadSnapshotWindow: unused, getProjectThreadRecords: () => Effect.die("unused project record read"), getProjectThread: unused, diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 701bff1a1391..fe0ed32ca7cd 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -6,6 +6,7 @@ import * as Semaphore from "effect/Semaphore"; import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; +import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -593,6 +594,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer), ), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* DelegatedTaskQuestionReactor.DelegatedTaskQuestionReactor; + yield* service.start(); + }), + ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), // Subscribes to `account.rate-limits.updated` so usage bars track live // telemetry instead of waiting for the next status probe. ProviderUsageLimitsIngestion.layer, diff --git a/apps/server/src/serverLogger.ts b/apps/server/src/serverLogger.ts index 4dee5b7d1b63..35909c2d1e03 100644 --- a/apps/server/src/serverLogger.ts +++ b/apps/server/src/serverLogger.ts @@ -1,3 +1,4 @@ +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as SharedObservability from "@t3tools/shared/observability"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -10,6 +11,7 @@ import * as ServerConfig from "./config.ts"; export const layer = Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; + const hostName = yield* HostProcess.Hostname; const layerMinimumLogLevel = Layer.succeed(References.MinimumLogLevel, config.logLevel); const logs = config.otlpLogsExport; @@ -20,7 +22,7 @@ export const layer = Effect.gen(function* () { url: config.otlpLogsUrl, exportInterval: `${logs.exportIntervalMs} millis`, headers: logs.headers, - resource: ServerConfig.otlpResource(config), + resource: ServerConfig.otlpResource(config, hostName), }); // `Logger.layer` writes the whole logger set rather than adding to it, so diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 83936691e785..da696c2bc9eb 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -580,7 +580,7 @@ it.layer(NodeServices.layer)("server settings", (it) => { ).pipe(Effect.provide(layerServerSettings())), ); - it.effect("persists custom usage prices and removes them from the settings file", () => + it.effect("preserves saved usage settings during cleanup edits and removes custom prices", () => Effect.scoped( Effect.gen(function* () { const serverConfig = yield* ServerConfig.ServerConfig; @@ -596,8 +596,30 @@ it.layer(NodeServices.layer)("server settings", (it) => { .pipe(Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(ServerSettings)))); yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": prices } }); + const usageModelAliases = { "example-preview": "example-model" }; + const sourceId = UsageLimitSourceId.make("hub"); + const usageLimitSources = { + [sourceId]: { + kind: "cliproxy" as const, + url: "https://hub.example.test", + managementKey: "", + enabled: true, + }, + }; + const saved = yield* serverSettings.updateSettings({ + usageModelAliases, + usageLimitSources, + }); + const updated = yield* serverSettings.updateSettings({ + storageCleanup: { worktreeSettledAfterDays: 0, worktreeKeepWhen: "any-local-files" }, + }); + assert.deepStrictEqual(updated.usageLimitSources, saved.usageLimitSources); const persisted = yield* readPersisted; assert.deepStrictEqual(persisted.usagePriceOverrides, { "example-model": prices }); + assert.deepStrictEqual(persisted.usageModelAliases, usageModelAliases); + assert.deepStrictEqual(persisted.usageLimitSources, usageLimitSources); + assert.equal(persisted.storageCleanup.worktreeSettledAfterDays, 0); + assert.equal(persisted.storageCleanup.worktreeKeepWhen, "any-local-files"); yield* serverSettings.updateSettings({ usagePriceOverrides: { "example-model": null } }); const restored = yield* readPersisted; diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 2b5c1f694006..a29e5d2a051e 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -9,11 +9,14 @@ import type * as Path from "effect/Path"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as Schema from "effect/Schema"; +import { SCAN_CACHE_FILE_NAME } from "./usage/usageScanCache.ts"; +import { TestClock } from "effect/testing"; import * as SqlClient from "effect/sql/SqlClient"; import { DEFAULT_SERVER_SETTINGS, StorageCleanupReport, type WorktreeKeepWhen, + type StorageCleanupSettings, } from "@t3tools/contracts"; import * as ServerConfig from "./config.ts"; import * as StorageCleanup from "./storageCleanup.ts"; @@ -21,6 +24,7 @@ import * as GitVcsDriver from "./vcs/GitVcsDriver.ts"; import * as GitManager from "./git/GitManager.ts"; import * as Settings from "./serverSettings.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; +import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as TerminalManager from "./terminal/Manager.ts"; @@ -231,178 +235,197 @@ describe("merged pull request cleanup", () => { }); }); -const cleanupFixture = Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const config = yield* ServerConfig.ServerConfig; - const git = yield* GitVcsDriver.GitVcsDriver; - const repo = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" }); - const command = (cwd: string, args: string[]) => - git.execute({ operation: "cleanup-test", cwd, args }); - yield* command(repo, ["init", "-b", "main"]); - yield* command(repo, ["config", "user.email", "cleanup@example.test"]); - yield* command(repo, ["config", "user.name", "Cleanup test"]); - yield* fs.writeFileString(`${repo}/tracked.txt`, "original\n"); - yield* fs.writeFileString(`${repo}/.gitignore`, ".env\ndist/\nnode_modules/\n"); - yield* command(repo, ["add", "."]); - yield* command(repo, ["commit", "-m", "initial"]); - yield* fs.makeDirectory(config.worktreesDir, { recursive: true }); - const worktree = `${config.worktreesDir}/feature`; - yield* command(repo, ["worktree", "add", "-b", "feature", worktree]); - // worktreeOnDelete lets domain events request sweeps once a test calls activate. - let settings: import("@t3tools/contracts").ServerSettings = { - ...DEFAULT_SERVER_SETTINGS, - storageCleanup: { - ...DEFAULT_SERVER_SETTINGS.storageCleanup, - worktreeAfterDays: 8, - worktreeOnDelete: true, - }, - }; - let threads = [shell({ branch: "feature", worktreePath: worktree })]; - let editBeforeRemoval = false; - let openSessionCwd: string | null = null; - let fullStatusCalls = 0; - let snapshotReads = 0; - let events: Stream.Stream = Stream.empty; - const activated = yield* Deferred.make(); - const context = yield* Layer.build(StorageCleanup.layer).pipe( - Effect.provideService(GitVcsDriver.GitVcsDriver, { - ...git, - execute: (input) => - Effect.gen(function* () { - if (editBeforeRemoval && input.args.includes("remove")) - yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n"); - return yield* git.execute(input); - }), - statusDetailsLocal: (...args) => { - fullStatusCalls++; - return git.statusDetailsLocal(...args); - }, - }), - Effect.provideService(Settings.ServerSettingsService, { - getSettings: Effect.sync(() => settings), - subscribeChanges: Effect.succeed(Stream.empty), - } as unknown as Settings.ServerSettingsService["Service"]), - Effect.provideService(ProjectStore.ProjectStoreV2, { - listShells: () => Effect.succeed([{ id: ProjectId.make("project-1"), workspaceRoot: repo }]), - } as unknown as ProjectStore.ProjectStoreV2["Service"]), - Effect.provideService(ProjectionStore.ProjectionStoreV2, { - getShellSnapshot: (input?: { location?: string }) => - Effect.sync(() => { - snapshotReads++; - return { threads: input?.location === "archive" ? [] : threads }; - }), - getThreadWorktreePaths: () => - Effect.sync(() => - threads.flatMap((thread) => - thread.worktreePath === null - ? [] - : [{ threadId: thread.id, worktreePath: thread.worktreePath }], - ), - ), - getThreadShell: (threadId: ThreadId) => - Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null), - } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), - Effect.provideService(Orchestrator.OrchestratorV2, { - streamDomainEvents: Stream.suspend(() => events), - } as unknown as Orchestrator.OrchestratorV2["Service"]), - Effect.provideService(SqlClient.SqlClient, ((strings: TemplateStringsArray) => - Effect.sync(() => - openSessionCwd !== null && strings.join("").includes("projection_provider_sessions") - ? [ - { - payload_json: JSON.stringify({ - id: "session-1", - driver: "codex", - providerInstanceId: "codex", - status: "ready", - cwd: openSessionCwd, - model: null, - capabilities: CodexProviderCapabilitiesV2, - createdAt: "2026-06-01T12:00:00.000Z", - updatedAt: "2026-06-01T12:00:00.000Z", - lastError: null, - }), - }, - ] - : [], - )) as unknown as SqlClient.SqlClient), - Effect.provideService(GitManager.GitManager, { - invalidateStatus: () => Effect.void, - } as unknown as GitManager.GitManager["Service"]), - Effect.provideService(TerminalManager.TerminalManager, { - subscribeMetadata: () => Effect.succeed(() => {}), - } as unknown as TerminalManager.TerminalManager["Service"]), - Effect.provideService(ServerActivation, Deferred.await(activated)), - ); - return { - service: Context.get(context, StorageCleanup.StorageCleanup), - editBeforeRemoval: () => { - editBeforeRemoval = true; - }, - fs, - worktree, - config, - command, - enableFiles: () => { - settings = { - ...settings, - storageCleanup: { - ...settings.storageCleanup, - browserArtifactsAfterDays: 8, - logsAfterDays: 8, - }, - }; - }, - setPolicy: (worktreeKeepWhen: WorktreeKeepWhen) => { - settings = { ...settings, storageCleanup: { ...settings.storageCleanup, worktreeKeepWhen } }; - }, - disable: () => { - settings = { - ...settings, - storageCleanup: { - ...settings.storageCleanup, - worktreeAfterDays: null, - worktreeOnDelete: false, +const cleanupFixture = ( + storageCleanup: StorageCleanupSettings = { + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeAfterDays: 8, + worktreeOnDelete: true, + }, +) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const config = yield* ServerConfig.ServerConfig; + const git = yield* GitVcsDriver.GitVcsDriver; + const repo = yield* fs.makeTempDirectoryScoped({ prefix: "cleanup-repo-" }); + const command = (cwd: string, args: string[]) => + git.execute({ operation: "cleanup-test", cwd, args }); + yield* command(repo, ["init", "-b", "main"]); + yield* command(repo, ["config", "user.email", "cleanup@example.test"]); + yield* command(repo, ["config", "user.name", "Cleanup test"]); + yield* fs.writeFileString(`${repo}/tracked.txt`, "original\n"); + yield* fs.writeFileString(`${repo}/.gitignore`, ".env\ndist/\nnode_modules/\n"); + yield* command(repo, ["add", "."]); + yield* command(repo, ["commit", "-m", "initial"]); + yield* fs.makeDirectory(config.worktreesDir, { recursive: true }); + const worktree = `${config.worktreesDir}/feature`; + yield* command(repo, ["worktree", "add", "-b", "feature", worktree]); + // worktreeOnDelete lets domain events request sweeps once a test calls activate. + let settings: import("@t3tools/contracts").ServerSettings = { + ...DEFAULT_SERVER_SETTINGS, + storageCleanup, + }; + let threads = [shell({ branch: "feature", worktreePath: worktree })]; + let editBeforeRemoval = false; + let openSessionCwd: string | null = null; + let sessionLive = true; + let fullStatusCalls = 0; + let snapshotReads = 0; + let events: Stream.Stream = Stream.empty; + const activated = yield* Deferred.make(); + const context = yield* Layer.build(StorageCleanup.layer).pipe( + Effect.provideService(GitVcsDriver.GitVcsDriver, { + ...git, + execute: (input) => + Effect.gen(function* () { + if (editBeforeRemoval && input.args.includes("remove")) + yield* fs.writeFileString(`${worktree}/tracked.txt`, "late edit\n"); + return yield* git.execute(input); + }), + statusDetailsLocal: (...args) => { + fullStatusCalls++; + return git.statusDetailsLocal(...args); }, - }; - }, - setThreads: (next: typeof threads) => { - threads = next; - }, - setOpenSessionCwd: (cwd: string | null) => { - openSessionCwd = cwd; - }, - fullStatusCalls: () => fullStatusCalls, - snapshotReads: () => snapshotReads, - /** Starts the hourly sweep and the subscription to `domainEvents`, which wait until now. */ - activate: (domainEvents: Stream.Stream) => { - events = domainEvents; - return Deferred.succeed(activated, undefined); - }, - }; -}); + }), + Effect.provideService(Settings.ServerSettingsService, { + getSettings: Effect.sync(() => settings), + subscribeChanges: Effect.succeed(Stream.empty), + } as unknown as Settings.ServerSettingsService["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + listShells: () => + Effect.succeed([{ id: ProjectId.make("project-1"), workspaceRoot: repo }]), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService(ProjectionStore.ProjectionStoreV2, { + getShellSnapshot: (input?: { location?: string }) => + Effect.sync(() => { + snapshotReads++; + return { threads: input?.location === "archive" ? [] : threads }; + }), + getThreadWorktreePaths: () => + Effect.sync(() => + threads.flatMap((thread) => + thread.worktreePath === null + ? [] + : [{ threadId: thread.id, worktreePath: thread.worktreePath }], + ), + ), + getThreadShell: (threadId: ThreadId) => + Effect.sync(() => threads.find((thread) => thread.id === threadId) ?? null), + } as unknown as ProjectionStore.ProjectionStoreV2["Service"]), + Effect.provideService(ProviderSessionManager.ProviderSessionManagerV2, { + isLive: () => Effect.sync(() => sessionLive), + } as unknown as ProviderSessionManager.ProviderSessionManagerV2["Service"]), + Effect.provideService(Orchestrator.OrchestratorV2, { + streamDomainEvents: Stream.suspend(() => events), + } as unknown as Orchestrator.OrchestratorV2["Service"]), + Effect.provideService(SqlClient.SqlClient, ((strings: TemplateStringsArray) => + Effect.sync(() => + openSessionCwd !== null && strings.join("").includes("projection_provider_sessions") + ? [ + { + payload_json: JSON.stringify({ + id: "session-1", + driver: "codex", + providerInstanceId: "codex", + status: "ready", + cwd: openSessionCwd, + model: null, + capabilities: CodexProviderCapabilitiesV2, + createdAt: "2026-06-01T12:00:00.000Z", + updatedAt: "2026-06-01T12:00:00.000Z", + lastError: null, + }), + }, + ] + : [], + )) as unknown as SqlClient.SqlClient), + Effect.provideService(GitManager.GitManager, { + invalidateStatus: () => Effect.void, + } as unknown as GitManager.GitManager["Service"]), + Effect.provideService(TerminalManager.TerminalManager, { + subscribeMetadata: () => Effect.succeed(() => {}), + } as unknown as TerminalManager.TerminalManager["Service"]), + Effect.provideService(ServerActivation, Deferred.await(activated)), + ); + return { + service: Context.get(context, StorageCleanup.StorageCleanup), + repo, + editBeforeRemoval: () => { + editBeforeRemoval = true; + }, + fs, + worktree, + config, + command, + enableFiles: () => { + settings = { + ...settings, + storageCleanup: { + ...settings.storageCleanup, + browserArtifactsAfterDays: 8, + logsAfterDays: 8, + }, + }; + }, + setSettings: (next: Partial) => { + settings = { ...settings, ...next }; + }, + setPolicy: (worktreeKeepWhen: WorktreeKeepWhen) => { + settings = { + ...settings, + storageCleanup: { ...settings.storageCleanup, worktreeKeepWhen }, + }; + }, + disable: () => { + settings = { + ...settings, + storageCleanup: { + ...settings.storageCleanup, + worktreeAfterDays: null, + worktreeOnDelete: false, + }, + }; + }, + setThreads: (next: typeof threads) => { + threads = next; + }, + setSessionLive: (live: boolean) => { + sessionLive = live; + }, + setOpenSessionCwd: (cwd: string | null) => { + openSessionCwd = cwd; + }, + fullStatusCalls: () => fullStatusCalls, + snapshotReads: () => snapshotReads, + /** Starts the hourly sweep and the subscription to `domainEvents`, which wait until now. */ + activate: (domainEvents: Stream.Stream) => { + events = domainEvents; + return Deferred.succeed(activated, undefined); + }, + }; + }); /** The fixture, with the size walk of its worktree held until `resume` succeeds. */ -const pausedMeasurementFixture = Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const measuring = yield* Deferred.make(); - const resume = yield* Deferred.make(); - let measuredPath: string | undefined; - const fixture = yield* cleanupFixture.pipe( - Effect.provideService(FileSystem.FileSystem, { - ...fs, - readDirectory: (directory, options) => - Effect.gen(function* () { - if (directory === measuredPath) { - yield* Deferred.succeed(measuring, undefined); - yield* Deferred.await(resume); - } - return yield* fs.readDirectory(directory, options); - }), - }), - ); - measuredPath = yield* fs.realPath(fixture.worktree); - return { ...fixture, measuring, resume }; -}); +const pausedMeasurementFixture = (storageCleanup?: StorageCleanupSettings) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const measuring = yield* Deferred.make(); + const resume = yield* Deferred.make(); + let measuredPath: string | undefined; + const fixture = yield* cleanupFixture(storageCleanup).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (directory, options) => + Effect.gen(function* () { + if (directory === measuredPath) { + yield* Deferred.succeed(measuring, undefined); + yield* Deferred.await(resume); + } + return yield* fs.readDirectory(directory, options); + }), + }), + ); + measuredPath = yield* fs.realPath(fixture.worktree); + return { ...fixture, measuring, resume }; + }); const sessionUpdated = ( index: number, status: OrchestrationV2ProviderSession["status"], @@ -444,7 +467,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("measures nested regular files without following symlinks", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, worktree, setPolicy } = yield* cleanupFixture; + const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); setPolicy("tracked-changes"); const sizes = yield* Effect.forEach(yield* fs.readDirectory(worktree), (name) => fs.stat(`${worktree}/${name}`).pipe(Effect.map((stat) => Number(stat.size))), @@ -468,7 +491,7 @@ describe("storage cleanup reports and local file policies", () => { runCleanupTest( Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; - const { service, worktree } = yield* cleanupFixture.pipe( + const { service, worktree } = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory) => fs.readDirectory(`${directory}/missing-directory`), @@ -498,7 +521,7 @@ describe("storage cleanup reports and local file policies", () => { ] as const)("keeps a worktree when %s during size measurement", ([, threadsWhileMeasuring]) => runCleanupTest( Effect.gen(function* () { - const fixture = yield* pausedMeasurementFixture; + const fixture = yield* pausedMeasurementFixture(); const { fs, worktree } = fixture; fixture.setPolicy("tracked-changes"); yield* fs.writeFileString(`${worktree}/notes.txt`, "untracked\n"); @@ -521,7 +544,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("reads the thread snapshot once per sweep, not per worktree", () => runCleanupTest( Effect.gen(function* () { - const { service, snapshotReads } = yield* cleanupFixture; + const { service, snapshotReads } = yield* cleanupFixture(); expect((yield* service.runNow).entries[0]).toMatchObject({ outcome: "removed" }); expect(snapshotReads()).toBe(1); }), @@ -535,7 +558,7 @@ describe("storage cleanup reports and local file policies", () => { ([first, second, sweeps]) => runCleanupTest( Effect.gen(function* () { - const fixture = yield* pausedMeasurementFixture; + const fixture = yield* pausedMeasurementFixture(); const handled = yield* Deferred.make(); // 20 updates arrive while the first automatic sweep measures the worktree. yield* fixture.activate( @@ -560,7 +583,7 @@ describe("storage cleanup reports and local file policies", () => { Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const walked: Array = []; - const fixture = yield* cleanupFixture.pipe( + const fixture = yield* cleanupFixture().pipe( Effect.provideService(FileSystem.FileSystem, { ...fs, readDirectory: (directory, options) => { @@ -578,7 +601,8 @@ describe("storage cleanup reports and local file policies", () => { bytes: null, }); expect(walked.filter((directory) => directory.startsWith(root))).toEqual([]); - fixture.setOpenSessionCwd(null); + // The stored session stays ready after its runtime was released. + fixture.setSessionLive(false); const removed = yield* fixture.service.runNow; expect(removed.entries[0]).toMatchObject({ outcome: "removed" }); expect(removed.entries[0]?.bytes).toBeGreaterThan(0); @@ -590,7 +614,7 @@ describe("storage cleanup reports and local file policies", () => { runCleanupTest( Effect.gen(function* () { const { service, fs, worktree, command, setThreads, fullStatusCalls } = - yield* cleanupFixture; + yield* cleanupFixture(); const changed = { outcome: "kept", reason: "Repository or branch changed" }; yield* command(worktree, ["checkout", "--detach"]); expect((yield* service.runNow).entries[0]).toMatchObject(changed); @@ -656,7 +680,7 @@ describe("storage cleanup reports and local file policies", () => { ] as const)("applies %j", ([policy, file, outcome]) => runCleanupTest( Effect.gen(function* () { - const { service, fs, worktree, setPolicy } = yield* cleanupFixture; + const { service, fs, worktree, setPolicy } = yield* cleanupFixture(); setPolicy(policy); expect(yield* service.latestReport).toBeNull(); yield* fs.writeFileString(`${worktree}/${file}`, "local data\n"); @@ -690,7 +714,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("preserves tracked edits written after the final status check", () => runCleanupTest( Effect.gen(function* () { - const fixture = yield* cleanupFixture; + const fixture = yield* cleanupFixture(); fixture.setPolicy("tracked-changes"); fixture.editBeforeRemoval(); yield* fixture.fs.writeFileString(`${fixture.worktree}/notes.txt`, "untracked\n"); @@ -708,7 +732,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("streams the current report and subsequent runs", () => runCleanupTest( Effect.gen(function* () { - const { service } = yield* cleanupFixture; + const { service } = yield* cleanupFixture(); const reports = yield* service.reports.pipe( Stream.take(2), Stream.tap((report) => (report === null ? service.runNow : Effect.void)), @@ -723,7 +747,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("caps entries while preserving totals and prioritizing removals", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, worktree, setThreads } = yield* cleanupFixture; + const { service, fs, worktree, setThreads } = yield* cleanupFixture(); const threads = []; for (let i = 0; i < 205; i++) { const worktreePath = `${worktree}-${i}`; @@ -752,7 +776,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("keeps staged edits in tracked-only mode", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, worktree, setPolicy, command } = yield* cleanupFixture; + const { service, fs, worktree, setPolicy, command } = yield* cleanupFixture(); setPolicy("tracked-changes"); yield* fs.writeFileString(`${worktree}/tracked.txt`, "staged\n"); yield* command(worktree, ["add", "tracked.txt"]); @@ -769,7 +793,7 @@ describe("storage cleanup reports and local file policies", () => { () => runCleanupTest( Effect.gen(function* () { - const fixture = yield* cleanupFixture; + const fixture = yield* cleanupFixture(); const { service, fs, worktree, setThreads } = fixture; setThreads([shell({ branch: "feature", worktreePath: worktree, status: "running" })]); expect((yield* service.runNow).entries[0]?.reason).toContain("Thread is running"); @@ -790,7 +814,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("serializes concurrent requests and returns each run's report", () => runCleanupTest( Effect.gen(function* () { - const { service } = yield* cleanupFixture; + const { service } = yield* cleanupFixture(); const reports = yield* Effect.all([service.runNow, service.runNow], { concurrency: "unbounded", }); @@ -805,7 +829,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("aggregates expired artifacts and rotated logs while retaining current logs", () => runCleanupTest( Effect.gen(function* () { - const { service, fs, config, enableFiles, disable } = yield* cleanupFixture; + const { service, fs, config, enableFiles, disable } = yield* cleanupFixture(); disable(); enableFiles(); yield* fs.makeDirectory(config.browserArtifactsDir, { recursive: true }); @@ -848,7 +872,7 @@ describe("storage cleanup reports and local file policies", () => { it.live("reports git failures without aborting the remaining categories", () => runCleanupTest( Effect.gen(function* () { - const { service, worktree, command, enableFiles } = yield* cleanupFixture; + const { service, worktree, command, enableFiles } = yield* cleanupFixture(); enableFiles(); yield* command(worktree, ["worktree", "lock", worktree]); const report = yield* service.runNow; @@ -863,3 +887,202 @@ describe("storage cleanup reports and local file policies", () => { ), ); }); + +describe("settled worktree retention", () => { + it.effect.each([ + "immediate", + "settle-script", + "expired", + "boundary", + "wait", + "recent-update", + "active", + "dirty", + "project-off", + "project-custom", + "inactive-settling", + ] as const)("applies retention and safety checks (%s)", (scenario) => + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fixture = yield* cleanupFixture(); + const days = ["wait", "boundary", "expired", "recent-update"].includes(scenario) ? 8 : 0; + const rules = { + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: + scenario === "project-custom" || scenario === "inactive-settling" ? null : days, + // Another rule must not bypass the settle-script grace either. + worktreeAfterDays: scenario === "inactive-settling" ? 1 : null, + }; + fixture.setSettings({ + storageCleanup: rules, + projectSettingsOverrides: { + [ProjectId.make("project-1")]: + scenario === "project-off" + ? { worktreeCleanup: { mode: "off" } } + : scenario === "project-custom" + ? { + worktreeCleanup: { + mode: "custom", + rules: { ...rules, worktreeSettledAfterDays: 0 }, + }, + } + : {}, + }, + }); + const thread = shell({ + branch: "feature", + worktreePath: fixture.worktree, + settledAt: + scenario === "active" + ? null + : at( + scenario === "expired" || + scenario === "recent-update" || + scenario === "inactive-settling" + ? -20 * DAY_MS + : scenario === "boundary" + ? -8 * DAY_MS + : scenario === "wait" + ? -8 * DAY_MS + 1 + : scenario === "settle-script" + ? 0 + : -60_000, + ), + updatedAt: at( + scenario === "recent-update" || + scenario === "settle-script" || + scenario === "inactive-settling" + ? 0 + : -10 * DAY_MS, + ), + }); + fixture.setThreads([thread]); + if (scenario === "dirty") + yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "edit\n"); + const report = yield* fixture.service.runNow; + const removed = ["immediate", "expired", "boundary", "project-custom"].includes(scenario); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(!removed); + expect(report.counts.removed).toBe(removed ? 1 : 0); + if (scenario !== "project-off") { + const reason = + scenario === "active" + ? "Not settled" + : scenario === "wait" + ? "Settled for 7 of 8 days" + : ["settle-script", "recent-update", "inactive-settling"].includes(scenario) + ? "Settled moments ago" + : scenario === "dirty" + ? "Has uncommitted changes (1 file)" + : `Settled for ${scenario === "expired" ? 20 : scenario === "boundary" ? 8 : 0} days`; + expect(report.entries[0]).toMatchObject({ outcome: removed ? "removed" : "kept", reason }); + } + expect(thread.branch).toBe("feature"); + expect( + (yield* fixture.command(fixture.repo, ["rev-parse", "--verify", "refs/heads/feature"])) + .exitCode, + ).toBe(0); + }).pipe(Effect.provide(cleanupTestLayer), Effect.scoped), + ); +}); + +describe("settled worktree rechecks", () => { + it.live.each([{ settledAt: null }, { settledAt: at(DAY_MS) }])( + "keeps a checkout changed during measurement (%j)", + (change) => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* pausedMeasurementFixture(); + const thread = shell({ + branch: "feature", + worktreePath: fixture.worktree, + settledAt: at(0), + }); + fixture.setSettings({ + storageCleanup: { + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 0, + }, + }); + fixture.setThreads([thread]); + const run = yield* fixture.service.runNow.pipe(Effect.forkChild); + yield* Deferred.await(fixture.measuring); + fixture.setThreads([{ ...thread, ...change }]); + yield* Deferred.succeed(fixture.resume, undefined); + const report = yield* Fiber.join(run); + expect(report.entries[0]?.reason).toBe( + "Thread activity or shared worktree changed since check", + ); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }), + ), + ); +}); + +it.live("keeps saved usage data when removing a settled checkout", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture(); + fixture.setSettings({ + storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeSettledAfterDays: 0 }, + }); + fixture.setThreads([ + shell({ branch: "feature", worktreePath: fixture.worktree, settledAt: at(0) }), + ]); + yield* fixture.fs.makeDirectory(fixture.config.stateDir, { recursive: true }); + const cachePath = `${fixture.config.stateDir}/${SCAN_CACHE_FILE_NAME}`; + const savedUsage = JSON.stringify({ tokens: 12345, cost: 1.25 }); + yield* fixture.fs.writeFileString(cachePath, savedUsage); + expect((yield* fixture.service.runNow).counts.removed).toBe(1); + expect(yield* fixture.fs.readFileString(cachePath)).toBe(savedUsage); + }), + ), +); + +it.live.each(["thread.settled", "stopped", "ready"] as const)( + "leaves settled cleanup to the regular sweeps after %s", + (trigger) => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* pausedMeasurementFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 0, + }); + fixture.setSettings({ + storageCleanup: { + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeSettledAfterDays: 0, + }, + }); + const thread = shell({ + branch: "feature", + worktreePath: fixture.worktree, + settledAt: at(0), + }); + fixture.setThreads([thread]); + const handled = yield* Deferred.make(); + yield* fixture.activate( + Stream.fromEffect(Deferred.await(fixture.measuring)).pipe( + Stream.flatMap(() => Stream.range(0, 19)), + Stream.map((index): OrchestrationV2DomainEvent => + trigger === "thread.settled" + ? { + id: EventId.make(`settled-${index}`), + type: "thread.settled", + threadId: thread.id, + occurredAt: at(0), + payload: { ...thread, lastVisitedAt: null }, + } + : sessionUpdated(index, trigger), + ), + Stream.concat( + Stream.fromEffect(Deferred.succeed(handled, undefined)).pipe(Stream.drain), + ), + ), + ); + yield* Deferred.await(handled); + yield* Deferred.succeed(fixture.resume, undefined); + yield* fixture.service.drain; + expect(fixture.snapshotReads()).toBe(1); + }), + ), +); diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 20f1ed9f6ed9..627bc410c52b 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -38,6 +38,7 @@ import * as GitManager from "./git/GitManager.ts"; import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; +import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts"; import { forkParked } from "./serverActivation.ts"; import * as Settings from "./serverSettings.ts"; @@ -56,6 +57,9 @@ const decodeCleanupSession = Schema.decodeUnknownEffect( ); const DAY_MS = 86_400_000; +// After a settle, the project's settle script needs time to open its +// terminal, which then protects the worktree. +const SETTLE_SCRIPT_GRACE_MS = 60_000; const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1); const REPORT_ENTRY_LIMIT = 200; @@ -69,6 +73,7 @@ function cleanupFailureReason(error: { readonly message: string }) { const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) => rules.worktreeAfterDays !== null || + rules.worktreeSettledAfterDays !== null || rules.worktreeOnMerge || rules.worktreeOnDelete || rules.worktreeUnchanged; @@ -172,6 +177,7 @@ const make = Effect.gen(function* () { const projectStore = yield* ProjectStore.ProjectStoreV2; const engine = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; + const providerSessions = yield* ProviderSessionManager.ProviderSessionManagerV2; const sql = yield* SqlClient.SqlClient; const git = yield* GitVcsDriver.GitVcsDriver; const gitManager = yield* GitManager.GitManager; @@ -483,15 +489,35 @@ const make = Effect.gen(function* () { return keep("repository or branch changed"); const changes = yield* localChangesReason(worktreePath, settings); if (changes !== null) return keep(changes); + // The project's settle script starts in the worktree right after a + // settle. Settling stamps updatedAt now, even when automatic + // settlement backdates settledAt to the thread's last activity. + if ( + !deleted && + thread.settledAt !== null && + now - DateTime.toEpochMillis(thread.updatedAt) < SETTLE_SCRIPT_GRACE_MS + ) + return keep("settled moments ago"); const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }); const old = !deleted && settings.worktreeAfterDays !== null && storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS; - let eligible = deleted || old; + const settledFor = + deleted || thread.settledAt === null + ? null + : now - DateTime.toEpochMillis(thread.settledAt); + const settledDays = settledFor === null ? null : Math.floor(settledFor / DAY_MS); + const settled = + settledFor !== null && + settings.worktreeSettledAfterDays !== null && + settledFor >= settings.worktreeSettledAfterDays * DAY_MS; + let eligible = deleted || old || settled; let removalReason = deleted ? "thread was deleted" - : `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days`; + : old + ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} days` + : `settled for ${settledDays} days`; if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) { const repositoryCwd = path.resolve(project.workspaceRoot); const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd); @@ -539,9 +565,13 @@ const make = Effect.gen(function* () { return keep( !deleted && settings.worktreeAfterDays !== null ? `inactive for ${Math.floor((now - storageCleanupActivityAt(thread)) / DAY_MS)} of ${settings.worktreeAfterDays} days` - : settings.worktreeOnMerge - ? "not merged" - : "has commits beyond the default branch", + : settings.worktreeSettledAfterDays !== null + ? settledFor === null + ? "not settled" + : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days` + : settings.worktreeOnMerge + ? "not merged" + : "has commits beyond the default branch", ); // Threads, queued deletion work and provider sessions as they are now, so a // queued turn, resumed session or new thread sharing this path cancels @@ -577,7 +607,8 @@ const make = Effect.gen(function* () { if ( latestShell === null || !storageCleanupThreadIdle(latestShell, now) || - storageCleanupActivityAt(latestShell) !== storageCleanupActivityAt(thread) + storageCleanupActivityAt(latestShell) !== storageCleanupActivityAt(thread) || + !Equal.equals(latestShell.settledAt, thread.settledAt) ) return "thread activity or shared worktree changed since check"; } @@ -589,13 +620,16 @@ const make = Effect.gen(function* () { const sessions = yield* Effect.forEach(sessionRows, (row) => decodeCleanupSession(row.payload_json), ); - if ( - sessions.some((session) => { - const cwd = path.resolve(session.cwd); - return cwd === worktreePath || inside(worktreePath, cwd); - }) - ) - return "provider session is still open"; + // A stored session can stay ready after its runtime was released, + // for example once every thread detached; only a live one holds it. + for (const session of sessions) { + const cwd = path.resolve(session.cwd); + if ( + (cwd === worktreePath || inside(worktreePath, cwd)) && + (yield* providerSessions.isLive(session.id)) + ) + return "provider session is still open"; + } return null; }); // Most cancelled removals are caught here, before the worktree is walked. diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index d655203af46d..b34e8c31935a 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -37,7 +37,10 @@ import { resolveClaudeModelSlug, scopeClaudeModelCatalog, } from "../provider/ClaudeModelCatalog.ts"; -import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts"; +import { + hasClaudeManagedMcpConfig, + makeClaudeEnvironment, +} from "../provider/Drivers/ClaudeHome.ts"; const CLAUDE_TIMEOUT_MS = 180_000; /** The tools an investigation can see. `--tools` takes bare names; patterns go in the allow list. */ @@ -209,6 +212,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ), ) : cwd; + const managedMcpConfig = yield* hasClaudeManagedMcpConfig(); const spawnCommand = yield* resolveSpawnCommand( claudeSettings.binaryPath || "claude", [ @@ -236,7 +240,9 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ] : ["--tools", ""]), "--disable-slash-commands", - "--strict-mcp-config", + // Claude refuses this flag next to a managed-mcp.json, which already keeps the + // user's own MCP servers out. + ...(managedMcpConfig ? [] : ["--strict-mcp-config"]), "--permission-mode", "dontAsk", ], diff --git a/apps/web/src/browser/browserLinkTarget.test.ts b/apps/web/src/browser/browserLinkTarget.test.ts index a60362c43bd5..c40893e6acf5 100644 --- a/apps/web/src/browser/browserLinkTarget.test.ts +++ b/apps/web/src/browser/browserLinkTarget.test.ts @@ -67,6 +67,14 @@ describe("resolveLinkTarget", () => { canOpenInApp: true, }), ).toBe("system"); + expect( + resolveLinkTarget({ + url: "https://example.com/", + event: { metaKey: false, ctrlKey: false, button: 1 }, + preference: "app", + canOpenInApp: true, + }), + ).toBe("system"); }); it("leaves non-web schemes to the shell", () => { diff --git a/apps/web/src/browser/browserLinkTarget.ts b/apps/web/src/browser/browserLinkTarget.ts index ce79e6ac6a6a..20fce7057c17 100644 --- a/apps/web/src/browser/browserLinkTarget.ts +++ b/apps/web/src/browser/browserLinkTarget.ts @@ -15,8 +15,12 @@ import { isPreviewAvailableFor } from "./previewRuntime"; export interface ResolveLinkTargetInput { readonly url: string; - /** Cmd/Ctrl-click always goes to the system browser, whatever the default. */ - readonly event: { readonly metaKey: boolean; readonly ctrlKey: boolean }; + /** Cmd/Ctrl-click and middle-click always go to the system browser, whatever the default. */ + readonly event: { + readonly metaKey: boolean; + readonly ctrlKey: boolean; + readonly button?: number | undefined; + }; readonly preference: BrowserLinkTarget; /** Whether this client has an in-app browser and a thread to open it beside. */ readonly canOpenInApp: boolean; @@ -30,7 +34,7 @@ export interface ResolveLinkTargetInput { * already treat it. */ export function resolveLinkTarget(input: ResolveLinkTargetInput): BrowserLinkTarget { - if (input.event.metaKey || input.event.ctrlKey) return "system"; + if (input.event.metaKey || input.event.ctrlKey || input.event.button === 1) return "system"; if (input.preference !== "app") return "system"; if (!input.canOpenInApp) return "system"; if (!isWebUrl(input.url)) return "system"; diff --git a/apps/web/src/browser/useOpenLink.ts b/apps/web/src/browser/useOpenLink.ts index d6d33efc6996..22e6a8cd6c0c 100644 --- a/apps/web/src/browser/useOpenLink.ts +++ b/apps/web/src/browser/useOpenLink.ts @@ -34,7 +34,11 @@ const NO_MODIFIER = { metaKey: false, ctrlKey: false } as const; export function useOpenLink(threadRef: ScopedThreadRef | null | undefined): ( url: string, options?: { - readonly event?: { readonly metaKey: boolean; readonly ctrlKey: boolean }; + readonly event?: { + readonly metaKey: boolean; + readonly ctrlKey: boolean; + readonly button?: number | undefined; + }; /** Thread to open beside when it is not the hook's own, e.g. a sidebar row's. */ readonly threadRef?: ScopedThreadRef | undefined; }, diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 821d1643ede0..dd0343ca990e 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -849,7 +849,7 @@ function MarkdownCodeBlock({ theme, onRunShellCommand, isStreaming, - leadingActions, + viewToggle, canWrap = true, diagram = false, children, @@ -860,9 +860,10 @@ function MarkdownCodeBlock({ theme: "light" | "dark"; onRunShellCommand?: ((command: string) => void) | undefined; isStreaming: boolean; - leadingActions?: ReactNode; + /** Switches between source and rendered content; sits left of copy in both views. */ + viewToggle?: ReactNode; canWrap?: boolean; - /** Renders content instead of code, with actions below it like tables. */ + /** Renders content frameless, with the code header's actions above it. */ diagram?: boolean; children: ReactNode; }) { @@ -942,12 +943,14 @@ function MarkdownCodeBlock({ if (diagram) { return ( -
- {children} -
- {leadingActions} + // The transparent border and header padding match the code frame, so the + // actions stay in place when switching views. +
+
+ {viewToggle} {copyButton}
+ {children}
); } @@ -962,7 +965,6 @@ function MarkdownCodeBlock({ headerProps={THREAD_FIND_IGNORE_PROPS} actions={ - {leadingActions} {canWrap ? ( Run in terminal ) : null} + {viewToggle} {copyButton} } @@ -1043,7 +1046,7 @@ function MarkdownMermaidCodeBlock({ isStreaming={isStreaming} canWrap={!showDiagram} diagram={showDiagram} - leadingActions={ + viewToggle={ isStreaming ? null : ( (); +// The factories below build functions ChatView calls during render, or hands +// to ChatComposer, which can call them after an await. They live outside the +// component so each closure keeps only its inputs, not a whole render scope +// (see useStableCallback), while still acting on the render that made them. + +/** Records a thread error in local state, keyed by the route the making render saw. */ +function makeThreadErrorSetter(input: { + readonly routeThreadRef: ScopedThreadRef; + readonly routeThreadKey: string; + readonly draftId: DraftId | null; + readonly serverThreadRef: ScopedThreadRef | null; + readonly setLocalServerErrorsByThreadKey: ( + update: SetStateAction>, + ) => void; + readonly setLocalDraftErrorsByDraftId: ( + update: SetStateAction>, + ) => void; +}) { + return (targetThreadId: ThreadId | null, error: string | null) => { + if (!targetThreadId) return; + const nextError = sanitizeThreadErrorMessage(error); + const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() }; + const { routeThreadRef, serverThreadRef } = input; + if ( + serverThreadRef && + targetThreadId === routeThreadRef.threadId && + serverThreadRef.environmentId === routeThreadRef.environmentId && + serverThreadRef.threadId === targetThreadId + ) { + input.setLocalServerErrorsByThreadKey((existing) => { + if ((existing[input.routeThreadKey]?.message ?? null) === nextError) { + return existing; + } + return { ...existing, [input.routeThreadKey]: nextEntry }; + }); + return; + } + const localDraftErrorKey = input.draftId ?? targetThreadId; + input.setLocalDraftErrorsByDraftId((existing) => { + if ((existing[localDraftErrorKey]?.message ?? null) === nextError) { + return existing; + } + return { ...existing, [localDraftErrorKey]: nextEntry }; + }); + }; +} + +/** Writes the custom answer for a question of the pending user input the making render saw. */ +function makePendingCustomAnswerSetter(input: { + readonly activePendingUserInput: PendingUserInput | null; + readonly activePendingRequestKey: string; + readonly promptRef: { current: string }; + readonly setPendingUserInputAnswersByRequestId: ( + update: SetStateAction>>, + ) => void; +}) { + return (questionId: string, value: string) => { + const { activePendingUserInput, activePendingRequestKey } = input; + if (!activePendingUserInput) { + return; + } + const question = activePendingUserInput.questions.find((entry) => entry.id === questionId); + if (!question || question.allowCustomAnswer === false) { + return; + } + input.promptRef.current = value; + input.setPendingUserInputAnswersByRequestId((existing) => ({ + ...existing, + [activePendingRequestKey]: { + ...existing[activePendingRequestKey], + [questionId]: setPendingUserInputCustomAnswer( + existing[activePendingRequestKey]?.[questionId], + value, + question, + ), + }, + })); + // The editor owns this selection. Resetting it before the answer renders + // can re-enter Lexical with offsets from the previous skill token. + }; +} + +/** Draft id for editing a queued run of `threadRef`. */ +function makeQueuedEditDraftTarget(threadRef: ScopedThreadRef) { + return (runId: RunId) => DraftId.make(`queued-edit:${scopedThreadKey(threadRef)}:${runId}`); +} + +/** Why the model picker should disable a model, or null when it can be chosen. */ +function makeModelDisabledReason( + context: Omit< + Parameters[0], + "nextModelSelection" + > | null, +) { + return (instanceId: ProviderInstanceId, model: string): string | null => { + if (!context) return null; + const reason = getStartedThreadModelChangeBlockReason({ + ...context, + nextModelSelection: { instanceId, model }, + }); + return reason ? `${reason.description} Start a new thread to use this model.` : null; + }; +} + export default function ChatView(props: ChatViewProps) { const { environmentId, @@ -1591,10 +1699,8 @@ export default function ChatView(props: ChatViewProps) { } = props; const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope); - const hasTerminalWriteAccess = useCallback( - () => readEnvironmentScope(environmentId, AuthTerminalOperateScope), - [environmentId], - ); + const hasTerminalWriteAccess = () => + readEnvironmentScope(environmentId, AuthTerminalOperateScope); const canReadTerminal = useEnvironmentScope(environmentId, AuthTerminalReadScope); const draftId = routeKind === "draft" ? props.draftId : null; const handleNewThread = useNewThreadHandler(); @@ -1696,8 +1802,8 @@ export default function ChatView(props: ChatViewProps) { readonly existingAttachments: ReadonlyArray; readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined; } | null>(null); - const queuedEditDraftTargetFor = useCallback( - (runId: RunId) => DraftId.make(`queued-edit:${scopedThreadKey(routeThreadRef)}:${runId}`), + const queuedEditDraftTargetFor = useMemo( + () => makeQueuedEditDraftTarget(routeThreadRef), [routeThreadRef], ); const baseComposerDraftTarget: ScopedThreadRef | DraftId = @@ -1861,21 +1967,21 @@ export default function ChatView(props: ChatViewProps) { const [restingComposerControlsHost, setRestingComposerControlsHost] = useState(null); const [restingComposerControlsVisible, setRestingComposerControlsVisible] = useState(false); - const citeAssistantText = useCallback( - (citation: AssistantCitation, sourceAnchor: AssistantCitationSourceAnchor) => { - const inserted = composerRef.current?.citeAssistantText(citation, sourceAnchor) ?? false; - if (!inserted) { - toastManager.add({ - type: "warning", - title: "The composer is not ready", - description: - "Try citing the selection after the connection or pending input is resolved.", - }); - } - return inserted; - }, - [composerRef], - ); + const citeAssistantText = ( + citation: AssistantCitation, + sourceAnchor: AssistantCitationSourceAnchor, + ) => { + const inserted = composerRef.current?.citeAssistantText(citation, sourceAnchor) ?? false; + if (!inserted) { + toastManager.add({ + type: "warning", + title: "The composer is not ready", + description: "Try citing the selection after the connection or pending input is resolved.", + }); + } + return inserted; + }; + const citeAssistantTextStable = useStableCallback(citeAssistantText); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false); const [expandedImage, setExpandedImage] = useState(null); @@ -1976,10 +2082,8 @@ export default function ChatView(props: ChatViewProps) { LastInvokedScriptByProjectSchema, ); const legendListRef = useRef(null); - const getTimelineScrollableNode = useCallback( - () => legendListRef.current?.getScrollableNode() ?? null, - [], - ); + const getTimelineScrollableNode = () => legendListRef.current?.getScrollableNode() ?? null; + const getTimelineScrollableNodeStable = useStableCallback(getTimelineScrollableNode); const [composerOverlayElement, setComposerOverlayElement] = useState(null); // Space the timeline keeps clear above its end. Tracks the overlay while the // composer is expanded and holds that height while it rests, so the resting @@ -1991,10 +2095,9 @@ export default function ChatView(props: ChatViewProps) { const composerMountedRef = useRef(true); const [scrollToEndClearance, setScrollToEndClearance] = useState(0); const isAtEndRef = useRef(true); - const isTimelineAtLogicalEnd = useCallback( - () => resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current, - [], - ); + const isTimelineAtLogicalEnd = () => + resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current; + const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd); // Whether the timeline's rows extend past the viewport above the composer. // The composer only rests when there is reading space to give back. const [timelineOverflows, setTimelineOverflows] = useState(false); @@ -2009,15 +2112,15 @@ export default function ChatView(props: ChatViewProps) { const isResuming = resumingThreadKeys.has(routeThreadKey); const composerSendGenerationRef = useRef(0); const multipleModelSelections = fanoutState.selections; - const setMultipleModelSelections = useCallback( - (selections: SetStateAction | null>) => { - appAtomRegistry.update(fanoutStateAtom, (current) => ({ - ...current, - selections: typeof selections === "function" ? selections(current.selections) : selections, - })); - }, - [fanoutStateAtom], - ); + const setMultipleModelSelections = ( + selections: SetStateAction | null>, + ) => { + appAtomRegistry.update(fanoutStateAtom, (current) => ({ + ...current, + selections: typeof selections === "function" ? selections(current.selections) : selections, + })); + }; + const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections); const multipleModelSelectionsRef = useRef(multipleModelSelections); multipleModelSelectionsRef.current = multipleModelSelections; const uncertainMultipleSubmissionsRef = fanoutState.uncertainSubmissions; @@ -2356,16 +2459,13 @@ export default function ChatView(props: ChatViewProps) { [activeKnownTerminalIds, panelTerminalIds], ); const canReuseTerminal = activeThreadKnownSessionsRaw !== null; - const allocateTerminalId = useCallback( - () => - nextTerminalId( - allocatableActiveTerminalIds, - canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope) - ? undefined - : randomUUID(), - ), - [allocatableActiveTerminalIds, canReuseTerminal, environmentId], - ); + const allocateTerminalId = () => + nextTerminalId( + allocatableActiveTerminalIds, + canReuseTerminal && readEnvironmentScope(environmentId, AuthTerminalReadScope) + ? undefined + : randomUUID(), + ); const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable; const rightPanelOpen = rightPanelState.isOpen; const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } = @@ -2516,25 +2616,23 @@ export default function ChatView(props: ChatViewProps) { const removeClonedProject = useRemoveClonedProject(); // The banner mirrors the server's clone state, so a request that never got // there needs its own feedback. - const runProjectCloneAction = useCallback( - async ( - title: string, - action: () => Promise>, - ): Promise => { - const result = await action(); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title, - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - } - }, - [], - ); + const runProjectCloneAction = async ( + title: string, + action: () => Promise>, + ): Promise => { + const result = await action(); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + }; + const runProjectCloneActionStable = useStableCallback(runProjectCloneAction); const projectCloneSendBlockReason = activeProjectClone === null ? null @@ -2562,7 +2660,7 @@ export default function ChatView(props: ChatViewProps) { size="xs" variant="ghost" onClick={() => - void runProjectCloneAction("Failed to cancel clone", () => + void runProjectCloneActionStable("Failed to cancel clone", () => cancelProjectClone({ environmentId, input: { projectId } }), ) } @@ -2592,7 +2690,7 @@ export default function ChatView(props: ChatViewProps) { size="xs" variant="ghost" onClick={() => - void runProjectCloneAction("Failed to retry clone", () => + void runProjectCloneActionStable("Failed to retry clone", () => retryProjectClone({ environmentId, input: { projectId } }), ) } @@ -2608,24 +2706,26 @@ export default function ChatView(props: ChatViewProps) { cancelProjectClone, removeClonedProject, retryProjectClone, - runProjectCloneAction, + runProjectCloneActionStable, ]); const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection; - const handleNewThreadInActiveProject = useCallback(() => { + const handleNewThreadInActiveProject = () => { startNewThreadForProject(activeProjectRef, handleNewThread); - }, [activeProjectRef, handleNewThread]); + }; + const handleNewThreadInActiveProjectStable = useStableCallback(handleNewThreadInActiveProject); const projectGroupingSettings = selectProjectGroupingSettings(settings); const activeDraftLogicalProjectKey = !isServerThread && activeProject ? deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings) : undefined; - const handleOpenDraftProjectSettings = useCallback(() => { + const handleOpenDraftProjectSettings = () => { if (!activeDraftLogicalProjectKey) return; void navigate({ to: "/projects/$projectKey", params: { projectKey: activeDraftLogicalProjectKey }, }); - }, [activeDraftLogicalProjectKey, navigate]); + }; + const handleOpenDraftProjectSettingsStable = useStableCallback(handleOpenDraftProjectSettings); const activeEnvironmentShell = useEnvironmentQuery( activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null, ); @@ -2639,24 +2739,22 @@ export default function ChatView(props: ChatViewProps) { const pendingFileSurfaceIds = activeProjectKey ? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS) : EMPTY_PENDING_FILE_SURFACE_IDS; - const handleFilePendingChange = useCallback( - (relativePath: string, pending: boolean) => { - if (!activeProjectKey) return; - setPendingFileSurfaceIdsByProject((currentByProject) => { - const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS; - const surfaceId = `file:${relativePath}`; - if (current.has(surfaceId) === pending) return currentByProject; - const next = new Set(current); - if (pending) next.add(surfaceId); - else next.delete(surfaceId); - const nextByProject = new Map(currentByProject); - if (next.size === 0) nextByProject.delete(activeProjectKey); - else nextByProject.set(activeProjectKey, next); - return nextByProject; - }); - }, - [activeProjectKey], - ); + const handleFilePendingChange = (relativePath: string, pending: boolean) => { + if (!activeProjectKey) return; + setPendingFileSurfaceIdsByProject((currentByProject) => { + const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS; + const surfaceId = `file:${relativePath}`; + if (current.has(surfaceId) === pending) return currentByProject; + const next = new Set(current); + if (pending) next.add(surfaceId); + else next.delete(surfaceId); + const nextByProject = new Map(currentByProject); + if (next.size === 0) nextByProject.delete(activeProjectKey); + else nextByProject.set(activeProjectKey, next); + return nextByProject; + }); + }; + const handleFilePendingChangeStable = useStableCallback(handleFilePendingChange); const configuredPreviewUrls = useMemo( () => getConfiguredPreviewUrls(activeProjectScripts), [activeProjectScripts], @@ -2715,21 +2813,21 @@ export default function ChatView(props: ChatViewProps) { connection: activeEnvironment.connection, }; }, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]); - const handleReconnectActiveEnvironment = useCallback( - async (environmentId: EnvironmentId) => { - const result = await retryEnvironment(environmentId); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not reconnect environment", - description: error instanceof Error ? error.message : "Failed to reconnect.", - }), - ); - } - }, - [retryEnvironment], + const handleReconnectActiveEnvironment = async (environmentId: EnvironmentId) => { + const result = await retryEnvironment(environmentId); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not reconnect environment", + description: error instanceof Error ? error.message : "Failed to reconnect.", + }), + ); + } + }; + const handleReconnectActiveEnvironmentStable = useStableCallback( + handleReconnectActiveEnvironment, ); const disconnectDelayElapsed = useEnvironmentDisconnectDelay( activeEnvironmentUnavailable ? activeEnvironment.environmentId : null, @@ -2741,27 +2839,27 @@ export default function ChatView(props: ChatViewProps) { !Cloud.isCloudBoxTarget(activeEnvironment.entry.target) && !isDesktopLocalConnectionTarget(activeEnvironment.entry.target); const [disconnectingEnvironment, setDisconnectingEnvironment] = useState(false); - const handleDisconnectActiveEnvironment = useCallback( - async (environmentId: EnvironmentId) => { - setDisconnectingEnvironment(true); - const result = await setEnvironmentEnabled({ environmentId, enabled: false }); - setDisconnectingEnvironment(false); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not disconnect server", - description: error instanceof Error ? error.message : "Failed to disconnect.", - }), - ); - } - return; + const handleDisconnectActiveEnvironment = async (environmentId: EnvironmentId) => { + setDisconnectingEnvironment(true); + const result = await setEnvironmentEnabled({ environmentId, enabled: false }); + setDisconnectingEnvironment(false); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not disconnect server", + description: error instanceof Error ? error.message : "Failed to disconnect.", + }), + ); } - void navigate({ to: "/", replace: true }); - }, - [navigate, setEnvironmentEnabled], + return; + } + void navigate({ to: "/", replace: true }); + }; + const handleDisconnectActiveEnvironmentStable = useStableCallback( + handleDisconnectActiveEnvironment, ); const { scratchWorkspaceRootFor, openScratchProject } = useScratchProject(); const activeProjectIsScratch = @@ -2850,112 +2948,96 @@ export default function ChatView(props: ChatViewProps) { activeEnvironment: activeEnvironmentOption, canPickEnvironment: hasMultipleEnvironments, }); - const openPullRequestDialog = useCallback( - (reference?: string) => { - if (!canCheckoutPullRequestIntoThread) { - return; - } - setPullRequestDialogState({ - initialReference: reference ?? null, - key: Date.now(), - }); - }, - [canCheckoutPullRequestIntoThread], - ); + const openPullRequestDialog = (reference?: string) => { + if (!canCheckoutPullRequestIntoThread) { + return; + } + setPullRequestDialogState({ + initialReference: reference ?? null, + key: Date.now(), + }); + }; + const openPullRequestDialogStable = useStableCallback(openPullRequestDialog); - const closePullRequestDialog = useCallback(() => { + const closePullRequestDialog = () => { setPullRequestDialogState(null); - }, []); - - const openOrReuseProjectDraftThread = useCallback( - async (input: { branch: string; worktreePath: string | null; envMode: DraftThreadEnvMode }) => { - if (!activeProject) { - throw new Error("No active project is available for this pull request."); - } - const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id); - const logicalProjectKey = deriveLogicalProjectKeyFromSettings( - activeProject, - projectGroupingSettings, - ); - const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if (storedDraftSession) { - setDraftThreadContext(storedDraftSession.draftId, input); - setLogicalProjectDraftThreadId( - logicalProjectKey, - activeProjectRef, - storedDraftSession.draftId, - { - threadId: storedDraftSession.threadId, - ...input, - }, - ); - if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) { - await navigate({ - to: "/draft/$draftId", - params: buildDraftThreadRouteParams(storedDraftSession.draftId), - }); - } - return storedDraftSession.threadId; - } + }; - const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null; - if ( - !isServerThread && - activeDraftSession?.logicalProjectKey === logicalProjectKey && - draftId - ) { - setDraftThreadContext(draftId, input); - setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, { - threadId: activeDraftSession.threadId, - createdAt: activeDraftSession.createdAt, - runtimeMode: activeDraftSession.runtimeMode, - interactionMode: activeDraftSession.interactionMode, + const openOrReuseProjectDraftThread = async (input: { + branch: string; + worktreePath: string | null; + envMode: DraftThreadEnvMode; + }) => { + if (!activeProject) { + throw new Error("No active project is available for this pull request."); + } + const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id); + const logicalProjectKey = deriveLogicalProjectKeyFromSettings( + activeProject, + projectGroupingSettings, + ); + const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey); + if (storedDraftSession) { + setDraftThreadContext(storedDraftSession.draftId, input); + setLogicalProjectDraftThreadId( + logicalProjectKey, + activeProjectRef, + storedDraftSession.draftId, + { + threadId: storedDraftSession.threadId, ...input, + }, + ); + if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) { + await navigate({ + to: "/draft/$draftId", + params: buildDraftThreadRouteParams(storedDraftSession.draftId), }); - return activeDraftSession.threadId; } + return storedDraftSession.threadId; + } - const nextDraftId = newDraftId(); - const nextThreadId = newThreadId(); - setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, { - threadId: nextThreadId, - createdAt: new Date().toISOString(), - runtimeMode: resolveProjectSettings(settings, activeProject.id, activeProject).settings - .defaultRuntimeMode, - interactionMode: DEFAULT_INTERACTION_MODE, + const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null; + if (!isServerThread && activeDraftSession?.logicalProjectKey === logicalProjectKey && draftId) { + setDraftThreadContext(draftId, input); + setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, { + threadId: activeDraftSession.threadId, + createdAt: activeDraftSession.createdAt, + runtimeMode: activeDraftSession.runtimeMode, + interactionMode: activeDraftSession.interactionMode, ...input, }); - await navigate({ - to: "/draft/$draftId", - params: buildDraftThreadRouteParams(nextDraftId), - }); - return nextThreadId; - }, - [ - activeProject, - draftId, - getDraftSession, - getDraftSessionByLogicalProjectKey, - isServerThread, - navigate, - projectGroupingSettings, - routeKind, - settings, - setDraftThreadContext, - setLogicalProjectDraftThreadId, - ], - ); + return activeDraftSession.threadId; + } - const handlePreparedPullRequestThread = useCallback( - async (input: { branch: string; worktreePath: string | null }) => { - await openOrReuseProjectDraftThread({ - branch: input.branch, - worktreePath: input.worktreePath, - envMode: input.worktreePath ? "worktree" : "local", - }); - }, - [openOrReuseProjectDraftThread], - ); + const nextDraftId = newDraftId(); + const nextThreadId = newThreadId(); + setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, { + threadId: nextThreadId, + createdAt: new Date().toISOString(), + runtimeMode: resolveProjectSettings(settings, activeProject.id, activeProject).settings + .defaultRuntimeMode, + interactionMode: DEFAULT_INTERACTION_MODE, + ...input, + }); + await navigate({ + to: "/draft/$draftId", + params: buildDraftThreadRouteParams(nextDraftId), + }); + return nextThreadId; + }; + + const handlePreparedPullRequestThread = async (input: { + branch: string; + worktreePath: string | null; + }) => { + await openOrReuseProjectDraftThread({ + branch: input.branch, + worktreePath: input.worktreePath, + envMode: input.worktreePath ? "worktree" : "local", + }); + }; + const handlePreparedPullRequestThreadStable = useStableCallback(handlePreparedPullRequestThread); useEffect(() => { if (!serverThread?.id) return; @@ -3122,7 +3204,9 @@ export default function ChatView(props: ChatViewProps) { disabled={disconnectingEnvironment} title="Hide this server's threads. Switch it on again in Connections." onClick={() => - void handleDisconnectActiveEnvironment(activeEnvironmentUnavailableState.environmentId) + void handleDisconnectActiveEnvironmentStable( + activeEnvironmentUnavailableState.environmentId, + ) } > Disconnect server @@ -3150,7 +3234,7 @@ export default function ChatView(props: ChatViewProps) { size="xs" variant="ghost" onClick={() => - void handleReconnectActiveEnvironment( + void handleReconnectActiveEnvironmentStable( activeEnvironmentUnavailableState.environmentId, ) } @@ -3255,10 +3339,10 @@ export default function ChatView(props: ChatViewProps) { autoBalanceUpdateBanner, activeEnvironmentUnavailableState, activeCloudMachine, - handleReconnectActiveEnvironment, + handleReconnectActiveEnvironmentStable, canDisconnectActiveEnvironment, disconnectingEnvironment, - handleDisconnectActiveEnvironment, + handleDisconnectActiveEnvironmentStable, setDismissedVersionMismatchKey, showVersionMismatchBanner, reconnectWarningGraceElapsed, @@ -3576,7 +3660,7 @@ export default function ChatView(props: ChatViewProps) { activeProviderStatus !== null && hasProviderUsageLimits(activeProviderStatus.driver, providerStatuses, usageLimitSources); // Answered locally from the last Limits snapshot; the agent never sees it. - const openUsageLimits = useCallback(() => { + const openUsageLimits = () => { const now = Date.now(); const report = activeProviderInstanceId !== null && usageLimitsKey !== null @@ -3594,21 +3678,13 @@ export default function ChatView(props: ChatViewProps) { setUsageLimitsPanel(null); toastManager.add({ type: "info", title: "Usage limits are unavailable for this provider" }); return false; - }, [ - activeProviderInstanceId, - providerStatuses, - routeThreadKey, - usageLimitSources, - usageLimitsKey, - ]); + }; + const openUsageLimitsStable = useStableCallback(openUsageLimits); // Responses can resolve after navigating away; only the originating thread's panel clears. - const clearUsageLimitsFor = useCallback( - (threadKey: string) => - setUsageLimitsPanel((current) => - current !== null && current.threadKey === threadKey ? null : current, - ), - [], - ); + const clearUsageLimitsFor = (threadKey: string) => + setUsageLimitsPanel((current) => + current !== null && current.threadKey === threadKey ? null : current, + ); const { beginLocalDispatch, resetLocalDispatch, @@ -3739,27 +3815,28 @@ export default function ChatView(props: ChatViewProps) { useEffect(() => { attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId; }, [attachmentPreviewHandoffByMessageId]); - const clearAttachmentPreviewHandoff = useCallback( - (messageId: MessageId, previewUrls?: ReadonlyArray) => { - delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; - const currentPreviewUrls = - previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; - setAttachmentPreviewHandoffByMessageId((existing) => { - if (!(messageId in existing)) { - return existing; - } - const next = { ...existing }; - delete next[messageId]; - attachmentPreviewHandoffByMessageIdRef.current = next; - return next; - }); - for (const previewUrl of currentPreviewUrls) { - revokeBlobPreviewUrl(previewUrl); + const clearAttachmentPreviewHandoff = ( + messageId: MessageId, + previewUrls?: ReadonlyArray, + ) => { + delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; + const currentPreviewUrls = + previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; + setAttachmentPreviewHandoffByMessageId((existing) => { + if (!(messageId in existing)) { + return existing; } - }, - [], - ); - const clearAttachmentPreviewHandoffs = useCallback(() => { + const next = { ...existing }; + delete next[messageId]; + attachmentPreviewHandoffByMessageIdRef.current = next; + return next; + }); + for (const previewUrl of currentPreviewUrls) { + revokeBlobPreviewUrl(previewUrl); + } + }; + const clearAttachmentPreviewHandoffStable = useStableCallback(clearAttachmentPreviewHandoff); + const clearAttachmentPreviewHandoffs = () => { attachmentPreviewPromotionInFlightByMessageIdRef.current = {}; for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) { for (const previewUrl of previewUrls) { @@ -3768,16 +3845,17 @@ export default function ChatView(props: ChatViewProps) { } attachmentPreviewHandoffByMessageIdRef.current = {}; setAttachmentPreviewHandoffByMessageId({}); - }, []); + }; + const clearAttachmentPreviewHandoffsStable = useStableCallback(clearAttachmentPreviewHandoffs); useEffect(() => { return () => { - clearAttachmentPreviewHandoffs(); + clearAttachmentPreviewHandoffsStable(); for (const message of optimisticUserMessagesRef.current) { revokeUserMessagePreviewUrls(message); } }; - }, [clearAttachmentPreviewHandoffs]); - const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => { + }, [clearAttachmentPreviewHandoffsStable]); + const handoffAttachmentPreviews = (messageId: MessageId, previewUrls: string[]) => { if (previewUrls.length === 0) return; const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; @@ -3795,45 +3873,42 @@ export default function ChatView(props: ChatViewProps) { attachmentPreviewHandoffByMessageIdRef.current = next; return next; }); - }, []); - const downloadFileAttachment = useCallback( - async (attachment: ChatFileAttachment) => { - const connection = readPreparedConnection(environmentId); - if (!connection) { - toastManager.add({ type: "error", title: "The environment is not connected." }); - return; - } + }; + const handoffAttachmentPreviewsStable = useStableCallback(handoffAttachmentPreviews); + const downloadFileAttachment = async (attachment: ChatFileAttachment) => { + const connection = readPreparedConnection(environmentId); + if (!connection) { + toastManager.add({ type: "error", title: "The environment is not connected." }); + return; + } - try { - const url = await resolveFileAttachmentUrl({ - attachment, - environmentId, - httpBaseUrl: connection.httpBaseUrl, - createAssetUrl: createAttachmentAssetUrl, - }); - const anchor = document.createElement("a"); - anchor.href = url; - anchor.download = attachment.name; - anchor.click(); - } catch (error) { - toastManager.add({ - type: "error", - title: "Could not download " + attachment.name, - description: error instanceof Error ? error.message : "The attachment is unavailable.", - }); - } - }, - [createAttachmentAssetUrl, environmentId], - ); - const openFileAttachment = useCallback( - (attachment: ChatFileAttachment) => { - if (activeThreadRef) { - useRightPanelStore.getState().openAttachment(activeThreadRef, attachment); - return; - } - }, - [activeThreadRef], - ); + try { + const url = await resolveFileAttachmentUrl({ + attachment, + environmentId, + httpBaseUrl: connection.httpBaseUrl, + createAssetUrl: createAttachmentAssetUrl, + }); + const anchor = document.createElement("a"); + anchor.href = url; + anchor.download = attachment.name; + anchor.click(); + } catch (error) { + toastManager.add({ + type: "error", + title: "Could not download " + attachment.name, + description: error instanceof Error ? error.message : "The attachment is unavailable.", + }); + } + }; + const downloadFileAttachmentStable = useStableCallback(downloadFileAttachment); + const openFileAttachment = (attachment: ChatFileAttachment) => { + if (activeThreadRef) { + useRightPanelStore.getState().openAttachment(activeThreadRef, attachment); + return; + } + }; + const openFileAttachmentStable = useStableCallback(openFileAttachment); const serverAttachmentResources = useMemo( () => selectHandoffImageResources( @@ -3924,7 +3999,7 @@ export default function ChatView(props: ChatViewProps) { if (cancelled) { return; } - clearAttachmentPreviewHandoff(messageId as MessageId, handoffPreviewUrls); + clearAttachmentPreviewHandoffStable(messageId as MessageId, handoffPreviewUrls); }) .catch(() => { if (!cancelled) { @@ -3948,7 +4023,7 @@ export default function ChatView(props: ChatViewProps) { }; }, [ attachmentPreviewHandoffByMessageId, - clearAttachmentPreviewHandoff, + clearAttachmentPreviewHandoffStable, serverAttachmentUrlById, serverVisibleTurnItems, ]); @@ -4115,25 +4190,24 @@ export default function ChatView(props: ChatViewProps) { () => new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])), [retryableRunIdsKey], ); - const onRetryWorkspacePreparation = useCallback( - (runId: RunId) => { - // One retry per failed run: a second click lands after the run is preparing again. - if (!activeThreadRef || retryingWorkspacePreparationRunIds.has(runId)) return; - retryingWorkspacePreparationRunIds.add(runId); - void retryWorkspacePreparation({ - environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, runId }, - }).finally(() => retryingWorkspacePreparationRunIds.delete(runId)); - }, - [activeThreadRef, retryWorkspacePreparation], - ); - const onCancelWorktreeSetup = useCallback(() => { + const onRetryWorkspacePreparation = (runId: RunId) => { + // One retry per failed run: a second click lands after the run is preparing again. + if (!activeThreadRef || retryingWorkspacePreparationRunIds.has(runId)) return; + retryingWorkspacePreparationRunIds.add(runId); + void retryWorkspacePreparation({ + environmentId: activeThreadRef.environmentId, + input: { threadId: activeThreadRef.threadId, runId }, + }).finally(() => retryingWorkspacePreparationRunIds.delete(runId)); + }; + const onRetryWorkspacePreparationStable = useStableCallback(onRetryWorkspacePreparation); + const onCancelWorktreeSetup = () => { if (!worktreeSetup || worktreeSetup.phase !== "running") return; void cancelWorktreeSetup({ environmentId: setupTarget.environmentId, input: { threadId: worktreeSetup.threadId }, }); - }, [cancelWorktreeSetup, setupTarget.environmentId, worktreeSetup]); + }; + const onCancelWorktreeSetupStable = useStableCallback(onCancelWorktreeSetup); // The setup terminal belongs to the thread that was set up. A failed // bootstrap deletes that thread and closes its terminals, so only offer the // terminal while the setup thread is still the active one. @@ -4400,7 +4474,7 @@ export default function ChatView(props: ChatViewProps) { () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions), [keybindings, terminalShortcutLabelOptions], ); - const onToggleDiff = useCallback(() => { + const onToggleDiff = () => { if (!isServerThread) { return; } @@ -4410,7 +4484,8 @@ export default function ChatView(props: ChatViewProps) { if (activeThreadRef) { useRightPanelStore.getState().toggle(activeThreadRef, "diff"); } - }, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]); + }; + const onToggleDiffStable = useStableCallback(onToggleDiff); const needsLoadBalancing = Cloud.needsLoadBalancedPick({ automatic: automaticEnvironment, @@ -4480,7 +4555,7 @@ export default function ChatView(props: ChatViewProps) { logicalProjectEnvironments, setDraftThreadContext, ]); - const onAutoEnvironment = useCallback(() => { + const onAutoEnvironment = () => { if (envLocked || !draftId) return; cloud.onEnvironmentPicked(null); if (composerHasAttachments) { @@ -4502,15 +4577,8 @@ export default function ChatView(props: ChatViewProps) { branch: null, worktreePath: null, }); - }, [ - envLocked, - draftId, - setDraftThreadContext, - loadBalancing.refresh, - logicalProjectEnvironments, - composerHasAttachments, - cloud.onEnvironmentPicked, - ]); + }; + const onAutoEnvironmentStable = useStableCallback(onAutoEnvironment); const autoEnvironmentLabel = automaticEnvironment ? draftThread?.loadBalancedEnvironmentId ? "Auto balance" @@ -4531,85 +4599,70 @@ export default function ChatView(props: ChatViewProps) { }; }, [draftId, activeProjectKey]); - const onEnvironmentChange = useCallback( - (nextEnvironmentId: EnvironmentId) => { - if (envLocked || !draftId || sendInFlightRef.current) return; - const originalDraft = getDraftSession(draftId); - if (!originalDraft || originalDraft.promotedTo) return; - const target = logicalProjectEnvironments.find( - (env) => env.environmentId === nextEnvironmentId, - ); - if (!target) return; - cloud.onEnvironmentPicked(nextEnvironmentId); - const request = { environmentId: target.environmentId }; - environmentChangeRef.current = request; - setIsEnvironmentChanging(false); - const retarget = (project: (typeof allProjects)[number]) => { - const currentDraft = getDraftSession(draftId); - if ( - environmentChangeRef.current !== request || - sendInFlightRef.current || - !currentDraft || - currentDraft.promotedTo || - currentDraft.environmentId !== originalDraft.environmentId || - currentDraft.projectId !== originalDraft.projectId - ) - return; - const projectRef = scopeProjectRef(target.environmentId, project.id); - if (activeProjectIsScratch) { - // Scratch projects are machine-local, so move their logical mapping too. - setLogicalProjectDraftThreadId( - deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings), - projectRef, - draftId, - { environmentSelection: "manual", loadBalancedEnvironmentId: null }, - ); - } else { - setDraftThreadContext(draftId, { - projectRef, - environmentSelection: "manual", - loadBalancedEnvironmentId: null, - }); - } - }; - const finish = () => { - if (environmentChangeRef.current === request) { - environmentChangeRef.current = null; - setIsEnvironmentChanging(false); - } - }; - if (target.projectId !== null) { - const project = allProjects.find( - (project) => - project.environmentId === target.environmentId && project.id === target.projectId, - ); - if (project) retarget(project); - finish(); + const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => { + if (envLocked || !draftId || sendInFlightRef.current) return; + const originalDraft = getDraftSession(draftId); + if (!originalDraft || originalDraft.promotedTo) return; + const target = logicalProjectEnvironments.find( + (env) => env.environmentId === nextEnvironmentId, + ); + if (!target) return; + cloud.onEnvironmentPicked(nextEnvironmentId); + const request = { environmentId: target.environmentId }; + environmentChangeRef.current = request; + setIsEnvironmentChanging(false); + const retarget = (project: (typeof allProjects)[number]) => { + const currentDraft = getDraftSession(draftId); + if ( + environmentChangeRef.current !== request || + sendInFlightRef.current || + !currentDraft || + currentDraft.promotedTo || + currentDraft.environmentId !== originalDraft.environmentId || + currentDraft.projectId !== originalDraft.projectId + ) return; + const projectRef = scopeProjectRef(target.environmentId, project.id); + if (activeProjectIsScratch) { + // Scratch projects are machine-local, so move their logical mapping too. + setLogicalProjectDraftThreadId( + deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings), + projectRef, + draftId, + { environmentSelection: "manual", loadBalancedEnvironmentId: null }, + ); + } else { + setDraftThreadContext(draftId, { + projectRef, + environmentSelection: "manual", + loadBalancedEnvironmentId: null, + }); } - // Keep send disabled until the destination Scratch project is ready. - setIsEnvironmentChanging(true); - void openScratchProject(target.environmentId, "Could not switch machine") - .then((project) => { - if (project) retarget(project); - }) - .finally(finish); - }, - [ - activeProjectIsScratch, - allProjects, - draftId, - envLocked, - getDraftSession, - logicalProjectEnvironments, - openScratchProject, - projectGroupingSettings, - sendInFlightRef, - setDraftThreadContext, - setLogicalProjectDraftThreadId, - cloud.onEnvironmentPicked, - ], - ); + }; + const finish = () => { + if (environmentChangeRef.current === request) { + environmentChangeRef.current = null; + setIsEnvironmentChanging(false); + } + }; + if (target.projectId !== null) { + const project = allProjects.find( + (project) => + project.environmentId === target.environmentId && project.id === target.projectId, + ); + if (project) retarget(project); + finish(); + return; + } + // Keep send disabled until the destination Scratch project is ready. + setIsEnvironmentChanging(true); + void openScratchProject(target.environmentId, "Could not switch machine") + .then((project) => { + if (project) retarget(project); + }) + .finally(finish); + }; + const onEnvironmentChangeStable = useStableCallback(onEnvironmentChange); const activeTerminalGroup = terminalUiState.terminalGroups.find( @@ -4621,48 +4674,28 @@ export default function ChatView(props: ChatViewProps) { null; const hasReachedSplitLimit = (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP; - const setThreadError = useCallback( - (targetThreadId: ThreadId | null, error: string | null) => { - if (!targetThreadId) return; - const nextError = sanitizeThreadErrorMessage(error); - const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() }; - if ( - serverThread && - targetThreadId === routeThreadRef.threadId && - serverThread.environmentId === routeThreadRef.environmentId && - serverThread.id === targetThreadId - ) { - setLocalServerErrorsByThreadKey((existing) => { - if ((existing[routeThreadKey]?.message ?? null) === nextError) { - return existing; - } - return { - ...existing, - [routeThreadKey]: nextEntry, - }; - }); - return; - } - const localDraftErrorKey = draftId ?? targetThreadId; - setLocalDraftErrorsByDraftId((existing) => { - if ((existing[localDraftErrorKey]?.message ?? null) === nextError) { - return existing; - } - return { - ...existing, - [localDraftErrorKey]: nextEntry, - }; - }); - }, - [draftId, routeThreadKey, routeThreadRef, serverThread], + const setThreadError = useMemo( + () => + makeThreadErrorSetter({ + routeThreadRef, + routeThreadKey, + draftId, + serverThreadRef: serverThread + ? { threadId: serverThread.id, environmentId: serverThread.environmentId } + : null, + setLocalServerErrorsByThreadKey, + setLocalDraftErrorsByDraftId, + }), + [draftId, routeThreadKey, routeThreadRef, serverThread?.id, serverThread?.environmentId], ); - const focusComposer = useCallback(() => { + const focusComposer = () => { composerRef.current?.focusAtEnd(); - }, [composerRef]); + }; + const focusComposerStable = useStableCallback(focusComposer); const canInterruptRunningThread = canOperateThread && deriveCanInterruptRunningThread(activeThread !== undefined, activeRuntime); - const onInterrupt = useCallback(async () => { + const onInterrupt = async () => { if ( !activeThread || !readEnvironmentScope(activeThread.environmentId, AuthOrchestrationOperateScope) @@ -4679,56 +4712,54 @@ export default function ChatView(props: ChatViewProps) { error instanceof Error ? error.message : "Failed to interrupt the current turn.", ); } - }, [activeThread, environmentId, interruptThreadTurn, setThreadError]); - useEffect(() => subscribeSnapShotComposerFocus(focusComposer), [focusComposer]); - const scheduleComposerFocus = useCallback(() => { + }; + const onInterruptStable = useStableCallback(onInterrupt); + useEffect(() => subscribeSnapShotComposerFocus(focusComposerStable), [focusComposerStable]); + const scheduleComposerFocus = () => { window.requestAnimationFrame(() => { focusComposer(); }); - }, [focusComposer]); - const useArtifactTemplate = useCallback( - (template: CodexArtifactTemplate) => { - const composer = composerRef.current; - if (!composer) return; - - const currentDraft = composer.getSendContext().prompt; - const prompt = codexArtifactTemplatePromptToAppend(currentDraft, template); - if (prompt !== null && !composer.insertTextAtEnd(prompt, { ensureLeadingBoundary: true })) { - toastManager.add({ - type: "error", - title: "Unable to add to chat", - description: "The composer is busy; try again once it is ready.", - }); - return; - } - scheduleComposerFocus(); - }, - [composerRef, scheduleComposerFocus], - ); + }; + const scheduleComposerFocusStable = useStableCallback(scheduleComposerFocus); + const useArtifactTemplate = (template: CodexArtifactTemplate) => { + const composer = composerRef.current; + if (!composer) return; + + const currentDraft = composer.getSendContext().prompt; + const prompt = codexArtifactTemplatePromptToAppend(currentDraft, template); + if (prompt !== null && !composer.insertTextAtEnd(prompt, { ensureLeadingBoundary: true })) { + toastManager.add({ + type: "error", + title: "Unable to add to chat", + description: "The composer is busy; try again once it is ready.", + }); + return; + } + scheduleComposerFocus(); + }; + const useArtifactTemplateStable = useStableCallback(useArtifactTemplate); // An MCP App's approved `ui/message`: queued like a typed message, so it // never steers or interrupts a running turn. - const sendAppMessage = useCallback( - async (text: string) => { - if (!isServerThread || activeThreadId === null) { - throw new Error("Messages from apps need a started thread."); - } - const result = await startThreadTurn({ - environmentId, - input: { - threadId: activeThreadId, - message: { messageId: newMessageId(), role: "user", text, attachments: [] }, - runtimeMode, - interactionMode, - dispatchMode: "queue", - }, - }); - if (result._tag === "Failure") { - const error = squashAtomCommandFailure(result); - throw error instanceof Error ? error : new Error("Could not send the app's message."); - } - }, - [activeThreadId, environmentId, interactionMode, isServerThread, runtimeMode, startThreadTurn], - ); + const sendAppMessage = async (text: string) => { + if (!isServerThread || activeThreadId === null) { + throw new Error("Messages from apps need a started thread."); + } + const result = await startThreadTurn({ + environmentId, + input: { + threadId: activeThreadId, + message: { messageId: newMessageId(), role: "user", text, attachments: [] }, + runtimeMode, + interactionMode, + dispatchMode: "queue", + }, + }); + if (result._tag === "Failure") { + const error = squashAtomCommandFailure(result); + throw error instanceof Error ? error : new Error("Could not send the app's message."); + } + }; + const sendAppMessageStable = useStableCallback(sendAppMessage); const editQueuedRunCommand = useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false, }); @@ -4756,48 +4787,34 @@ export default function ChatView(props: ChatViewProps) { url: urlByAttachmentId.get(attachment.id) ?? null, })); }, [editingQueuedRun, queuedEditImageResources, queuedEditImageUrls]); - const beginEditingQueuedRun = useCallback( - (request: EditQueuedRunRequest) => { - if (!activeThread) return; - if (editingQueuedRun !== null && editingQueuedRun.runId !== request.runId) { - clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId)); - } - const target = queuedEditDraftTargetFor(request.runId); - clearComposerDraftContent(target); - setComposerDraftPrompt(target, request.text); - setEditingQueuedRun({ - threadId: activeThread.id, - runId: request.runId, - messageId: request.messageId, - originalText: request.text, - existingAttachments: request.attachments, - context: serverProjection?.messages.find((message) => message.id === request.messageId) - ?.context, - }); - scheduleComposerFocus(); - }, - [ - activeThread, - clearComposerDraftContent, - editingQueuedRun, - queuedEditDraftTargetFor, - serverProjection, - scheduleComposerFocus, - setComposerDraftPrompt, - ], - ); - const cancelEditingQueuedRun = useCallback(() => { + const beginEditingQueuedRun = (request: EditQueuedRunRequest) => { + if (!activeThread) return; + if (editingQueuedRun !== null && editingQueuedRun.runId !== request.runId) { + clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId)); + } + const target = queuedEditDraftTargetFor(request.runId); + clearComposerDraftContent(target); + setComposerDraftPrompt(target, request.text); + setEditingQueuedRun({ + threadId: activeThread.id, + runId: request.runId, + messageId: request.messageId, + originalText: request.text, + existingAttachments: request.attachments, + context: serverProjection?.messages.find((message) => message.id === request.messageId) + ?.context, + }); + scheduleComposerFocus(); + }; + const beginEditingQueuedRunStable = useStableCallback(beginEditingQueuedRun); + const cancelEditingQueuedRun = () => { if (editingQueuedRun === null) return; clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId)); setEditingQueuedRun(null); scheduleComposerFocus(); - }, [ - clearComposerDraftContent, - editingQueuedRun, - queuedEditDraftTargetFor, - scheduleComposerFocus, - ]); - const removeEditingQueuedAttachment = useCallback((attachmentId: string) => { + }; + const cancelEditingQueuedRunStable = useStableCallback(cancelEditingQueuedRun); + const removeEditingQueuedAttachment = (attachmentId: string) => { setEditingQueuedRun((current) => current === null ? current @@ -4808,7 +4825,8 @@ export default function ChatView(props: ChatViewProps) { ), }, ); - }, []); + }; + const removeEditingQueuedAttachmentStable = useStableCallback(removeEditingQueuedAttachment); // Exit edit mode when the edited run leaves the queue (it started, or was // cancelled from another client). A dirty edit moves into the thread's own // draft when that draft is empty; otherwise it is dropped with a toast. @@ -4851,20 +4869,16 @@ export default function ChatView(props: ChatViewProps) { queuedEditDraftTargetFor, serverProjection, ]); - const addTerminalContextToDraft = useCallback( - (selection: TerminalContextSelection) => { - composerRef.current?.addTerminalContext(selection); - }, - [composerRef], - ); - const setTerminalOpen = useCallback( - (open: boolean) => { - if (!activeThreadRef) return; - storeSetTerminalOpen(activeThreadRef, open); - }, - [activeThreadRef, storeSetTerminalOpen], - ); - const toggleTerminalVisibility = useCallback(() => { + const addTerminalContextToDraft = (selection: TerminalContextSelection) => { + composerRef.current?.addTerminalContext(selection); + }; + const addTerminalContextToDraftStable = useStableCallback(addTerminalContextToDraft); + const setTerminalOpen = (open: boolean) => { + if (!activeThreadRef) return; + storeSetTerminalOpen(activeThreadRef, open); + }; + const setTerminalOpenStable = useStableCallback(setTerminalOpen); + const toggleTerminalVisibility = () => { if (!activeThreadRef) return; const nextOpen = !terminalUiState.terminalOpen; if ( @@ -4908,76 +4922,45 @@ export default function ChatView(props: ChatViewProps) { return; } setTerminalOpen(nextOpen); - }, [ - activeServerOrderedTerminalIds, - activeProject, - activeThreadId, - activeThreadRef, - activeThreadWorktreePath, - allocateTerminalId, - environmentId, - gitCwd, - openTerminal, - panelTerminalIds, - runningTerminalIds, - hasTerminalWriteAccess, - setTerminalOpen, - storeEnsureTerminal, - terminalUiState.terminalIds.length, - terminalUiState.terminalOpen, - ]); - const splitTerminal = useCallback( - (direction: "horizontal" | "vertical" = "horizontal") => { - if ( - !hasTerminalWriteAccess() || - !activeThreadRef || - hasReachedSplitLimit || - !activeThreadId || - !activeProject - ) { - return; - } - const cwdForOpen = gitCwd ?? activeProject.workspaceRoot; - if (!cwdForOpen) { - return; - } - const terminalId = allocateTerminalId(); - if (direction === "vertical") { - storeSplitTerminalVertical(activeThreadRef, terminalId); - } else { - storeSplitTerminal(activeThreadRef, terminalId); - } - setTerminalFocusRequestId((value) => value + 1); - void openTerminal({ - environmentId, - input: { - threadId: activeThreadId, - terminalId, - cwd: cwdForOpen, - ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), - env: projectScriptRuntimeEnv({ - project: { cwd: activeProject.workspaceRoot }, - worktreePath: activeThreadWorktreePath, - }), - }, - }); - }, - [ - activeProject, - activeThreadId, - allocateTerminalId, - activeThreadRef, - openTerminal, - hasTerminalWriteAccess, - activeThreadWorktreePath, + }; + const toggleTerminalVisibilityStable = useStableCallback(toggleTerminalVisibility); + const splitTerminal = (direction: "horizontal" | "vertical" = "horizontal") => { + if ( + !hasTerminalWriteAccess() || + !activeThreadRef || + hasReachedSplitLimit || + !activeThreadId || + !activeProject + ) { + return; + } + const cwdForOpen = gitCwd ?? activeProject.workspaceRoot; + if (!cwdForOpen) { + return; + } + const terminalId = allocateTerminalId(); + if (direction === "vertical") { + storeSplitTerminalVertical(activeThreadRef, terminalId); + } else { + storeSplitTerminal(activeThreadRef, terminalId); + } + setTerminalFocusRequestId((value) => value + 1); + void openTerminal({ environmentId, - gitCwd, - hasReachedSplitLimit, - storeSplitTerminal, - storeSplitTerminalVertical, - ], - ); - const createNewTerminal = useCallback(() => { + input: { + threadId: activeThreadId, + terminalId, + cwd: cwdForOpen, + ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), + env: projectScriptRuntimeEnv({ + project: { cwd: activeProject.workspaceRoot }, + worktreePath: activeThreadWorktreePath, + }), + }, + }); + }; + const splitTerminalStable = useStableCallback(splitTerminal); + const createNewTerminal = () => { if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) { return; } @@ -5001,206 +4984,162 @@ export default function ChatView(props: ChatViewProps) { }), }, }); - }, [ - activeProject, - activeThreadId, - allocateTerminalId, - activeThreadRef, - openTerminal, - hasTerminalWriteAccess, - activeThreadWorktreePath, - environmentId, - gitCwd, - storeNewTerminal, - ]); - const closeTerminal = useCallback( - (terminalId: string) => { - if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return; - const fallbackExitWrite = () => - writeTerminal({ - environmentId, - input: { threadId: activeThreadId, terminalId, data: "exit\n" }, - }); - void (async () => { - const closeResult = await closeTerminalMutation({ - environmentId, - input: { - threadId: activeThreadId, - terminalId, - deleteHistory: true, - }, - }); - if ( - closeResult._tag === "Failure" && - !isAtomCommandInterrupted(closeResult) && - hasTerminalWriteAccess() - ) { - await fallbackExitWrite(); - } - })(); - storeCloseTerminal(activeThreadRef, terminalId); - setTerminalFocusRequestId((value) => value + 1); - }, - [ - activeThreadId, - activeThreadRef, - closeTerminalMutation, - hasTerminalWriteAccess, - environmentId, - storeCloseTerminal, - writeTerminal, - ], - ); - const runProjectScript = useCallback( - async ( - script: ProjectScript, - options?: { - cwd?: string; - env?: Record; - worktreePath?: string | null; - preferNewTerminal?: boolean; - rememberAsLastInvoked?: boolean; - }, - ) => { - if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return; - if (options?.rememberAsLastInvoked !== false) { - setLastInvokedScriptByProjectId((current) => { - if (current[activeProject.id] === script.id) return current; - return { ...current, [activeProject.id]: script.id }; - }); - } - const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot; - const baseTerminalId = - terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID; - const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId); - const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy; - const shouldCreateNewTerminal = - wantsNewTerminal || - !canReuseTerminal || - !readEnvironmentScope(environmentId, AuthTerminalReadScope); - const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; - - setTerminalUiLaunchContext({ - threadId: activeThreadId, - cwd: targetCwd, - worktreePath: targetWorktreePath, - }); - setTerminalOpen(true); - if (!activeThreadRef) { - return; - } - setTerminalFocusRequestId((value) => value + 1); - - const runtimeEnv = projectScriptRuntimeEnv({ - project: { - cwd: activeProject.workspaceRoot, - }, - worktreePath: targetWorktreePath, - ...(options?.env ? { extraEnv: options.env } : {}), + }; + const createNewTerminalStable = useStableCallback(createNewTerminal); + const closeTerminal = (terminalId: string) => { + if (!hasTerminalWriteAccess() || !activeThreadId || !activeThreadRef) return; + const fallbackExitWrite = () => + writeTerminal({ + environmentId, + input: { threadId: activeThreadId, terminalId, data: "exit\n" }, }); - const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId; - const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal - ? { - threadId: activeThreadId, - terminalId: targetTerminalId, - cwd: targetCwd, - ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), - env: runtimeEnv, - cols: SCRIPT_TERMINAL_COLS, - rows: SCRIPT_TERMINAL_ROWS, - } - : { - threadId: activeThreadId, - terminalId: targetTerminalId, - cwd: targetCwd, - ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), - env: runtimeEnv, - }; - - if (shouldCreateNewTerminal) { - storeNewTerminal(activeThreadRef, targetTerminalId); - } else { - storeSetActiveTerminal(activeThreadRef, targetTerminalId); - } - - const openResult = await openTerminal({ environmentId, input: openTerminalInput }); - if (openResult._tag === "Failure") { - if (!isAtomCommandInterrupted(openResult)) { - const error = squashAtomCommandFailure(openResult); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : `Failed to run script "${script.name}".`, - ); - } - return; - } - - if (!hasTerminalWriteAccess()) return; - const writeResult = await writeTerminal({ + void (async () => { + const closeResult = await closeTerminalMutation({ environmentId, input: { threadId: activeThreadId, - terminalId: targetTerminalId, - data: `${script.command}\r`, + terminalId, + deleteHistory: true, }, }); - if (writeResult._tag === "Failure") { - if (!isAtomCommandInterrupted(writeResult)) { - const error = squashAtomCommandFailure(writeResult); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : `Failed to run script "${script.name}".`, - ); - } - return; + if ( + closeResult._tag === "Failure" && + !isAtomCommandInterrupted(closeResult) && + hasTerminalWriteAccess() + ) { + await fallbackExitWrite(); } - if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) { - const previewResult = await openUrlInPreview({ - threadRef: activeThreadRef, - url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl), - openPreview, - }); - if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) { - const error = squashAtomCommandFailure(previewResult); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not open preview", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }), - ); + })(); + storeCloseTerminal(activeThreadRef, terminalId); + setTerminalFocusRequestId((value) => value + 1); + }; + const runProjectScript = async ( + script: ProjectScript, + options?: { + cwd?: string; + env?: Record; + worktreePath?: string | null; + preferNewTerminal?: boolean; + rememberAsLastInvoked?: boolean; + }, + ) => { + if (!hasTerminalWriteAccess() || !activeThreadId || !activeProject || !activeThread) return; + if (options?.rememberAsLastInvoked !== false) { + setLastInvokedScriptByProjectId((current) => { + if (current[activeProject.id] === script.id) return current; + return { ...current, [activeProject.id]: script.id }; + }); + } + const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot; + const baseTerminalId = + terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID; + const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId); + const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy; + const shouldCreateNewTerminal = + wantsNewTerminal || + !canReuseTerminal || + !readEnvironmentScope(environmentId, AuthTerminalReadScope); + const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; + + setTerminalUiLaunchContext({ + threadId: activeThreadId, + cwd: targetCwd, + worktreePath: targetWorktreePath, + }); + setTerminalOpen(true); + if (!activeThreadRef) { + return; + } + setTerminalFocusRequestId((value) => value + 1); + + const runtimeEnv = projectScriptRuntimeEnv({ + project: { + cwd: activeProject.workspaceRoot, + }, + worktreePath: targetWorktreePath, + ...(options?.env ? { extraEnv: options.env } : {}), + }); + const targetTerminalId = shouldCreateNewTerminal ? allocateTerminalId() : baseTerminalId; + const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal + ? { + threadId: activeThreadId, + terminalId: targetTerminalId, + cwd: targetCwd, + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), + env: runtimeEnv, + cols: SCRIPT_TERMINAL_COLS, + rows: SCRIPT_TERMINAL_ROWS, } + : { + threadId: activeThreadId, + terminalId: targetTerminalId, + cwd: targetCwd, + ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), + env: runtimeEnv, + }; + + if (shouldCreateNewTerminal) { + storeNewTerminal(activeThreadRef, targetTerminalId); + } else { + storeSetActiveTerminal(activeThreadRef, targetTerminalId); + } + + const openResult = await openTerminal({ environmentId, input: openTerminalInput }); + if (openResult._tag === "Failure") { + if (!isAtomCommandInterrupted(openResult)) { + const error = squashAtomCommandFailure(openResult); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : `Failed to run script "${script.name}".`, + ); } - }, - [ - activeProject, - activeThread, - activeThreadId, - activeThreadRef, - gitCwd, - setTerminalOpen, - setThreadError, - storeNewTerminal, - storeSetActiveTerminal, - setLastInvokedScriptByProjectId, + return; + } + + if (!hasTerminalWriteAccess()) return; + const writeResult = await writeTerminal({ environmentId, - openTerminal, - openPreview, - hasTerminalWriteAccess, - activeKnownTerminalIds, - canReuseTerminal, - allocateTerminalId, - runningTerminalIds, - terminalUiState.activeTerminalId, - writeTerminal, - ], - ); + input: { + threadId: activeThreadId, + terminalId: targetTerminalId, + data: `${script.command}\r`, + }, + }); + if (writeResult._tag === "Failure") { + if (!isAtomCommandInterrupted(writeResult)) { + const error = squashAtomCommandFailure(writeResult); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : `Failed to run script "${script.name}".`, + ); + } + return; + } + if (script.autoOpenPreview && script.previewUrl && isPreviewSupportedInRuntime()) { + const previewResult = await openUrlInPreview({ + threadRef: activeThreadRef, + url: resolveDiscoveredServerUrl(activeThreadRef.environmentId, script.previewUrl), + openPreview, + }); + if (previewResult._tag === "Failure" && !isAtomCommandInterrupted(previewResult)) { + const error = squashAtomCommandFailure(previewResult); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not open preview", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); + } + } + }; + const runProjectScriptStable = useStableCallback(runProjectScript); - const runProjectScriptRef = useRef(runProjectScript); + const runProjectScriptRef = useRef(runProjectScriptStable); useLayoutEffect(() => { - runProjectScriptRef.current = runProjectScript; - }, [runProjectScript]); - const runShellCommand = useCallback((command: string) => { + runProjectScriptRef.current = runProjectScriptStable; + }, [runProjectScriptStable]); + const runShellCommand = (command: string) => { void runProjectScriptRef.current( { id: "chat-code-block", @@ -5211,334 +5150,302 @@ export default function ChatView(props: ChatViewProps) { }, { rememberAsLastInvoked: false }, ); - }, []); + }; + const runShellCommandStable = useStableCallback(runShellCommand); const supportsProjectSettingsOverrides = environmentById.get(environmentId)?.serverConfig?.environment.capabilities .projectSettingsOverrides === true; - const persistProjectScripts = useCallback( - async (input: { - projectId: ProjectId; - projectCwd: string; - previousScripts: ReadonlyArray; - nextScripts: ReadonlyArray; - keybinding: NewProjectScriptInput["keybinding"]; - keybindingCommand: KeybindingCommand | null; - }): Promise> => { - const previousKeybinding = keybindingValueForCommand( - appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [], - input.keybindingCommand, - ); - const isDeletingScript = !input.nextScripts.some( - (script) => commandForProjectScript(script.id) === input.keybindingCommand, - ); - const changesKeybinding = - input.keybinding !== undefined && - (input.keybinding?.trim() || null) !== previousKeybinding && - (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope)); - if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) { - return AsyncResult.failure( - Cause.fail( - new EnvironmentAuthorizationError({ - requiredScope: AuthSettingsWriteScope, - message: "This connection cannot change keyboard shortcuts.", - }), - ), - ); - } - const keybindingRule = changesKeybinding - ? decodeProjectScriptKeybindingRule({ - keybinding: input.keybinding, - command: input.keybindingCommand, - }) - : null; - const updateResult = mapAtomCommandResult( - await updateProjectScriptSettings({ - environmentId, - input: { - // The canonical key on servers that understand it; the legacy - // per-project map is still translated on older ones. - patch: supportsProjectSettingsOverrides - ? { - projectSettingsOverrides: { - [input.projectId]: { - ...settings.projectSettingsOverrides[input.projectId], - defaultProjectScripts: input.nextScripts, - }, - }, - } - : { - projectScriptOverrides: { - [input.projectId]: input.nextScripts, - }, - }, - }, - }), - () => undefined, + const persistProjectScripts = async (input: { + projectId: ProjectId; + projectCwd: string; + previousScripts: ReadonlyArray; + nextScripts: ReadonlyArray; + keybinding: NewProjectScriptInput["keybinding"]; + keybindingCommand: KeybindingCommand | null; + }): Promise> => { + const previousKeybinding = keybindingValueForCommand( + appAtomRegistry.get(serverEnvironment.configValueAtom(environmentId))?.keybindings ?? [], + input.keybindingCommand, + ); + const isDeletingScript = !input.nextScripts.some( + (script) => commandForProjectScript(script.id) === input.keybindingCommand, + ); + const changesKeybinding = + input.keybinding !== undefined && + (input.keybinding?.trim() || null) !== previousKeybinding && + (!isDeletingScript || readEnvironmentScope(environmentId, AuthSettingsWriteScope)); + if (changesKeybinding && !readEnvironmentScope(environmentId, AuthSettingsWriteScope)) { + return AsyncResult.failure( + Cause.fail( + new EnvironmentAuthorizationError({ + requiredScope: AuthSettingsWriteScope, + message: "This connection cannot change keyboard shortcuts.", + }), + ), ); - if (updateResult._tag === "Failure") { - return updateResult; - } - - if (!changesKeybinding) return updateResult; - if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) { - return AsyncResult.failure( - Cause.fail( - new EnvironmentAuthorizationError({ - requiredScope: AuthSettingsWriteScope, - message: isDeletingScript - ? "The script was deleted, but its keyboard shortcut could not be removed because permission changed." - : "The script was saved, but this connection can no longer change keyboard shortcuts.", - }), - ), - ); - } - - const scriptId = input.keybindingCommand - ? projectScriptIdFromCommand(input.keybindingCommand) - : null; - if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) { - return updateResult; - } - const retainedElsewhere = - !input.nextScripts.some((script) => script.id === scriptId) && - (settings.defaultProjectScripts.some((script) => script.id === scriptId) || - Object.entries(settings.projectSettingsOverrides).some( - ([projectId, entry]) => - projectId !== input.projectId && - entry.defaultProjectScripts?.some((script) => script.id === scriptId), - ) || - allProjects.some( - (other) => - other.environmentId === environmentId && - other.id !== input.projectId && - resolveProjectScripts(settings, other).some((script) => script.id === scriptId), - )); - if (!keybindingRule && retainedElsewhere) return updateResult; - - const previousRules = ( - environmentById.get(environmentId)?.serverConfig?.keybindings ?? [] - ).flatMap((binding) => { - if (binding.command !== input.keybindingCommand || binding.whenAst) return []; - const previous = decodeProjectScriptKeybindingRule({ - keybinding: keybindingValueForCommand([binding], input.keybindingCommand), + } + const keybindingRule = changesKeybinding + ? decodeProjectScriptKeybindingRule({ + keybinding: input.keybinding, command: input.keybindingCommand, - }); - return previous ? [previous] : []; - }); - const previous = previousRules.at(-1); - for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) { - const result = await removeKeybinding({ environmentId, input: rule }); - if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined); - } - return keybindingRule - ? mapAtomCommandResult( - await upsertKeybinding({ - environmentId, - input: - previous && previous.key !== keybindingRule.key - ? { ...keybindingRule, replace: previous } - : keybindingRule, - }), - () => undefined, - ) - : updateResult; - }, - [ - allProjects, - environmentById, - environmentId, - removeKeybinding, - settings, - supportsProjectSettingsOverrides, - updateProjectScriptSettings, - upsertKeybinding, - ], - ); - const saveProjectScript = useCallback( - async (input: NewProjectScriptInput): Promise> => { - if (!activeProject) { - return AsyncResult.success(undefined); - } - const nextId = nextProjectScriptId( - input.name, - activeProjectScripts.map((script) => script.id), + }) + : null; + const updateResult = mapAtomCommandResult( + await updateProjectScriptSettings({ + environmentId, + input: { + // The canonical key on servers that understand it; the legacy + // per-project map is still translated on older ones. + patch: supportsProjectSettingsOverrides + ? { + projectSettingsOverrides: { + [input.projectId]: { + ...settings.projectSettingsOverrides[input.projectId], + defaultProjectScripts: input.nextScripts, + }, + }, + } + : { + projectScriptOverrides: { + [input.projectId]: input.nextScripts, + }, + }, + }, + }), + () => undefined, + ); + if (updateResult._tag === "Failure") { + return updateResult; + } + + if (!changesKeybinding) return updateResult; + if (!readEnvironmentScope(environmentId, AuthSettingsWriteScope)) { + return AsyncResult.failure( + Cause.fail( + new EnvironmentAuthorizationError({ + requiredScope: AuthSettingsWriteScope, + message: isDeletingScript + ? "The script was deleted, but its keyboard shortcut could not be removed because permission changed." + : "The script was saved, but this connection can no longer change keyboard shortcuts.", + }), + ), ); - const nextScript = buildProjectScript(nextId, input); - const nextScripts = [ - ...activeProjectScripts.map((script) => releaseClaimedRoles(script, input)), - nextScript, - ]; + } - return persistProjectScripts({ - projectId: activeProject.id, - projectCwd: activeProject.workspaceRoot, - previousScripts: activeProjectScripts, - nextScripts, - keybinding: input.keybinding, - keybindingCommand: commandForProjectScript(nextId), + const scriptId = input.keybindingCommand + ? projectScriptIdFromCommand(input.keybindingCommand) + : null; + if (!keybindingRule && !input.previousScripts.some((script) => script.id === scriptId)) { + return updateResult; + } + const retainedElsewhere = + !input.nextScripts.some((script) => script.id === scriptId) && + (settings.defaultProjectScripts.some((script) => script.id === scriptId) || + Object.entries(settings.projectSettingsOverrides).some( + ([projectId, entry]) => + projectId !== input.projectId && + entry.defaultProjectScripts?.some((script) => script.id === scriptId), + ) || + allProjects.some( + (other) => + other.environmentId === environmentId && + other.id !== input.projectId && + resolveProjectScripts(settings, other).some((script) => script.id === scriptId), + )); + if (!keybindingRule && retainedElsewhere) return updateResult; + + const previousRules = ( + environmentById.get(environmentId)?.serverConfig?.keybindings ?? [] + ).flatMap((binding) => { + if (binding.command !== input.keybindingCommand || binding.whenAst) return []; + const previous = decodeProjectScriptKeybindingRule({ + keybinding: keybindingValueForCommand([binding], input.keybindingCommand), + command: input.keybindingCommand, }); - }, - [activeProject, activeProjectScripts, persistProjectScripts], - ); - const updateProjectScript = useCallback( - async ( - scriptId: string, - input: NewProjectScriptInput, - ): Promise> => { - if (!activeProject) { - return AsyncResult.success(undefined); - } - const existingScript = activeProjectScripts.find((script) => script.id === scriptId); - if (!existingScript) { - return AsyncResult.failure(Cause.fail(new Error("Script not found."))); - } + return previous ? [previous] : []; + }); + const previous = previousRules.at(-1); + for (const rule of keybindingRule ? previousRules.slice(0, -1) : previousRules) { + const result = await removeKeybinding({ environmentId, input: rule }); + if (result._tag === "Failure") return mapAtomCommandResult(result, () => undefined); + } + return keybindingRule + ? mapAtomCommandResult( + await upsertKeybinding({ + environmentId, + input: + previous && previous.key !== keybindingRule.key + ? { ...keybindingRule, replace: previous } + : keybindingRule, + }), + () => undefined, + ) + : updateResult; + }; + const saveProjectScript = async ( + input: NewProjectScriptInput, + ): Promise> => { + if (!activeProject) { + return AsyncResult.success(undefined); + } + const nextId = nextProjectScriptId( + input.name, + activeProjectScripts.map((script) => script.id), + ); + const nextScript = buildProjectScript(nextId, input); + const nextScripts = [ + ...activeProjectScripts.map((script) => releaseClaimedRoles(script, input)), + nextScript, + ]; - const updatedScript = buildProjectScript(existingScript.id, input); - const nextScripts = activeProjectScripts.map((script) => - script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input), - ); + return persistProjectScripts({ + projectId: activeProject.id, + projectCwd: activeProject.workspaceRoot, + previousScripts: activeProjectScripts, + nextScripts, + keybinding: input.keybinding, + keybindingCommand: commandForProjectScript(nextId), + }); + }; + const saveProjectScriptStable = useStableCallback(saveProjectScript); + const updateProjectScript = async ( + scriptId: string, + input: NewProjectScriptInput, + ): Promise> => { + if (!activeProject) { + return AsyncResult.success(undefined); + } + const existingScript = activeProjectScripts.find((script) => script.id === scriptId); + if (!existingScript) { + return AsyncResult.failure(Cause.fail(new Error("Script not found."))); + } - return persistProjectScripts({ - projectId: activeProject.id, - projectCwd: activeProject.workspaceRoot, - previousScripts: activeProjectScripts, - nextScripts, - keybinding: input.keybinding, - keybindingCommand: commandForProjectScript(scriptId), - }); - }, - [activeProject, activeProjectScripts, persistProjectScripts], - ); - const deleteProjectScript = useCallback( - async (scriptId: string): Promise> => { - if (!activeProject) { - return AsyncResult.success(undefined); - } - const nextScripts = activeProjectScripts.filter((script) => script.id !== scriptId); + const updatedScript = buildProjectScript(existingScript.id, input); + const nextScripts = activeProjectScripts.map((script) => + script.id === scriptId ? updatedScript : releaseClaimedRoles(script, input), + ); - const deletedName = activeProjectScripts.find((s) => s.id === scriptId)?.name; + return persistProjectScripts({ + projectId: activeProject.id, + projectCwd: activeProject.workspaceRoot, + previousScripts: activeProjectScripts, + nextScripts, + keybinding: input.keybinding, + keybindingCommand: commandForProjectScript(scriptId), + }); + }; + const updateProjectScriptStable = useStableCallback(updateProjectScript); + const deleteProjectScript = async ( + scriptId: string, + ): Promise> => { + if (!activeProject) { + return AsyncResult.success(undefined); + } + const nextScripts = activeProjectScripts.filter((script) => script.id !== scriptId); - const result = await persistProjectScripts({ - projectId: activeProject.id, - projectCwd: activeProject.workspaceRoot, - previousScripts: activeProjectScripts, - nextScripts, - keybinding: null, - keybindingCommand: commandForProjectScript(scriptId), + const deletedName = activeProjectScripts.find((s) => s.id === scriptId)?.name; + + const result = await persistProjectScripts({ + projectId: activeProject.id, + projectCwd: activeProject.workspaceRoot, + previousScripts: activeProjectScripts, + nextScripts, + keybinding: null, + keybindingCommand: commandForProjectScript(scriptId), + }); + if (result._tag === "Success") { + toastManager.add({ + type: "success", + title: `Deleted action "${deletedName ?? "Unknown"}"`, }); - if (result._tag === "Success") { - toastManager.add({ - type: "success", - title: `Deleted action "${deletedName ?? "Unknown"}"`, - }); - } else if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Could not delete action", - description: error instanceof Error ? error.message : "An unexpected error occurred.", - }), - ); - } - return result; - }, - [activeProject, activeProjectScripts, persistProjectScripts], - ); + } else if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not delete action", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }), + ); + } + return result; + }; + const deleteProjectScriptStable = useStableCallback(deleteProjectScript); - const handleRuntimeModeChange = useCallback( - (mode: RuntimeMode) => { - if (mode === runtimeMode) return; - setComposerDraftRuntimeMode(composerDraftTarget, mode); - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); - } - scheduleComposerFocus(); - }, - [ - isLocalDraftThread, - runtimeMode, - scheduleComposerFocus, - composerDraftTarget, - setComposerDraftRuntimeMode, - setDraftThreadContext, - ], - ); + const handleRuntimeModeChange = (mode: RuntimeMode) => { + if (mode === runtimeMode) return; + setComposerDraftRuntimeMode(composerDraftTarget, mode); + if (isLocalDraftThread) { + setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); + } + scheduleComposerFocus(); + }; + const handleRuntimeModeChangeStable = useStableCallback(handleRuntimeModeChange); - const handleInteractionModeChange = useCallback( - (mode: ProviderInteractionMode) => { - if (mode === "plan" && !interactionModeEnabled) return; - if (mode === interactionMode) return; - setComposerDraftInteractionMode(composerDraftTarget, mode); - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { interactionMode: mode }); - } - scheduleComposerFocus(); - }, - [ - interactionMode, - interactionModeEnabled, - isLocalDraftThread, - scheduleComposerFocus, - composerDraftTarget, - setComposerDraftInteractionMode, - setDraftThreadContext, - ], - ); - const toggleInteractionMode = useCallback(() => { + const handleInteractionModeChange = (mode: ProviderInteractionMode) => { + if (mode === "plan" && !interactionModeEnabled) return; + if (mode === interactionMode) return; + setComposerDraftInteractionMode(composerDraftTarget, mode); + if (isLocalDraftThread) { + setDraftThreadContext(composerDraftTarget, { interactionMode: mode }); + } + scheduleComposerFocus(); + }; + const handleInteractionModeChangeStable = useStableCallback(handleInteractionModeChange); + const toggleInteractionMode = () => { if (!interactionModeEnabled) return; handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); - }, [handleInteractionModeChange, interactionMode, interactionModeEnabled]); - const openProviderSetup = useCallback( - (instanceId: ProviderInstanceId) => { - void navigate({ - to: "/settings/providers", - search: { environmentId, instanceId }, - }); - }, - [environmentId, navigate], - ); + }; + const toggleInteractionModeStable = useStableCallback(toggleInteractionMode); + const openProviderSetup = (instanceId: ProviderInstanceId) => { + void navigate({ + to: "/settings/providers", + search: { environmentId, instanceId }, + }); + }; + const openProviderSetupStable = useStableCallback(openProviderSetup); const canOperatePreview = useEnvironmentScope( activeThreadRef?.environmentId ?? null, AuthPreviewOperateScope, ); - const createBrowserSurface = useCallback( - (profileId?: string) => { - if (!activeThreadRef || !canOperatePreview) return; - void addBrowserSurface({ - threadRef: activeThreadRef, - openPreview, - ...(profileId === undefined ? {} : { profileId }), - }).then((result) => { - if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; - const error = squashAtomCommandFailure(result); - if (error instanceof BrowserSettingsReadError) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: "Unable to open browser", - description: error.message, - }), - ); - } - }); - }, - [activeThreadRef, canOperatePreview, openPreview], - ); - const addDiffSurface = useCallback(() => { + const createBrowserSurface = (profileId?: string) => { + if (!activeThreadRef || !canOperatePreview) return; + void addBrowserSurface({ + threadRef: activeThreadRef, + openPreview, + ...(profileId === undefined ? {} : { profileId }), + }).then((result) => { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + if (error instanceof BrowserSettingsReadError) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Unable to open browser", + description: error.message, + }), + ); + } + }); + }; + const createBrowserSurfaceStable = useStableCallback(createBrowserSurface); + const addDiffSurface = () => { if (!activeThreadRef || !isServerThread || !isGitRepo) return; useDiffPanelStore.getState().selectGitScope(activeThreadRef, "branch"); useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); - }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]); - const openChangesFromThreadPanel = useCallback(() => { + }; + const addDiffSurfaceStable = useStableCallback(addDiffSurface); + const openChangesFromThreadPanel = () => { addDiffSurface(); - }, [addDiffSurface]); - const addFilesSurface = useCallback(() => { + }; + const openChangesFromThreadPanelStable = useStableCallback(openChangesFromThreadPanel); + const addFilesSurface = () => { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().open(activeThreadRef, "files"); - }, [activeProject, activeThreadRef]); + }; + const addFilesSurfaceStable = useStableCallback(addFilesSurface); const supportsThreadPullRequests = serverConfig?.environment.capabilities.threadPullRequests === true; const visiblePullRequests = visibleThreadPullRequests( @@ -5547,22 +5454,24 @@ export default function ChatView(props: ChatViewProps) { const visiblePullRequestCount = visiblePullRequests.length; const pullRequestsSurfaceAvailable = isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0; - const addPullRequestsSurface = useCallback(() => { + const addPullRequestsSurface = () => { if (!activeThreadRef || !pullRequestsSurfaceAvailable) return; useRightPanelStore.getState().open(activeThreadRef, "pull-requests"); - }, [activeThreadRef, pullRequestsSurfaceAvailable]); + }; + const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface); const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState( activeThreadRef?.environmentId ?? null, ); const [deviceSetupThread, setDeviceSetupThread] = useState(null); - const addDeviceSurface = useCallback(() => { + const addDeviceSurface = () => { if (!activeThreadRef) return; if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") { setDeviceSetupThread(activeThreadRef); return; } useRightPanelStore.getState().open(activeThreadRef, "device"); - }, [activeThreadRef, deviceState.onboardingCompleted, deviceState.hostStatus]); + }; + const addDeviceSurfaceStable = useStableCallback(addDeviceSurface); // A device the agent opens floats over chat like an agent-driven browser, // or becomes a panel tab when floating previews are off. Sessions opened by // another client arrive the same way; sheet layouts get neither. The first @@ -5676,13 +5585,11 @@ export default function ChatView(props: ChatViewProps) { ); if (!sessionStillExists) usePreviewMiniPlayerStore.getState().close(activeThreadRef); }, [activePreviewMiniPlayer, activeThreadRef, deviceState.sessions, deviceStateLoaded]); - const openFileSurface = useCallback( - (relativePath: string) => { - if (!activeThreadRef || !activeProject) return; - useRightPanelStore.getState().openFile(activeThreadRef, relativePath); - }, - [activeProject, activeThreadRef], - ); + const openFileSurface = (relativePath: string) => { + if (!activeThreadRef || !activeProject) return; + useRightPanelStore.getState().openFile(activeThreadRef, relativePath); + }; + const openFileSurfaceStable = useStableCallback(openFileSurface); // The thread's own change request, placed against the project it belongs to. Without a // project there is nothing to resolve it against, so the caller falls back to the browser. const persistedLinkedThreadPullRequest = isServerThread @@ -5949,7 +5856,7 @@ export default function ChatView(props: ChatViewProps) { shouldUsePlanSidebarSheet, threadDetailLoading, ]); - const closePreviewPanel = useCallback(() => { + const closePreviewPanel = () => { if (activeThreadRef) { // Closing the panel on a live browser or device floats it instead of dropping it. if (activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId) { @@ -5964,8 +5871,9 @@ export default function ChatView(props: ChatViewProps) { useRightPanelStore.getState().setMaximized(activeThreadRef, false); useRightPanelStore.getState().close(activeThreadRef); } - }, [activeRightPanelSurface, activeThreadRef]); - const togglePreviewPanel = useCallback(() => { + }; + const closePreviewPanelStable = useStableCallback(closePreviewPanel); + const togglePreviewPanel = () => { if (!activeThreadRef || !browserAvailable) return; if (previewPanelOpen) { closePreviewPanel(); @@ -5978,16 +5886,9 @@ export default function ChatView(props: ChatViewProps) { } else { createBrowserSurface(); } - }, [ - activePreviewState.activeTabId, - activeThreadRef, - browserAvailable, - canOperatePreview, - closePreviewPanel, - createBrowserSurface, - previewPanelOpen, - ]); - const addTerminalSurface = useCallback(() => { + }; + const togglePreviewPanelStable = useStableCallback(togglePreviewPanel); + const addTerminalSurface = () => { if (!hasTerminalWriteAccess() || !activeThreadRef || !activeThreadId || !activeProject) return; const cwd = gitCwd ?? activeProject.workspaceRoot; const terminalId = allocateTerminalId(); @@ -6006,151 +5907,118 @@ export default function ChatView(props: ChatViewProps) { }), }, }); - }, [ - activeProject, - activeThreadId, - activeThreadRef, - activeThreadWorktreePath, - allocateTerminalId, - gitCwd, - openTerminal, - hasTerminalWriteAccess, - ]); - const splitPanelTerminal = useCallback( - (direction: "horizontal" | "vertical" = "horizontal") => { - if ( - !hasTerminalWriteAccess() || - !activeThreadRef || - !activeThreadId || - !activeProject || - activeRightPanelSurface?.kind !== "terminal" || - activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP - ) { - return; - } - const terminalId = allocateTerminalId(); - const cwd = gitCwd ?? activeProject.workspaceRoot; - useRightPanelStore - .getState() - .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction); - setTerminalFocusRequestId((value) => value + 1); - void openTerminal({ - environmentId: activeThreadRef.environmentId, - input: { - threadId: activeThreadId, - terminalId, - cwd, - ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), - env: projectScriptRuntimeEnv({ - project: { cwd: activeProject.workspaceRoot }, - worktreePath: activeThreadWorktreePath, - }), - }, - }); - }, - [ - activeProject, - activeRightPanelSurface, - activeThreadId, - activeThreadRef, - activeThreadWorktreePath, - allocateTerminalId, - gitCwd, - openTerminal, - hasTerminalWriteAccess, - ], - ); - const splitPanelTerminalVertical = useCallback(() => { + }; + const addTerminalSurfaceStable = useStableCallback(addTerminalSurface); + const splitPanelTerminal = (direction: "horizontal" | "vertical" = "horizontal") => { + if ( + !hasTerminalWriteAccess() || + !activeThreadRef || + !activeThreadId || + !activeProject || + activeRightPanelSurface?.kind !== "terminal" || + activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP + ) { + return; + } + const terminalId = allocateTerminalId(); + const cwd = gitCwd ?? activeProject.workspaceRoot; + useRightPanelStore + .getState() + .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction); + setTerminalFocusRequestId((value) => value + 1); + void openTerminal({ + environmentId: activeThreadRef.environmentId, + input: { + threadId: activeThreadId, + terminalId, + cwd, + ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), + env: projectScriptRuntimeEnv({ + project: { cwd: activeProject.workspaceRoot }, + worktreePath: activeThreadWorktreePath, + }), + }, + }); + }; + const splitPanelTerminalStable = useStableCallback(splitPanelTerminal); + const splitPanelTerminalVertical = () => { splitPanelTerminal("vertical"); - }, [splitPanelTerminal]); - const activatePanelTerminal = useCallback( - (terminalId: string) => { - if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return; - useRightPanelStore - .getState() - .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); - setTerminalFocusRequestId((value) => value + 1); - }, - [activeRightPanelSurface, activeThreadRef], - ); - const closePanelTerminal = useCallback( - (terminalId: string) => { - if ( - !hasTerminalWriteAccess() || - !activeThreadRef || - activeRightPanelSurface?.kind !== "terminal" - ) - return; - void closeTerminalMutation({ - environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, - }); - storeCloseTerminal(activeThreadRef, terminalId); - useRightPanelStore - .getState() - .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); - setTerminalFocusRequestId((value) => value + 1); - }, - [ - hasTerminalWriteAccess, - activeRightPanelSurface, - activeThreadRef, - closeTerminalMutation, - storeCloseTerminal, - ], - ); - const requestCloseTerminal = useCallback( - (terminalId: string) => { - if (!hasTerminalWriteAccess()) return; - const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId); - void confirmTerminalClose([label]).then((confirmed) => { - if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { - closeTerminal(terminalId); - } - }); - }, - [hasTerminalWriteAccess, activeTerminalLabelsById, closeTerminal, environmentId], - ); - const requestClosePanelTerminal = useCallback( - (terminalId: string) => { - if (!hasTerminalWriteAccess()) return; - const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId); - void confirmTerminalClose([label]).then((confirmed) => { - if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { - closePanelTerminal(terminalId); - } - }); - }, - [hasTerminalWriteAccess, activeTerminalLabelsById, closePanelTerminal, environmentId], - ); - const activateRightPanelSurface = useCallback( - (surface: RightPanelSurface) => { - if (!activeThreadRef) return; - useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); - if (surface.kind === "preview" && surface.resourceId) { - setActivePreviewTab(activeThreadRef, surface.resourceId); - } - if (surface.kind === "terminal") { - setTerminalFocusRequestId((value) => value + 1); + }; + const splitPanelTerminalVerticalStable = useStableCallback(splitPanelTerminalVertical); + const activatePanelTerminal = (terminalId: string) => { + if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return; + useRightPanelStore + .getState() + .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); + setTerminalFocusRequestId((value) => value + 1); + }; + const activatePanelTerminalStable = useStableCallback(activatePanelTerminal); + const closePanelTerminal = (terminalId: string) => { + if ( + !hasTerminalWriteAccess() || + !activeThreadRef || + activeRightPanelSurface?.kind !== "terminal" + ) + return; + void closeTerminalMutation({ + environmentId: activeThreadRef.environmentId, + input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, + }); + storeCloseTerminal(activeThreadRef, terminalId); + useRightPanelStore + .getState() + .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); + setTerminalFocusRequestId((value) => value + 1); + }; + const closePanelTerminalStable = useStableCallback(closePanelTerminal); + const requestCloseTerminal = (terminalId: string) => { + if (!hasTerminalWriteAccess()) return; + const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId); + void confirmTerminalClose([label]).then((confirmed) => { + if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { + closeTerminal(terminalId); } - if (surface.kind === "diff" && !diffOpen) { - onDiffPanelOpen?.(); + }); + }; + const requestCloseTerminalStable = useStableCallback(requestCloseTerminal); + const requestClosePanelTerminal = (terminalId: string) => { + if (!hasTerminalWriteAccess()) return; + const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId); + void confirmTerminalClose([label]).then((confirmed) => { + if (confirmed && readEnvironmentScope(environmentId, AuthTerminalOperateScope)) { + closePanelTerminal(terminalId); } - }, - [activeThreadRef, diffOpen, onDiffPanelOpen], - ); - const toggleRightPanel = useCallback(() => { + }); + }; + const requestClosePanelTerminalStable = useStableCallback(requestClosePanelTerminal); + const activateRightPanelSurface = (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); + if (surface.kind === "preview" && surface.resourceId) { + setActivePreviewTab(activeThreadRef, surface.resourceId); + } + if (surface.kind === "terminal") { + setTerminalFocusRequestId((value) => value + 1); + } + if (surface.kind === "diff" && !diffOpen) { + onDiffPanelOpen?.(); + } + }; + const activateRightPanelSurfaceStable = useStableCallback(activateRightPanelSurface); + const toggleRightPanel = () => { if (!activeThreadRef) return; if (rightPanelOpen) { closePreviewPanel(); return; } useRightPanelStore.getState().toggleVisibility(activeThreadRef); - }, [activeThreadRef, closePreviewPanel, rightPanelOpen]); - const toggleThreadPanel = useCallback(() => { + }; + const toggleRightPanelStable = useStableCallback(toggleRightPanel); + const toggleThreadPanel = () => { if (!activeThreadRef) return; useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation); - }, [activeThreadRef, threadPanelPresentation]); + }; + const toggleThreadPanelStable = useStableCallback(toggleThreadPanel); // A thread started for a link the OS opened shows its browser maximized, like a browser window. useEffect(() => { if (!canMaximizeRightPanel) return; @@ -6158,70 +6026,61 @@ export default function ChatView(props: ChatViewProps) { useRightPanelStore.getState().setMaximized(routeThreadRef, true); } }, [canMaximizeRightPanel, routeThreadRef]); - const toggleRightPanelMaximized = useCallback(() => { + const toggleRightPanelMaximized = () => { if (!canMaximizeRightPanel || !activeThreadRef) return; useRightPanelStore.getState().setMaximized(activeThreadRef, !rightPanelMaximized); - }, [activeThreadRef, canMaximizeRightPanel, rightPanelMaximized]); - const cleanupRightPanelSurfaces = useCallback( - (surfaces: readonly RightPanelSurface[]) => { - if (!activeThreadRef) return; - for (const surface of surfaces) { - // Without preview access only the local surface goes away. The - // server record is in-memory bookkeeping, not a live view, and stays - // listed until a client with the scope closes it or the server restarts. - if (canOperatePreview && surface.kind === "preview" && surface.resourceId) { - void closePreviewSession({ - closePreview, - snapshot: activePreviewState.sessions[surface.resourceId] ?? null, - tabId: surface.resourceId, - threadRef: activeThreadRef, + }; + const toggleRightPanelMaximizedStable = useStableCallback(toggleRightPanelMaximized); + const cleanupRightPanelSurfaces = (surfaces: readonly RightPanelSurface[]) => { + if (!activeThreadRef) return; + for (const surface of surfaces) { + // Without preview access only the local surface goes away. The + // server record is in-memory bookkeeping, not a live view, and stays + // listed until a client with the scope closes it or the server restarts. + if (canOperatePreview && surface.kind === "preview" && surface.resourceId) { + void closePreviewSession({ + closePreview, + snapshot: activePreviewState.sessions[surface.resourceId] ?? null, + tabId: surface.resourceId, + threadRef: activeThreadRef, + }); + } + if ( + surface.kind === "terminal" && + readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope) + ) { + for (const terminalId of surface.terminalIds) { + storeCloseTerminal(activeThreadRef, terminalId); + void closeTerminalMutation({ + environmentId: activeThreadRef.environmentId, + input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, }); } - if ( - surface.kind === "terminal" && - readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope) - ) { - for (const terminalId of surface.terminalIds) { - storeCloseTerminal(activeThreadRef, terminalId); - void closeTerminalMutation({ - environmentId: activeThreadRef.environmentId, - input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, - }); - } - } - } - }, - [ - activeThreadRef, - activePreviewState.sessions, - canOperatePreview, - closePreview, - closeTerminalMutation, - storeCloseTerminal, - ], - ); - const closeAfterAgentBrowserConfirmation = useCallback( - (surfaces: readonly RightPanelSurface[], closeSurfaces: () => void) => { - const message = agentControlledBrowserCloseConfirmation( - surfaces, - activePreviewState.desktopByTabId, - ); - if (!message) { - closeSurfaces(); - return; } - const localApi = readLocalApi(); - if (!localApi) return; - void localApi.dialogs.confirm(message, { variant: "destructive" }).then( - (confirmed) => { - if (confirmed) closeSurfaces(); - }, - () => undefined, - ); - }, - [activePreviewState.desktopByTabId], - ); - const syncActivePreviewSurface = useCallback(() => { + } + }; + const closeAfterAgentBrowserConfirmation = ( + surfaces: readonly RightPanelSurface[], + closeSurfaces: () => void, + ) => { + const message = agentControlledBrowserCloseConfirmation( + surfaces, + activePreviewState.desktopByTabId, + ); + if (!message) { + closeSurfaces(); + return; + } + const localApi = readLocalApi(); + if (!localApi) return; + void localApi.dialogs.confirm(message, { variant: "destructive" }).then( + (confirmed) => { + if (confirmed) closeSurfaces(); + }, + () => undefined, + ); + }; + const syncActivePreviewSurface = () => { if (!activeThreadRef) return; const nextActiveSurface = selectActiveRightPanelSurface( useRightPanelStore.getState().byThreadKey, @@ -6230,110 +6089,80 @@ export default function ChatView(props: ChatViewProps) { if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) { setActivePreviewTab(activeThreadRef, nextActiveSurface.resourceId); } - }, [activeThreadRef]); - const finishRightPanelSurfaceClose = useCallback( - (surfaces: readonly RightPanelSurface[]) => { - if (!activeThreadRef) return; - const store = useRightPanelStore.getState(); - const activeId = selectThreadRightPanelState( - store.byThreadKey, - activeThreadRef, - ).activeSurfaceId; - const ordered = surfaces.toSorted( - (left, right) => Number(left.id === activeId) - Number(right.id === activeId), + }; + const finishRightPanelSurfaceClose = (surfaces: readonly RightPanelSurface[]) => { + if (!activeThreadRef) return; + const store = useRightPanelStore.getState(); + const activeId = selectThreadRightPanelState( + store.byThreadKey, + activeThreadRef, + ).activeSurfaceId; + const ordered = surfaces.toSorted( + (left, right) => Number(left.id === activeId) - Number(right.id === activeId), + ); + for (const surface of ordered) { + cleanupRightPanelSurfaces([surface]); + store.closeSurface(activeThreadRef, surface.id); + } + syncActivePreviewSurface(); + }; + const closeRightPanelSurface = (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + const finishClose = () => finishRightPanelSurfaceClose([surface]); + if (surface.kind === "preview") { + closeAfterAgentBrowserConfirmation([surface], finishClose); + return; + } + if ( + surface.kind !== "terminal" || + !readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope) + ) { + finishClose(); + return; + } + const activeLabel = + activeTerminalLabelsById.get(surface.activeTerminalId) ?? + getTerminalLabel(surface.activeTerminalId); + const otherLabels = surface.terminalIds + .filter((terminalId) => terminalId !== surface.activeTerminalId) + .map( + (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId), ); - for (const surface of ordered) { - cleanupRightPanelSurfaces([surface]); - store.closeSurface(activeThreadRef, surface.id); - } - syncActivePreviewSurface(); - }, - [activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface], - ); - const closeRightPanelSurface = useCallback( - (surface: RightPanelSurface) => { - if (!activeThreadRef) return; - const finishClose = () => finishRightPanelSurfaceClose([surface]); - if (surface.kind === "preview") { - closeAfterAgentBrowserConfirmation([surface], finishClose); - return; - } - if ( - surface.kind !== "terminal" || - !readEnvironmentScope(activeThreadRef.environmentId, AuthTerminalOperateScope) - ) { + void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => { + if (confirmed) { finishClose(); - return; } - const activeLabel = - activeTerminalLabelsById.get(surface.activeTerminalId) ?? - getTerminalLabel(surface.activeTerminalId); - const otherLabels = surface.terminalIds - .filter((terminalId) => terminalId !== surface.activeTerminalId) - .map( - (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId), - ); - void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => { - if (confirmed) { - finishClose(); - } - }); - }, - [ - activeThreadRef, - activeTerminalLabelsById, - closeAfterAgentBrowserConfirmation, - finishRightPanelSurfaceClose, - ], - ); - const closeOtherRightPanelSurfaces = useCallback( - (surface: RightPanelSurface) => { - if (!activeThreadRef) return; - const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id); - const finishClose = () => finishRightPanelSurfaceClose(surfaces); - closeAfterAgentBrowserConfirmation(surfaces, finishClose); - }, - [ - activeThreadRef, - closeAfterAgentBrowserConfirmation, - finishRightPanelSurfaceClose, - rightPanelState.surfaces, - ], - ); - const closeRightPanelSurfacesToRight = useCallback( - (surface: RightPanelSurface) => { - if (!activeThreadRef) return; - const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id); - if (surfaceIndex < 0) return; - const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1); - const finishClose = () => finishRightPanelSurfaceClose(surfaces); - closeAfterAgentBrowserConfirmation(surfaces, finishClose); - }, - [ - activeThreadRef, - closeAfterAgentBrowserConfirmation, - finishRightPanelSurfaceClose, - rightPanelState.surfaces, - ], - ); - const closeAllRightPanelSurfaces = useCallback(() => { + }); + }; + const closeRightPanelSurfaceStable = useStableCallback(closeRightPanelSurface); + const closeOtherRightPanelSurfaces = (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id); + const finishClose = () => finishRightPanelSurfaceClose(surfaces); + closeAfterAgentBrowserConfirmation(surfaces, finishClose); + }; + const closeOtherRightPanelSurfacesStable = useStableCallback(closeOtherRightPanelSurfaces); + const closeRightPanelSurfacesToRight = (surface: RightPanelSurface) => { + if (!activeThreadRef) return; + const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id); + if (surfaceIndex < 0) return; + const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1); + const finishClose = () => finishRightPanelSurfaceClose(surfaces); + closeAfterAgentBrowserConfirmation(surfaces, finishClose); + }; + const closeRightPanelSurfacesToRightStable = useStableCallback(closeRightPanelSurfacesToRight); + const closeAllRightPanelSurfaces = () => { if (!activeThreadRef) return; const finishClose = () => finishRightPanelSurfaceClose(rightPanelState.surfaces); closeAfterAgentBrowserConfirmation(rightPanelState.surfaces, finishClose); - }, [ - activeThreadRef, - closeAfterAgentBrowserConfirmation, - finishRightPanelSurfaceClose, - rightPanelState.surfaces, - ]); - const moveRightPanelSurface = useCallback( - (surfaceId: string, toIndex: number) => { - if (activeThreadRef) - useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex); - }, - [activeThreadRef], - ); - const copyRightPanelFilePath = useCallback((relativePath: string) => { + }; + const closeAllRightPanelSurfacesStable = useStableCallback(closeAllRightPanelSurfaces); + const moveRightPanelSurface = (surfaceId: string, toIndex: number) => { + if (activeThreadRef) + useRightPanelStore.getState().moveSurface(activeThreadRef, surfaceId, toIndex); + }; + const moveRightPanelSurfaceStable = useStableCallback(moveRightPanelSurface); + const copyRightPanelFilePath = (relativePath: string) => { if (typeof window === "undefined" || !navigator.clipboard?.writeText) { toastManager.add( stackedThreadToast({ @@ -6363,88 +6192,80 @@ export default function ChatView(props: ChatViewProps) { ); }, ); - }, []); + }; + const copyRightPanelFilePathStable = useStableCallback(copyRightPanelFilePath); useEffect( () => subscribePreviewAction((action) => { - if (action === "toggle-panel") togglePreviewPanel(); + if (action === "toggle-panel") togglePreviewPanelStable(); }), - [togglePreviewPanel], + [togglePreviewPanelStable], ); - const persistThreadSettingsForNextTurn = useCallback( - async (input: { - threadId: ThreadId; - createdAt: string; - branch?: string; - runtimeMode: RuntimeMode; - interactionMode: ProviderInteractionMode; - }): Promise> => { - if (!serverThread) { - return AsyncResult.success(undefined); - } - - let result: AtomCommandResult = AsyncResult.success(undefined); - const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({ - currentModelSelection: serverThread.modelSelection, - currentBranch: serverThread.branch, - ...(input.branch ? { nextBranch: input.branch } : {}), - }); - if (metadataUpdate) { - result = mapAtomCommandResult( - await updateThreadMetadata({ - environmentId, - input: { - threadId: input.threadId, - ...metadataUpdate, - }, - }), - () => undefined, - ); - if (result._tag === "Failure") { - return result; - } + const persistThreadSettingsForNextTurn = async (input: { + threadId: ThreadId; + createdAt: string; + branch?: string; + runtimeMode: RuntimeMode; + interactionMode: ProviderInteractionMode; + }): Promise> => { + if (!serverThread) { + return AsyncResult.success(undefined); + } + + let result: AtomCommandResult = AsyncResult.success(undefined); + const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({ + currentModelSelection: serverThread.modelSelection, + currentBranch: serverThread.branch, + ...(input.branch ? { nextBranch: input.branch } : {}), + }); + if (metadataUpdate) { + result = mapAtomCommandResult( + await updateThreadMetadata({ + environmentId, + input: { + threadId: input.threadId, + ...metadataUpdate, + }, + }), + () => undefined, + ); + if (result._tag === "Failure") { + return result; } + } - if (input.runtimeMode !== serverThread.runtimeMode) { - result = mapAtomCommandResult( - await setThreadRuntimeMode({ - environmentId, - input: { - threadId: input.threadId, - runtimeMode: input.runtimeMode, - createdAt: input.createdAt, - }, - }), - () => undefined, - ); - if (result._tag === "Failure") { - return result; - } + if (input.runtimeMode !== serverThread.runtimeMode) { + result = mapAtomCommandResult( + await setThreadRuntimeMode({ + environmentId, + input: { + threadId: input.threadId, + runtimeMode: input.runtimeMode, + createdAt: input.createdAt, + }, + }), + () => undefined, + ); + if (result._tag === "Failure") { + return result; } + } - if (input.interactionMode !== serverThread.interactionMode) { - result = mapAtomCommandResult( - await setThreadInteractionMode({ - environmentId, - input: { - threadId: input.threadId, - interactionMode: input.interactionMode, - createdAt: input.createdAt, - }, - }), - () => undefined, - ); - } - return result; - }, - [ - environmentId, - serverThread, - setThreadInteractionMode, - setThreadRuntimeMode, - updateThreadMetadata, - ], - ); + if (input.interactionMode !== serverThread.interactionMode) { + result = mapAtomCommandResult( + await setThreadInteractionMode({ + environmentId, + input: { + threadId: input.threadId, + interactionMode: input.interactionMode, + createdAt: input.createdAt, + }, + }), + () => undefined, + ); + } + return result; + }; // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during // thread switches. LegendList fires scroll events with isAtEnd=false while @@ -6472,7 +6293,7 @@ export default function ChatView(props: ChatViewProps) { readonly userScrollGeneration: number; } | null>(null); const anchorScrollRestoreFrameRef = useRef(null); - const cancelTimelineLiveFollowForUserNavigation = useCallback(() => { + const cancelTimelineLiveFollowForUserNavigation = () => { cancelPositionRestoreRef.current?.(); anchorUserScrollGenerationRef.current += 1; const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling"; @@ -6512,14 +6333,17 @@ export default function ChatView(props: ChatViewProps) { scrollNode.scrollTop = currentScrollTop; } } - }, []); - const cancelTimelineLiveFollowForUserNavigationRef = useRef( + }; + const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback( cancelTimelineLiveFollowForUserNavigation, ); + const cancelTimelineLiveFollowForUserNavigationRef = useRef( + cancelTimelineLiveFollowForUserNavigationStable, + ); useEffect(() => { cancelTimelineLiveFollowForUserNavigationRef.current = - cancelTimelineLiveFollowForUserNavigation; - }, [cancelTimelineLiveFollowForUserNavigation]); + cancelTimelineLiveFollowForUserNavigationStable; + }, [cancelTimelineLiveFollowForUserNavigationStable]); useEffect(() => { const previous = observedTimelineActivityRef.current; const dispatchedUserItem = @@ -6557,13 +6381,13 @@ export default function ChatView(props: ChatViewProps) { setShowScrollToBottom(false); setTimelineAnchor({ threadKey: activeThreadKey, messageId }); }, [activeActivityRun, activeThreadKey, isServerThread, serverProjection, threadStatus]); - const timelineRealContentOverflowsViewport = useCallback( - (list?: LegendListRef | null) => - timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), { - composerInset: composerTimelineInset, - anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET, - }), - [composerTimelineInset], + const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) => + timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), { + composerInset: composerTimelineInset, + anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET, + }); + const timelineRealContentOverflowsViewportStable = useStableCallback( + timelineRealContentOverflowsViewport, ); const pageScrollControllerRef = useRef | null>( null, @@ -6571,8 +6395,11 @@ export default function ChatView(props: ChatViewProps) { const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => { timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end"; composerRef.current?.collapseForTimelineScrollKey(key); - if ((key === "PageUp" && timelineRealContentOverflowsViewport()) || !isTimelineAtLogicalEnd()) { - cancelTimelineLiveFollowForUserNavigation(); + if ( + (key === "PageUp" && timelineRealContentOverflowsViewportStable()) || + !isTimelineAtLogicalEndStable() + ) { + cancelTimelineLiveFollowForUserNavigationStable(); } }); useEffect(() => { @@ -6590,18 +6417,21 @@ export default function ChatView(props: ChatViewProps) { } }; }, [composerOverlayElement]); - const onComposerPageScrollKeyDown = useCallback((key: PageScrollKey) => { + const onComposerPageScrollKeyDown = (key: PageScrollKey) => { pageScrollControllerRef.current?.handleKeyDown(key); - }, []); - const onComposerPageScrollKeyUp = useCallback((key: string) => { + }; + const onComposerPageScrollKeyDownStable = useStableCallback(onComposerPageScrollKeyDown); + const onComposerPageScrollKeyUp = (key: string) => { pageScrollControllerRef.current?.handleKeyUp(key); - }, []); - const onComposerPageScrollRelease = useCallback(() => { + }; + const onComposerPageScrollKeyUpStable = useStableCallback(onComposerPageScrollKeyUp); + const onComposerPageScrollRelease = () => { pageScrollControllerRef.current?.releaseActiveKey(); - }, []); + }; + const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease); // Live-follow stays active after send/thread-open until an actual list scroll // gesture opts out. - const scrollToEnd = useCallback((animated = false) => { + const scrollToEnd = (animated: boolean = false) => { cancelPositionRestoreRef.current?.(); isAtEndRef.current = true; timelineScrollModeRef.current = "following-end"; @@ -6617,7 +6447,8 @@ export default function ChatView(props: ChatViewProps) { requestAnimationFrame(() => { void legendListRef.current?.scrollToEnd?.({ animated }); }); - }, []); + }; + const scrollToEndStable = useStableCallback(scrollToEnd); useEffect(() => { let removeListeners: (() => void) | null = null; let frame: number | null = null; @@ -6642,7 +6473,7 @@ export default function ChatView(props: ChatViewProps) { // while pinned at the end produces no scroll event, never re-arms, // and streaming silently stops following. Underflowing content can't // scroll at all, so nothing there should break follow. - const contentScrollsUp = () => timelineRealContentOverflowsViewport(); + const contentScrollsUp = () => timelineRealContentOverflowsViewportStable(); // The follow re-arm band, not the strict flag: streaming growth makes // isAtEnd flicker false for a frame before the follow scroll catches // up, and a gesture landing in that window while still pinned would @@ -6738,7 +6569,7 @@ export default function ChatView(props: ChatViewProps) { handleManualNavigation(); } composerRef.current?.collapseForTimelineScrollKey(event.key); - if (isTimelineAtLogicalEnd()) { + if (isTimelineAtLogicalEndStable()) { composerRef.current?.restoreAfterTimelineReachedEnd(); } break; @@ -6772,9 +6603,9 @@ export default function ChatView(props: ChatViewProps) { } removeListeners?.(); }; - }, [activeThread?.id, isTimelineAtLogicalEnd, timelineRealContentOverflowsViewport]); + }, [activeThread?.id, isTimelineAtLogicalEndStable, timelineRealContentOverflowsViewportStable]); - const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => { + const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => { if (pendingTimelineAnchorRef.current === messageId) { pendingTimelineAnchorRef.current = null; } @@ -6823,8 +6654,9 @@ export default function ChatView(props: ChatViewProps) { }); }; requestAnimationFrame(() => positionAnchor(12)); - }, []); - const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => { + }; + const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady); + const onTimelineAnchorSizeChanged = (messageId: MessageId) => { if (settledTimelineAnchorRef.current !== messageId) { return; } @@ -6864,13 +6696,15 @@ export default function ChatView(props: ChatViewProps) { } } }); - }, []); + }; + const onTimelineAnchorSizeChangedStable = useStableCallback(onTimelineAnchorSizeChanged); - const onToolOutputCollapsedAtEnd = useCallback(() => { + const onToolOutputCollapsedAtEnd = () => { composerRef.current?.restoreAfterTimelineReachedEnd(); - }, [composerRef]); + }; + const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd); - const onIsAtEndChange = useCallback((isAtEnd: boolean) => { + const onIsAtEndChange = (isAtEnd: boolean) => { if ( !isAtEnd && liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current @@ -6900,7 +6734,8 @@ export default function ChatView(props: ChatViewProps) { liveFollowUserScrollGenerationRef.current = null; showScrollDebouncer.current.maybeExecute(); } - }, []); + }; + const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange); useLayoutEffect(() => { if (timelineScrollModeRef.current !== "anchoring-new-turn") return; @@ -6912,11 +6747,11 @@ export default function ChatView(props: ChatViewProps) { timelineEntries, }) ) { - scrollToEnd(); + scrollToEndStable(); } }, [ activeRunningTurnId, - scrollToEnd, + scrollToEndStable, timelineAnchorMessageId, timelineEntries, timelineLiveFollowEnabled, @@ -6944,12 +6779,12 @@ export default function ChatView(props: ChatViewProps) { useEffect(() => { if (!activeThread?.id || terminalUiState.terminalOpen) return; const frame = window.requestAnimationFrame(() => { - focusComposer(); + focusComposerStable(); }); return () => { window.cancelAnimationFrame(frame); }; - }, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]); + }, [activeThread?.id, focusComposerStable, terminalUiState.terminalOpen]); // Tabbing back into the app lands focus wherever it last was, often the right panel or the // body. Put it in the composer unless something that takes typing already holds it. The @@ -6969,7 +6804,7 @@ export default function ChatView(props: ChatViewProps) { frame = null; // A full-screen app owns the page; refocusing the composer would close it. if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return; - if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposer(); + if (shouldRefocusComposerOnWindowFocus(document.activeElement)) focusComposerStable(); }); }); }; @@ -6978,7 +6813,7 @@ export default function ChatView(props: ChatViewProps) { window.removeEventListener("focus", onWindowFocus); if (frame !== null) window.cancelAnimationFrame(frame); }; - }, [activeThread?.id, focusComposer, isMobileViewport, terminalUiState.terminalOpen]); + }, [activeThread?.id, focusComposerStable, isMobileViewport, terminalUiState.terminalOpen]); useEffect(() => { if (!activeThread?.id) return; @@ -6999,7 +6834,7 @@ export default function ChatView(props: ChatViewProps) { for (const removedMessage of removedMessages) { const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage); if (previewUrls.length > 0) { - handoffAttachmentPreviews(removedMessage.id, previewUrls); + handoffAttachmentPreviewsStable(removedMessage.id, previewUrls); continue; } revokeUserMessagePreviewUrls(removedMessage); @@ -7011,7 +6846,7 @@ export default function ChatView(props: ChatViewProps) { activeMessageCount, activeThread?.id, serverAcknowledgedUserMessageIds, - handoffAttachmentPreviews, + handoffAttachmentPreviewsStable, optimisticUserMessages, ]); @@ -7029,9 +6864,10 @@ export default function ChatView(props: ChatViewProps) { setExpandedImage(null); }, [resetLocalDispatch, threadId]); - const closeExpandedImage = useCallback(() => { + const closeExpandedImage = () => { setExpandedImage(null); - }, []); + }; + const closeExpandedImageStable = useStableCallback(closeExpandedImage); const activeWorktreePath = activeThread?.worktreePath ?? null; const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({ @@ -7076,87 +6912,86 @@ export default function ChatView(props: ChatViewProps) { : null, [activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread], ); - const publishComposerOverlayHeight = useCallback( - (height: number) => { - const nextHeight = Math.ceil(height); - if (nextHeight <= 0) return; - const isResting = overlayComposerIsResting({ - composerMounted: composerMountedRef.current, - composerReportedResting: composerRestingRef.current, - }); - const modelStrip = composerOverlayElement?.querySelector( - '[data-composer-model-strip="true"]', - ); - // The model-only strip disappears on expansion; counting it again would - // add 32px of timeline padding as soon as the empty composer collapses. - const restingOnlyHeight = - modelStrip && isResting - ? Math.max( - 0, - modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop), - ) - : 0; - const nextInset = resolveComposerTimelineInset({ - currentInset: composerTimelineInsetRef.current, - overlayHeight: nextHeight, - isResting, - restingOnlyHeight, - }); - if (composerTimelineInsetRef.current !== nextInset) { - composerTimelineInsetRef.current = nextInset; - setComposerTimelineInset(nextInset); - } - const mainSurface = composerOverlayElement?.querySelector( - '[data-chat-composer-main-surface="true"]', - ); - const button = composerOverlayElement?.parentElement?.querySelector( - 'button[aria-label="Scroll to end"]', - ); - const clearance = - composerOverlayElement && mainSurface && button - ? resolveScrollToEndClearance({ - overlayHeight: nextHeight, - mainSurfaceTop: mainSurface.getBoundingClientRect().top, - button: button.getBoundingClientRect(), - attachments: Array.from( - composerOverlayElement.querySelectorAll( - '[data-composer-banner-surface="attached"]', - ), - (element) => element.getBoundingClientRect(), + const publishComposerOverlayHeight = (height: number) => { + const nextHeight = Math.ceil(height); + if (nextHeight <= 0) return; + const isResting = overlayComposerIsResting({ + composerMounted: composerMountedRef.current, + composerReportedResting: composerRestingRef.current, + }); + const modelStrip = composerOverlayElement?.querySelector( + '[data-composer-model-strip="true"]', + ); + // The model-only strip disappears on expansion; counting it again would + // add 32px of timeline padding as soon as the empty composer collapses. + const restingOnlyHeight = + modelStrip && isResting + ? Math.max( + 0, + modelStrip.offsetHeight + Number.parseFloat(getComputedStyle(modelStrip).marginTop), + ) + : 0; + const nextInset = resolveComposerTimelineInset({ + currentInset: composerTimelineInsetRef.current, + overlayHeight: nextHeight, + isResting, + restingOnlyHeight, + }); + if (composerTimelineInsetRef.current !== nextInset) { + composerTimelineInsetRef.current = nextInset; + setComposerTimelineInset(nextInset); + } + const mainSurface = composerOverlayElement?.querySelector( + '[data-chat-composer-main-surface="true"]', + ); + const button = composerOverlayElement?.parentElement?.querySelector( + 'button[aria-label="Scroll to end"]', + ); + const clearance = + composerOverlayElement && mainSurface && button + ? resolveScrollToEndClearance({ + overlayHeight: nextHeight, + mainSurfaceTop: mainSurface.getBoundingClientRect().top, + button: button.getBoundingClientRect(), + attachments: Array.from( + composerOverlayElement.querySelectorAll( + '[data-composer-banner-surface="attached"]', ), - }) - : nextHeight; - setScrollToEndClearance(clearance); - }, - [composerOverlayElement], - ); + (element) => element.getBoundingClientRect(), + ), + }) + : nextHeight; + setScrollToEndClearance(clearance); + }; + const publishComposerOverlayHeightStable = useStableCallback(publishComposerOverlayHeight); // The composer reports its resting flag from a layout effect, which runs // before this component's own layout effects and before any resize // observation, so every measurement below sees the flag for its layout. // Only the flag is stored here: the stored height still belongs to the // previous layout, and the composer publishes the new layout's height // itself once it has measured it. - const onComposerRestingChange = useCallback((resting: boolean) => { + const onComposerRestingChange = (resting: boolean) => { composerRestingRef.current = resting; - }, []); + }; + const onComposerRestingChangeStable = useStableCallback(onComposerRestingChange); // A held reservation belongs to the previous thread's draft. Rebuild it from // this thread's overlay so a tall draft elsewhere does not pad this one. useLayoutEffect(() => { if (!composerOverlayElement) return; composerTimelineInsetRef.current = 0; - publishComposerOverlayHeight(composerOverlayElement.getBoundingClientRect().height); - }, [activeThreadKey, composerOverlayElement, publishComposerOverlayHeight]); + publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height); + }, [activeThreadKey, composerOverlayElement, publishComposerOverlayHeightStable]); useLayoutEffect(() => { if (!composerOverlayElement) return; const updateHeight = () => { - publishComposerOverlayHeight(composerOverlayElement.getBoundingClientRect().height); + publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height); }; updateHeight(); return observeResize(composerOverlayElement, updateHeight); - }, [composerOverlayElement, publishComposerOverlayHeight, showScrollToBottom]); + }, [composerOverlayElement, publishComposerOverlayHeightStable, showScrollToBottom]); // Swapping the composer for the status bar (or back) changes what the // overlay holds, so rebuild the reservation from the new content. useLayoutEffect(() => { @@ -7164,8 +6999,8 @@ export default function ChatView(props: ChatViewProps) { composerMountedRef.current = composerMounted; if (!composerOverlayElement) return; composerTimelineInsetRef.current = 0; - publishComposerOverlayHeight(composerOverlayElement.getBoundingClientRect().height); - }, [composerMounted, composerOverlayElement, publishComposerOverlayHeight]); + publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height); + }, [composerMounted, composerOverlayElement, publishComposerOverlayHeightStable]); const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef); const activeThreadReferenceCopyTarget = useMemo( () => @@ -7185,7 +7020,7 @@ export default function ChatView(props: ChatViewProps) { openPanelPullRequestUrl, ], ); - const copyActiveThreadReference = useCallback(() => { + const copyActiveThreadReference = () => { const target = activeThreadReferenceCopyTarget; if (target === null) return; void writeTextToClipboard(target.value, target.clipboardTarget).then( @@ -7208,7 +7043,8 @@ export default function ChatView(props: ChatViewProps) { ); }, ); - }, [activeThreadReferenceCopyTarget]); + }; + const copyActiveThreadReferenceStable = useStableCallback(copyActiveThreadReference); const pullRequestPanelTarget = activeThread ? threadPullRequestPanelTarget({ projectId: activeThread.projectId, @@ -7217,11 +7053,12 @@ export default function ChatView(props: ChatViewProps) { branchPullRequest: activeThreadShell?.branchPullRequest ?? activeThread.branchPullRequest, }) : null; - const addPullRequestSurface = useCallback(() => { + const addPullRequestSurface = () => { if (!supportsPullRequests || activeThreadRef === null || pullRequestPanelTarget === null) return; useRightPanelStore.getState().openPullRequest(activeThreadRef, pullRequestPanelTarget); - }, [activeThreadRef, pullRequestPanelTarget, supportsPullRequests]); + }; + const addPullRequestSurfaceStable = useStableCallback(addPullRequestSurface); const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null; const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true; const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; @@ -7248,10 +7085,11 @@ export default function ChatView(props: ChatViewProps) { ? threadWokeAt(activeThreadShell, { now: new Date().toISOString() }) : null; const acknowledgeThreadWoke = useAcknowledgeThreadWoke(); - const acknowledgeActiveThreadWoke = useCallback(() => { + const acknowledgeActiveThreadWoke = () => { if (activeThreadRef === null || activeThreadWokeAt === null) return; acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt); - }, [acknowledgeThreadWoke, activeThreadRef, activeThreadWokeAt]); + }; + const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke); // Mirror of the sidebar's Woke pill for the open thread. Same watermark as // the sidebar, so an acknowledgement from any device hides it. const activeThreadLocalVisitedAt = useUiStateStore((store) => @@ -7296,7 +7134,7 @@ export default function ChatView(props: ChatViewProps) { // must never clear (or re-enable) thread B's button. const [unsettlingThreadKey, setUnsettlingThreadKey] = useState(null); const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey; - const handleUnsettleActiveThread = useCallback(async () => { + const handleUnsettleActiveThread = async () => { if ( !activeThreadRef || !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) @@ -7322,13 +7160,14 @@ export default function ChatView(props: ChatViewProps) { } finally { setUnsettlingThreadKey((current) => (current === threadKey ? null : current)); } - }, [activeThreadRef, unsettleThreadMutation]); + }; + const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread); const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, { reportFailure: false, }); const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState(null); const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey; - const handleUnsnoozeActiveThread = useCallback(async () => { + const handleUnsnoozeActiveThread = async () => { if ( !activeThreadRef || !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) @@ -7368,7 +7207,8 @@ export default function ChatView(props: ChatViewProps) { } finally { setUnsnoozingThreadKey((current) => (current === threadKey ? null : current)); } - }, [activeThreadRef, activeThreadShell, unsnoozeThreadMutation, updateThreadMetadata]); + }; + const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread); const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false); const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false); // Once revealed for a given mismatch, the banner stays mounted until the @@ -7402,7 +7242,7 @@ export default function ChatView(props: ChatViewProps) { return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed; }); }, [activeBranchMismatchKey, showBranchMismatchBanner]); - const handleSwitchCheckoutToThread = useCallback(async () => { + const handleSwitchCheckoutToThread = async () => { if (!canWriteSourceControl) return; if ( !activeProjectCwd || @@ -7462,18 +7302,7 @@ export default function ChatView(props: ChatViewProps) { gitStatusQuery.refresh(); setIsRestoringThreadBranch(false); scheduleComposerFocus(); - }, [ - canWriteSourceControl, - activeProjectCwd, - activeThread, - environmentId, - gitStatusQuery, - isRestoringThreadBranch, - localCheckoutBranchMismatch, - scheduleComposerFocus, - switchGitRef, - updateThreadMetadata, - ]); + }; // The stack renders items[0] front-most and tucks the rest behind hover, so // ordering is priority: system banners, then the branch-mismatch notice, // and the informational parked-thread banner last — it must never cover another. @@ -7485,7 +7314,7 @@ export default function ChatView(props: ChatViewProps) { const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState(null); const isStoppingBackgroundWork = stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`; - const handleStopBackgroundWork = useCallback(async () => { + const handleStopBackgroundWork = async () => { if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return; const requestKey = `${environmentId}:${activeThread.id}`; @@ -7506,23 +7335,21 @@ export default function ChatView(props: ChatViewProps) { ); } } - }, [activeThread, environmentId, interruptThreadTurn, setThreadError]); - const onOpenRelatedThread = useCallback( - (threadId: ThreadId) => { - // Related threads live here, except a message Home sent from another environment. - const owner = serverThreadRefs.some( - (ref) => ref.environmentId === environmentId && ref.threadId === threadId, - ) - ? environmentId - : (serverThreadRefs.find((ref) => ref.threadId === threadId)?.environmentId ?? - environmentId); - void navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(scopeThreadRef(owner, threadId)), - }); - }, - [environmentId, navigate, serverThreadRefs], - ); + }; + const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork); + const onOpenRelatedThread = (threadId: ThreadId) => { + // Related threads live here, except a message Home sent from another environment. + const owner = serverThreadRefs.some( + (ref) => ref.environmentId === environmentId && ref.threadId === threadId, + ) + ? environmentId + : (serverThreadRefs.find((ref) => ref.threadId === threadId)?.environmentId ?? environmentId); + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(owner, threadId)), + }); + }; + const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread); const childThreadInputs = useChildThreadInputs(activeThreadRef); const childInputBannerItem = useMemo(() => { const first = childThreadInputs[0]; @@ -7533,22 +7360,22 @@ export default function ChatView(props: ChatViewProps) { id: `child-input:${first.id}`, variant: "info", priority: "activity", - icon: , - title: - childThreadInputs.length === 1 - ? "Subagent needs input" - : `${childThreadInputs.length} subagents need input`, + icon: first.hasPendingApprovals ? : , + title: childThreadInputsTitle(childThreadInputs), description: childThreadInputs.map((child, index) => ( - {index > 0 ? ", " : null} - onOpenRelatedThread(child.id)}> - {child.title} - + {index > 0 ? " " : null} + + onOpenRelatedThreadStable(child.id)}> + {child.title} + + {index < childThreadInputs.length - 1 ? "," : null} + )), actions: ( - ), }; @@ -7557,93 +7384,76 @@ export default function ChatView(props: ChatViewProps) { activePendingApproval, activePendingUserInput, activeThreadShell?.hasPendingUserInput, - onOpenRelatedThread, + onOpenRelatedThreadStable, ]); // Commands such as /compact and /goal clear run as their own turn. The draft - // and its attachments stay local. - const sendStandaloneCommand = useCallback( - async (text: string, failureMessage: string) => { - if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return; - const context = composerRef.current?.getSendContext(); - if (!context?.providerAvailable) return; - - const threadId = activeThread.id; - const messageId = newMessageId(); - const createdAt = new Date().toISOString(); - sendInFlightRef.current = true; - beginLocalDispatch(); - setThreadError(threadId, null); - setOptimisticUserMessages((messages) => [ - ...messages, - { - id: messageId, - role: "user", - text, - runId: null, - createdAt, - updatedAt: createdAt, - streaming: false, - }, - ]); - scrollToEnd(); - try { - const settingsResult = await persistThreadSettingsForNextTurn({ - threadId, - createdAt, - ...(localCheckoutBranchMismatch - ? { branch: localCheckoutBranchMismatch.currentBranch } - : {}), - runtimeMode, - interactionMode: context.interactionMode, - }); - const result = - settingsResult._tag === "Failure" - ? settingsResult - : await startThreadTurn({ - environmentId, - input: { - threadId, - message: { messageId, role: "user", text, attachments: [] }, - modelSelection: context.selectedModelSelection, - runtimeMode, - interactionMode: context.interactionMode, - createdAt, - }, - }); - if (result._tag === "Failure") { - setOptimisticUserMessages((messages) => - messages.filter((message) => message.id !== messageId), - ); - resetLocalDispatch(); - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError(threadId, error instanceof Error ? error.message : failureMessage); - } - } else { - clearUsageLimitsFor(routeThreadKey); + // and its attachments stay local. + const sendStandaloneCommand = async (text: string, failureMessage: string) => { + if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return; + const context = composerRef.current?.getSendContext(); + if (!context?.providerAvailable) return; + + const threadId = activeThread.id; + const messageId = newMessageId(); + const createdAt = new Date().toISOString(); + sendInFlightRef.current = true; + beginLocalDispatch(); + setThreadError(threadId, null); + setOptimisticUserMessages((messages) => [ + ...messages, + { + id: messageId, + role: "user", + text, + runId: null, + createdAt, + updatedAt: createdAt, + streaming: false, + }, + ]); + scrollToEnd(); + try { + const settingsResult = await persistThreadSettingsForNextTurn({ + threadId, + createdAt, + ...(localCheckoutBranchMismatch + ? { branch: localCheckoutBranchMismatch.currentBranch } + : {}), + runtimeMode, + interactionMode: context.interactionMode, + }); + const result = + settingsResult._tag === "Failure" + ? settingsResult + : await startThreadTurn({ + environmentId, + input: { + threadId, + message: { messageId, role: "user", text, attachments: [] }, + modelSelection: context.selectedModelSelection, + runtimeMode, + interactionMode: context.interactionMode, + createdAt, + }, + }); + if (result._tag === "Failure") { + setOptimisticUserMessages((messages) => + messages.filter((message) => message.id !== messageId), + ); + resetLocalDispatch(); + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError(threadId, error instanceof Error ? error.message : failureMessage); } - } finally { - sendInFlightRef.current = false; + } else { + clearUsageLimitsFor(routeThreadKey); } - }, - [ - activeThread, - beginLocalDispatch, - clientSettingsHydrated, - composerRef, - environmentId, - localCheckoutBranchMismatch, - persistThreadSettingsForNextTurn, - resetLocalDispatch, - routeThreadKey, - runtimeMode, - scrollToEnd, - sendInFlightRef, - setThreadError, - startThreadTurn, - ], - ); + } finally { + sendInFlightRef.current = false; + } + }; + const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand); // A native /goal keeps the agent working across turns. Stop pauses a Codex // goal; once the thread is idle the row offers the native follow-ups. const activeGoal = activeThreadShell?.goal ?? null; @@ -7667,7 +7477,9 @@ export default function ChatView(props: ChatViewProps) { @@ -7675,14 +7487,14 @@ export default function ChatView(props: ChatViewProps) { ), }; - }, [activeGoal, activeThread, isWorking, sendStandaloneCommand]); + }, [activeGoal, activeThread, isWorking, sendStandaloneCommandStable]); const backgroundWorkBannerItem = useMemo(() => { const presentation = presentPendingBackgroundWork(activeBackgroundTasks); @@ -7711,19 +7523,26 @@ export default function ChatView(props: ChatViewProps) { ? undefined : presentation.items.map((item, index) => { const childThreadId = item.childThreadId; + const separator = index < presentation.items.length - 1 ? "," : null; return ( - {index > 0 ? ", " : null} + {index > 0 ? " " : null} {childThreadId === undefined ? ( - item.label - ) : ( - onOpenRelatedThread(childThreadId)} - > + <> {item.label} - + {separator} + + ) : ( + + onOpenRelatedThreadStable(childThreadId)} + > + {item.label} + + {separator} + )} ); @@ -7733,7 +7552,7 @@ export default function ChatView(props: ChatViewProps) { size="xs" variant="ghost" disabled={!canOperateThread || isStoppingBackgroundWork} - onClick={() => void handleStopBackgroundWork()} + onClick={() => void handleStopBackgroundWorkStable()} > {isStoppingBackgroundWork ? "Stopping..." : "Stop"} @@ -7743,9 +7562,9 @@ export default function ChatView(props: ChatViewProps) { activeBackgroundTasks, activeThread, canOperateThread, - handleStopBackgroundWork, + handleStopBackgroundWorkStable, isStoppingBackgroundWork, - onOpenRelatedThread, + onOpenRelatedThreadStable, ]); // Settled, snoozed, and woke are thread state, not composer actions: each // gets one quiet line after the last message instead of a banner. A woken @@ -7766,7 +7585,7 @@ export default function ChatView(props: ChatViewProps) { } actionLabel={isUnsnoozing ? "Waking..." : "Wake now"} actionDisabled={!canOperateThread || isUnsnoozing} - onAction={() => void handleUnsnoozeActiveThread()} + onAction={() => void handleUnsnoozeActiveThreadStable()} /> ) : activeThreadSettled ? ( void handleUnsettleActiveThread()} + onAction={() => void handleUnsettleActiveThreadStable()} /> ) : activeThreadWokeVisible ? ( } label="Woke from snooze" actionLabel="Dismiss" - onAction={acknowledgeActiveThreadWoke} + onAction={acknowledgeActiveThreadWokeStable} /> ) : null; }, [ - acknowledgeActiveThreadWoke, + acknowledgeActiveThreadWokeStable, activeThreadSettled, activeThreadShell?.settledAt, activeThreadShell?.snoozedUntil, activeThreadSnoozed, activeThreadWokeVisible, canOperateThread, - handleUnsettleActiveThread, - handleUnsnoozeActiveThread, + handleUnsettleActiveThreadStable, + handleUnsnoozeActiveThreadStable, isUnsettling, isUnsnoozing, nowMinute, @@ -7874,7 +7693,7 @@ export default function ChatView(props: ChatViewProps) { () => new Set(), ); const keepFullHistory = fullHistoryThreadKeys.has(routeThreadKey); - const setKeepFullHistory = useCallback((threadKey: string, keep: boolean) => { + const setKeepFullHistory = (threadKey: string, keep: boolean) => { setFullHistoryThreadKeys((current) => { if (current.has(threadKey) === keep) return current; const next = new Set(current); @@ -7882,23 +7701,18 @@ export default function ChatView(props: ChatViewProps) { else next.delete(threadKey); return next; }); - }, []); - const toggleKeepFullHistory = useCallback( - () => setKeepFullHistory(routeThreadKey, !keepFullHistory), - [keepFullHistory, routeThreadKey, setKeepFullHistory], - ); - const handleRestoreThreadBranch = useCallback(() => { + }; + const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory); + const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory); + const handleRestoreThreadBranch = () => { if (!canWriteSourceControl) return; if (gitStatusQuery.data?.hasWorkingTreeChanges) { setBranchRestoreConfirmOpen(true); return; } void handleSwitchCheckoutToThread(); - }, [ - canWriteSourceControl, - gitStatusQuery.data?.hasWorkingTreeChanges, - handleSwitchCheckoutToThread, - ]); + }; + const handleRestoreThreadBranchStable = useStableCallback(handleRestoreThreadBranch); const feedbackBannerItems = useMemo( () => feedbackSubmissions.flatMap((submission) => { @@ -8001,7 +7815,7 @@ export default function ChatView(props: ChatViewProps) { size="xs" variant="ghost" disabled={!canWriteSourceControl || isRestoringThreadBranch} - onClick={handleRestoreThreadBranch} + onClick={handleRestoreThreadBranchStable} > {isRestoringThreadBranch ? "Restoring..." : "Restore branch"} @@ -8021,7 +7835,7 @@ export default function ChatView(props: ChatViewProps) { canWriteSourceControl, feedbackBannerItems, limitRecoveryBanner, - handleRestoreThreadBranch, + handleRestoreThreadBranchStable, isRestoringThreadBranch, backgroundWorkBannerItem, childInputBannerItem, @@ -8101,7 +7915,7 @@ export default function ChatView(props: ChatViewProps) { } else if (previous && !current) { terminalUiOpenByThreadRef.current[activeThreadKey] = current; const frame = window.requestAnimationFrame(() => { - focusComposer(); + focusComposerStable(); }); return () => { window.cancelAnimationFrame(frame); @@ -8109,31 +7923,31 @@ export default function ChatView(props: ChatViewProps) { } terminalUiOpenByThreadRef.current[activeThreadKey] = current; - }, [activeThreadKey, focusComposer, terminalUiState.terminalOpen]); - - const getShortcutContext = useCallback( - (eventTarget: EventTarget | null = document.activeElement) => ({ - terminalFocus: getTerminalFocusOwner() !== null, - terminalOpen: Boolean(terminalUiState.terminalOpen), - previewFocus: isPreviewFocused(), - previewOpen: previewPanelOpen, - editableFocus: isEditableFocused(eventTarget), - modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false, - composerFocus: document.activeElement?.getAttribute("data-testid") === "composer-editor", - draftThreadRoute: routeKind === "draft", - turnRunning: phase === "running", - isWeb: !isElectron, - isDesktop: isElectron, - }), - [composerRef, previewPanelOpen, terminalUiState.terminalOpen, routeKind, phase], - ); + }, [activeThreadKey, focusComposerStable, terminalUiState.terminalOpen]); + + const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({ + terminalFocus: getTerminalFocusOwner() !== null, + terminalOpen: Boolean(terminalUiState.terminalOpen), + previewFocus: isPreviewFocused(), + previewOpen: previewPanelOpen, + editableFocus: isEditableFocused(eventTarget), + modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false, + composerFocus: document.activeElement?.getAttribute("data-testid") === "composer-editor", + draftThreadRoute: routeKind === "draft", + turnRunning: phase === "running", + isWeb: !isElectron, + isDesktop: isElectron, + }); + const getShortcutContextStable = useStableCallback(getShortcutContext); const timelineSkills = activeProviderStatus ? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd, serverConfig?.provisionedSkills) : EMPTY_PROVIDER_SKILLS; const threadFindControlsRef = useRef(null); const [isThreadFindActive, setIsThreadFindActive] = useState(false); - const openThreadFind = useCallback(() => threadFindControlsRef.current?.open(), []); - const closeThreadFind = useCallback(() => threadFindControlsRef.current?.close(), []); + const openThreadFind = () => threadFindControlsRef.current?.open(); + const openThreadFindStable = useStableCallback(openThreadFind); + const closeThreadFind = () => threadFindControlsRef.current?.close(); + const closeThreadFindStable = useStableCallback(closeThreadFind); useEffect(() => { const handler = (event: globalThis.KeyboardEvent) => { @@ -8154,7 +7968,7 @@ export default function ChatView(props: ChatViewProps) { if (event.defaultPrevented && terminalFocusOwner === null) { return; } - const shortcutContext = getShortcutContext(event.target); + const shortcutContext = getShortcutContextStable(event.target); if ( !shortcutContext.terminalFocus && @@ -8176,7 +7990,7 @@ export default function ChatView(props: ChatViewProps) { if (command === "thread.copyReference") { event.preventDefault(); event.stopPropagation(); - if (!event.repeat) copyActiveThreadReference(); + if (!event.repeat) copyActiveThreadReferenceStable(); return; } @@ -8186,7 +8000,7 @@ export default function ChatView(props: ChatViewProps) { event.stopPropagation(); if (!isServerThread || !activeThreadRef || !supportsSettlement) return; if (activeThreadSettled) { - void handleUnsettleActiveThread(); + void handleUnsettleActiveThreadStable(); return; } // Same as the sidebar Settle button: settle, then open the next thread. @@ -8232,7 +8046,7 @@ export default function ChatView(props: ChatViewProps) { if (!terminalUiState.terminalOpen && !canReadTerminal && !canOperateTerminal) return; event.preventDefault(); event.stopPropagation(); - toggleTerminalVisibility(); + toggleTerminalVisibilityStable(); return; } @@ -8240,28 +8054,28 @@ export default function ChatView(props: ChatViewProps) { if (command === "chat.find" && isServerThread && serverConfig?.threadFind === true) { event.preventDefault(); event.stopPropagation(); - openThreadFind(); + openThreadFindStable(); return; } if (command === "rightPanel.toggle") { event.preventDefault(); event.stopPropagation(); - toggleRightPanel(); + toggleRightPanelStable(); return; } if (command === "rightPanel.toggleMaximized") { event.preventDefault(); event.stopPropagation(); - if (!event.repeat) toggleRightPanelMaximized(); + if (!event.repeat) toggleRightPanelMaximizedStable(); return; } if (command === "threadPanel.toggle") { event.preventDefault(); event.stopPropagation(); - toggleThreadPanel(); + toggleThreadPanelStable(); return; } @@ -8271,7 +8085,7 @@ export default function ChatView(props: ChatViewProps) { if (!activeRightPanelSurface) return; event.preventDefault(); event.stopPropagation(); - if (!event.repeat) closeRightPanelSurface(activeRightPanelSurface); + if (!event.repeat) closeRightPanelSurfaceStable(activeRightPanelSurface); return; } @@ -8282,13 +8096,13 @@ export default function ChatView(props: ChatViewProps) { event.preventDefault(); event.stopPropagation(); if (terminalFocusOwner === "right-panel") { - splitPanelTerminal(); + splitPanelTerminalStable(); return; } if (!terminalUiState.terminalOpen) { - setTerminalOpen(true); + setTerminalOpenStable(true); } - splitTerminal(); + splitTerminalStable(); return; } @@ -8299,13 +8113,13 @@ export default function ChatView(props: ChatViewProps) { event.preventDefault(); event.stopPropagation(); if (terminalFocusOwner === "right-panel") { - splitPanelTerminal("vertical"); + splitPanelTerminalStable("vertical"); return; } if (!terminalUiState.terminalOpen) { - setTerminalOpen(true); + setTerminalOpenStable(true); } - splitTerminal("vertical"); + splitTerminalStable("vertical"); return; } @@ -8316,11 +8130,11 @@ export default function ChatView(props: ChatViewProps) { event.preventDefault(); event.stopPropagation(); if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") { - requestClosePanelTerminal(activeRightPanelSurface.activeTerminalId); + requestClosePanelTerminalStable(activeRightPanelSurface.activeTerminalId); return; } if (!terminalUiState.terminalOpen) return; - requestCloseTerminal(terminalUiState.activeTerminalId); + requestCloseTerminalStable(terminalUiState.activeTerminalId); return; } @@ -8331,20 +8145,20 @@ export default function ChatView(props: ChatViewProps) { event.preventDefault(); event.stopPropagation(); if (terminalFocusOwner === "right-panel") { - addTerminalSurface(); + addTerminalSurfaceStable(); return; } if (!terminalUiState.terminalOpen) { - setTerminalOpen(true); + setTerminalOpenStable(true); } - createNewTerminal(); + createNewTerminalStable(); return; } if (command === "diff.toggle") { event.preventDefault(); event.stopPropagation(); - onToggleDiff(); + onToggleDiffStable(); return; } @@ -8378,7 +8192,7 @@ export default function ChatView(props: ChatViewProps) { (env) => env.environmentId === currentId, ); const next = logicalProjectEnvironments[(index + 1) % logicalProjectEnvironments.length]; - if (next) onEnvironmentChange(next.environmentId); + if (next) onEnvironmentChangeStable(next.environmentId); return; } @@ -8421,7 +8235,7 @@ export default function ChatView(props: ChatViewProps) { event.preventDefault(); event.stopPropagation(); if (event.repeat) return; - void onInterrupt(); + void onInterruptStable(); return; } @@ -8431,7 +8245,7 @@ export default function ChatView(props: ChatViewProps) { if (!script) return; event.preventDefault(); event.stopPropagation(); - void runProjectScript(script); + void runProjectScriptStable(script); }; const dismissFind = (event: KeyboardEvent) => { if ( @@ -8443,11 +8257,11 @@ export default function ChatView(props: ChatViewProps) { isCommandPaletteOpen() ) return; - const context = getShortcutContext(event.target); + const context = getShortcutContextStable(event.target); if (context.terminalFocus || context.previewFocus || context.modelPickerOpen) return; event.preventDefault(); - closeThreadFind(); - focusComposer(); + closeThreadFindStable(); + focusComposerStable(); }; window.addEventListener("keydown", handler, true); window.addEventListener("keydown", dismissFind); @@ -8461,7 +8275,7 @@ export default function ChatView(props: ChatViewProps) { activeProjectScripts, canReadTerminal, canOperateTerminal, - addTerminalSurface, + addTerminalSurfaceStable, activeThreadRef, activeThreadPinned, activeThreadSettled, @@ -8469,51 +8283,51 @@ export default function ChatView(props: ChatViewProps) { terminalUiState.terminalOpen, terminalUiState.activeTerminalId, activeThreadId, - closeRightPanelSurface, - requestCloseTerminal, - requestClosePanelTerminal, - createNewTerminal, - setTerminalOpen, - runProjectScript, - splitTerminal, - splitPanelTerminal, + closeRightPanelSurfaceStable, + requestCloseTerminalStable, + requestClosePanelTerminalStable, + createNewTerminalStable, + setTerminalOpenStable, + runProjectScriptStable, + splitTerminalStable, + splitPanelTerminalStable, keybindings, scriptKeybindings, - handleUnsettleActiveThread, + handleUnsettleActiveThreadStable, isServerThread, serverConfig?.threadFind, - onInterrupt, - onToggleDiff, + onInterruptStable, + onToggleDiffStable, pinThread, settleThread, supportsPinning, supportsSettlement, confirmAndUnpinThread, - copyActiveThreadReference, - getShortcutContext, - openThreadFind, - closeThreadFind, + copyActiveThreadReferenceStable, + getShortcutContextStable, + openThreadFindStable, + closeThreadFindStable, isThreadFindActive, - toggleRightPanel, - toggleRightPanelMaximized, - toggleThreadPanel, - toggleTerminalVisibility, + toggleRightPanelStable, + toggleRightPanelMaximizedStable, + toggleThreadPanelStable, + toggleTerminalVisibilityStable, composerRef, draftId, environmentId, envLocked, hasMultipleEnvironments, logicalProjectEnvironments, - onEnvironmentChange, + onEnvironmentChangeStable, ]); // A focused desktop browser page forwards these chords as menu actions. useEffect(() => { return window.desktopBridge?.onMenuAction((action) => { - if (action === "rightPanel.toggle") toggleRightPanel(); - else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximized(); + if (action === "rightPanel.toggle") toggleRightPanelStable(); + else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximizedStable(); }); - }, [toggleRightPanel, toggleRightPanelMaximized]); + }, [toggleRightPanelStable, toggleRightPanelMaximizedStable]); // Paste-to-focus: the resting composer blurs on a click into the timeline, // so a paste that follows has no editable target and would be dropped. @@ -8563,266 +8377,233 @@ export default function ChatView(props: ChatViewProps) { setPendingRevert(null); } - const onRevertToTurnCount = useCallback( - async (turnCount: number, messageId: MessageId, restoreFiles?: boolean) => { - const localApi = readLocalApi(); - if ( - !localApi || - !activeThread || - isRevertingCheckpoint || - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) - ) - return; - const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId); - const message = sourceMessage - ? { - id: sourceMessage.id, - role: sourceMessage.role, - text: sourceMessage.text, - attachments: sourceMessage.attachments, - context: sourceMessage.context, - runId: sourceMessage.runId, - streaming: false, - createdAt: DateTime.formatIso(sourceMessage.createdAt), - updatedAt: DateTime.formatIso(sourceMessage.updatedAt), - } - : undefined; - if (!message || message.role !== "user") return; + const onRevertToTurnCount = async ( + turnCount: number, + messageId: MessageId, + restoreFiles?: boolean, + ) => { + const localApi = readLocalApi(); + if ( + !localApi || + !activeThread || + isRevertingCheckpoint || + !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) + ) + return; + const sourceMessage = serverProjection?.messages.find((message) => message.id === messageId); + const message = sourceMessage + ? { + id: sourceMessage.id, + role: sourceMessage.role, + text: sourceMessage.text, + attachments: sourceMessage.attachments, + context: sourceMessage.context, + runId: sourceMessage.runId, + streaming: false, + createdAt: DateTime.formatIso(sourceMessage.createdAt), + updatedAt: DateTime.formatIso(sourceMessage.updatedAt), + } + : undefined; + if (!message || message.role !== "user") return; - if (!supportsConversationRollback) { - setThreadError( - activeThread.id, - "This provider does not support reverting conversation history. Start a new thread instead.", - ); - return; + if (!supportsConversationRollback) { + setThreadError( + activeThread.id, + "This provider does not support reverting conversation history. Start a new thread instead.", + ); + return; + } + if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { + setThreadError( + activeThread.id, + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, + ); + return; + } + if (phase === "running" || isSendBusy || isConnecting) { + setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); + return; + } + if (restoreFiles === undefined) { + setPendingRevert({ turnCount, messageId, routeThreadKey }); + return; + } + + useComposerDraftStore.setState((store) => ({ + rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey), + })); + setThreadError(activeThread.id, null); + try { + if (composerRef.current?.hasPendingAttachments()) { + throw new Error("Wait for attachments to finish preparing before rewinding."); } - if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { - setThreadError( - activeThread.id, - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, + const connection = readPreparedConnection(environmentId); + if (!connection) throw new Error("The environment is not connected."); + const files = await prepareRevertedMessageAttachments({ + message, + environmentId, + httpBaseUrl: connection.httpBaseUrl, + createAssetUrl: createAttachmentAssetUrl, + }); + const store = useComposerDraftStore.getState(); + const draft = store.getComposerDraft(composerDraftTarget); + if ( + (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length > + PROVIDER_SEND_TURN_MAX_ATTACHMENTS + ) { + throw new Error( + "Make room for this message's attachments in the composer before rewinding.", ); - return; - } - if (phase === "running" || isSendBusy || isConnecting) { - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); - return; } - if (restoreFiles === undefined) { - setPendingRevert({ turnCount, messageId, routeThreadKey }); - return; - } - - useComposerDraftStore.setState((store) => ({ - rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey), - })); - setThreadError(activeThread.id, null); - try { - if (composerRef.current?.hasPendingAttachments()) { - throw new Error("Wait for attachments to finish preparing before rewinding."); - } - const connection = readPreparedConnection(environmentId); - if (!connection) throw new Error("The environment is not connected."); - const files = await prepareRevertedMessageAttachments({ - message, + const commandId = CommandId.make(randomUUID()); + await waitForRevertedMessage(routeThreadRef, messageId, turnCount, commandId, async () => { + const result = await revertThreadCheckpoint({ environmentId, - httpBaseUrl: connection.httpBaseUrl, - createAssetUrl: createAttachmentAssetUrl, - }); - const store = useComposerDraftStore.getState(); - const draft = store.getComposerDraft(composerDraftTarget); - if ( - (draft?.images.length ?? 0) + (draft?.files.length ?? 0) + files.length > - PROVIDER_SEND_TURN_MAX_ATTACHMENTS - ) { - throw new Error( - "Make room for this message's attachments in the composer before rewinding.", - ); - } - const commandId = CommandId.make(randomUUID()); - await waitForRevertedMessage(routeThreadRef, messageId, turnCount, commandId, async () => { - const result = await revertThreadCheckpoint({ - environmentId, - input: { commandId, threadId: activeThread.id, turnCount, restoreFiles }, - }); - if (result._tag === "Failure") throw squashAtomCommandFailure(result); - }); - const currentPrompt = store.getComposerDraft(composerDraftTarget)?.prompt ?? ""; - const restoredPrompt = recallableComposerPrompt(message.text); - const nextPrompt = - restoredPrompt.length === 0 - ? currentPrompt - : currentPrompt.length > 0 - ? `${currentPrompt}\n\n${restoredPrompt}` - : restoredPrompt; - store.setPrompt(composerDraftTarget, nextPrompt); - const images: ComposerImageAttachment[] = []; - const restoredFiles: ComposerFileAttachment[] = []; - files.forEach((file, index) => { - const attachment = { - id: randomUUID(), - name: file.name, - mimeType: file.type, - sizeBytes: file.size, - file, - }; - if (message.attachments?.[index]?.type === "image") { - images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) }); - } else { - restoredFiles.push({ ...attachment, type: "file" }); - } + input: { commandId, threadId: activeThread.id, turnCount, restoreFiles }, }); - store.addImages(composerDraftTarget, images, { allowDuplicates: true }); - store.addFiles(composerDraftTarget, restoredFiles, { allowDuplicates: true }); - if (currentRouteThreadKeyRef.current === routeThreadKey) { - promptRef.current = nextPrompt; - composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length }); - requestAnimationFrame(() => { - if (currentRouteThreadKeyRef.current === routeThreadKey) - composerRef.current?.focusAtEnd(); - }); + if (result._tag === "Failure") throw squashAtomCommandFailure(result); + }); + const currentPrompt = store.getComposerDraft(composerDraftTarget)?.prompt ?? ""; + const restoredPrompt = recallableComposerPrompt(message.text); + const nextPrompt = + restoredPrompt.length === 0 + ? currentPrompt + : currentPrompt.length > 0 + ? `${currentPrompt}\n\n${restoredPrompt}` + : restoredPrompt; + store.setPrompt(composerDraftTarget, nextPrompt); + const images: ComposerImageAttachment[] = []; + const restoredFiles: ComposerFileAttachment[] = []; + files.forEach((file, index) => { + const attachment = { + id: randomUUID(), + name: file.name, + mimeType: file.type, + sizeBytes: file.size, + file, + }; + if (message.attachments?.[index]?.type === "image") { + images.push({ ...attachment, type: "image", previewUrl: URL.createObjectURL(file) }); + } else { + restoredFiles.push({ ...attachment, type: "file" }); } - } catch (error) { - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to revert thread state.", - ); - } finally { - useComposerDraftStore.setState((store) => { - const remaining = new Set(store.rewindingThreadKeys); - remaining.delete(routeThreadKey); - return { rewindingThreadKeys: remaining }; - }); - } - }, - [ - activeThread, - activeEnvironmentUnavailable, - activeEnvironmentUnavailableLabel, - composerDraftTarget, - composerRef, - createAttachmentAssetUrl, - environmentId, - isConnecting, - isRevertingCheckpoint, - isSendBusy, - phase, - revertThreadCheckpoint, - routeThreadKey, - routeThreadRef, - setThreadError, - supportsConversationRollback, - serverProjection, - ], - ); - - const onRollbackCheckpoint = useCallback( - async (input: { readonly checkpointId: string; readonly scopeId: string }) => { - if (!activeThread || isRevertingCheckpoint) return; - if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { - setThreadError( - activeThread.id, - `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, - ); - return; - } - if (phase === "running" || isSendBusy || isConnecting) { - setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); - return; - } - const localApi = readLocalApi(); - const confirmed = - localApi == null - ? window.confirm("Roll back this thread to the selected checkpoint?") - : await localApi.dialogs.confirm( - "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.", - ); - if (!confirmed) return; - - useComposerDraftStore.setState((store) => ({ - rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey), - })); - setThreadError(activeThread.id, null); - const result = await revertThreadCheckpoint({ - environmentId, - input: { - threadId: activeThread.id, - checkpointId: input.checkpointId, - scopeId: input.scopeId, - }, }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to revert thread state.", - ); + store.addImages(composerDraftTarget, images, { allowDuplicates: true }); + store.addFiles(composerDraftTarget, restoredFiles, { allowDuplicates: true }); + if (currentRouteThreadKeyRef.current === routeThreadKey) { + promptRef.current = nextPrompt; + composerRef.current?.resetCursorState({ prompt: nextPrompt, cursor: nextPrompt.length }); + requestAnimationFrame(() => { + if (currentRouteThreadKeyRef.current === routeThreadKey) + composerRef.current?.focusAtEnd(); + }); } + } catch (error) { + setThreadError( + activeThread.id, + error instanceof Error ? error.message : "Failed to revert thread state.", + ); + } finally { useComposerDraftStore.setState((store) => { const remaining = new Set(store.rewindingThreadKeys); remaining.delete(routeThreadKey); return { rewindingThreadKeys: remaining }; }); - }, - [ - activeEnvironmentUnavailable, - activeEnvironmentUnavailableLabel, - activeThread, + } + }; + const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount); + + const onRollbackCheckpoint = async (input: { + readonly checkpointId: string; + readonly scopeId: string; + }) => { + if (!activeThread || isRevertingCheckpoint) return; + if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) { + setThreadError( + activeThread.id, + `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`, + ); + return; + } + if (phase === "running" || isSendBusy || isConnecting) { + setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints."); + return; + } + const localApi = readLocalApi(); + const confirmed = + localApi == null + ? window.confirm("Roll back this thread to the selected checkpoint?") + : await localApi.dialogs.confirm( + "Roll back this thread to the selected checkpoint?\nThis action cannot be undone.", + ); + if (!confirmed) return; + + useComposerDraftStore.setState((store) => ({ + rewindingThreadKeys: new Set(store.rewindingThreadKeys).add(routeThreadKey), + })); + setThreadError(activeThread.id, null); + const result = await revertThreadCheckpoint({ environmentId, - isConnecting, - isRevertingCheckpoint, - isSendBusy, - phase, - revertThreadCheckpoint, - setThreadError, - ], - ); + input: { + threadId: activeThread.id, + checkpointId: input.checkpointId, + scopeId: input.scopeId, + }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThread.id, + error instanceof Error ? error.message : "Failed to revert thread state.", + ); + } + useComposerDraftStore.setState((store) => { + const remaining = new Set(store.rewindingThreadKeys); + remaining.delete(routeThreadKey); + return { rewindingThreadKeys: remaining }; + }); + }; - const onForkFromRun = useCallback( - async (input: { readonly sourceThreadId: ThreadId; readonly runId: RunId }) => { - if (!activeThread || activeEnvironmentUnavailable) return; - const targetThreadId = newThreadId(); - const targetThreadRef = scopeThreadRef(environmentId, targetThreadId); - const result = await forkThreadFromRun({ - environmentId, - input: { - sourceThreadId: input.sourceThreadId, - targetThreadId, - runId: input.runId, - title: `${activeThread.title} fork`, - }, - }); - if (result._tag === "Failure") { - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to fork this response.", - ); - } - return; - } - const targetThreadReady = await waitForThreadShell(targetThreadRef); - if (!targetThreadReady) { + const onForkFromRun = async (input: { + readonly sourceThreadId: ThreadId; + readonly runId: RunId; + }) => { + if (!activeThread || activeEnvironmentUnavailable) return; + const targetThreadId = newThreadId(); + const targetThreadRef = scopeThreadRef(environmentId, targetThreadId); + const result = await forkThreadFromRun({ + environmentId, + input: { + sourceThreadId: input.sourceThreadId, + targetThreadId, + runId: input.runId, + title: `${activeThread.title} fork`, + }, + }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); setThreadError( activeThread.id, - "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.", + error instanceof Error ? error.message : "Failed to fork this response.", ); - return; } - await navigate({ - to: "/$environmentId/$threadId", - params: buildThreadRouteParams(targetThreadRef), - }); - }, - [ - activeEnvironmentUnavailable, - activeThread, - environmentId, - forkThreadFromRun, - navigate, - setThreadError, - ], - ); + return; + } + const targetThreadReady = await waitForThreadShell(targetThreadRef); + if (!targetThreadReady) { + setThreadError( + activeThread.id, + "The fork was created, but its thread data did not reach this client. Reconnect and try opening it from the sidebar.", + ); + return; + } + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(targetThreadRef), + }); + }; + const onForkFromRunStable = useStableCallback(onForkFromRun); const onCompactContext = () => { if (compactDisabled) return; void sendStandaloneCommand("/compact", "Failed to compact context."); @@ -10334,245 +10115,214 @@ export default function ChatView(props: ChatViewProps) { } }; - const onRespondToApproval = useCallback( - async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => { - if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) - return; - if ( - pendingApprovals.find((approval) => approval.requestId === requestId) - ?.responseCapability !== "live" - ) - return; + const onRespondToApproval = async ( + requestId: RuntimeRequestId, + decision: ProviderApprovalDecision, + ) => { + if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) + return; + if ( + pendingApprovals.find((approval) => approval.requestId === requestId)?.responseCapability !== + "live" + ) + return; - setRespondingRequestIds((existing) => - existing.includes(requestId) ? existing : [...existing, requestId], + setRespondingRequestIds((existing) => + existing.includes(requestId) ? existing : [...existing, requestId], + ); + const result = await respondToThreadApproval({ + environmentId, + input: { + threadId: activeThreadId, + requestId, + decision, + }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : "Failed to submit approval decision.", ); - const result = await respondToThreadApproval({ + } + setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); + return result; + }; + const onRespondToApprovalStable = useStableCallback(onRespondToApproval); + + const onRespondToUserInput = async ( + requestId: RuntimeRequestId, + answers: Record, + ) => { + if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) + return; + const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId); + if (!pendingInput || pendingInput.responseCapability === "not_resumable") return; + const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]); + if (userInputResponsesInFlight.current.has(responseKey)) return; + const attachmentsByQuestionId = new Map< + string, + import("@t3tools/contracts").UserInputAttachments[string] + >(); + const providerAnswers = { ...answers }; + for (const question of pendingInput.questions) { + const target = questionAttachmentDraftId( environmentId, - input: { - threadId: activeThreadId, - requestId, - decision, - }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); + activeThreadId, + requestId, + question.id, + ); + if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return; + const draft = useComposerDraftStore.getState().getComposerDraft(target); + providerAnswers[question.id] = projectPendingUserInputAnswer( + answers[question.id], + draft?.threadContexts ?? [], + ); + const attachments = draft ? [...draft.images, ...draft.files] : []; + if (attachments.length === 0) continue; + const uploaded = getUploadedAttachments({ environmentId, images: attachments }); + if (!uploaded) { setThreadError( activeThreadId, - error instanceof Error ? error.message : "Failed to submit approval decision.", + "Wait for attachments to finish uploading, or remove failed uploads.", ); - } - setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); - return result; - }, - [activeThreadId, environmentId, pendingApprovals, respondToThreadApproval, setThreadError], - ); - - const onRespondToUserInput = useCallback( - async (requestId: RuntimeRequestId, answers: Record) => { - if (!activeThreadId || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return; - const pendingInput = pendingUserInputs.find((input) => input.requestId === requestId); - if (!pendingInput || pendingInput.responseCapability === "not_resumable") return; - const responseKey = JSON.stringify([environmentId, activeThreadId, requestId]); - if (userInputResponsesInFlight.current.has(responseKey)) return; - const attachmentsByQuestionId = new Map< - string, - import("@t3tools/contracts").UserInputAttachments[string] - >(); - const providerAnswers = { ...answers }; - for (const question of pendingInput.questions) { - const target = questionAttachmentDraftId( - environmentId, - activeThreadId, - requestId, - question.id, - ); - if ((useQuestionAttachmentPreparation.getState().counts[target] ?? 0) > 0) return; - const draft = useComposerDraftStore.getState().getComposerDraft(target); - providerAnswers[question.id] = projectPendingUserInputAnswer( - answers[question.id], - draft?.threadContexts ?? [], - ); - const attachments = draft ? [...draft.images, ...draft.files] : []; - if (attachments.length === 0) continue; - const uploaded = getUploadedAttachments({ environmentId, images: attachments }); - if (!uploaded) { - setThreadError( - activeThreadId, - "Wait for attachments to finish uploading, or remove failed uploads.", - ); - return; - } - attachmentsByQuestionId.set( - question.id, - uploaded as import("@t3tools/contracts").UserInputAttachments[string], - ); } - userInputResponsesInFlight.current.add(responseKey); + attachmentsByQuestionId.set( + question.id, + uploaded as import("@t3tools/contracts").UserInputAttachments[string], + ); + } + userInputResponsesInFlight.current.add(responseKey); - setRespondingUserInputRequestIds((existing) => - existing.includes(requestId) ? existing : [...existing, requestId], + setRespondingUserInputRequestIds((existing) => + existing.includes(requestId) ? existing : [...existing, requestId], + ); + const result = await respondToThreadUserInput({ + environmentId, + input: { + threadId: activeThreadId, + requestId, + answers: providerAnswers, + ...(attachmentsByQuestionId.size > 0 + ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) } + : {}), + }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : "Failed to submit user input.", ); - const result = await respondToThreadUserInput({ - environmentId, - input: { - threadId: activeThreadId, - requestId, - answers: providerAnswers, - ...(attachmentsByQuestionId.size > 0 - ? { attachmentsByQuestionId: Object.fromEntries(attachmentsByQuestionId) } - : {}), - }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : "Failed to submit user input.", - ); - } - userInputResponsesInFlight.current.delete(responseKey); - setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); - return result; - }, - [activeThreadId, environmentId, pendingUserInputs, respondToThreadUserInput, setThreadError], - ); + } + userInputResponsesInFlight.current.delete(responseKey); + setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); + return result; + }; // Closes an async question without messaging the agent. The server records // the dismissal so every client releases the composer. - const onDismissUserInput = useCallback( - async (requestId: RuntimeRequestId) => { - if (!activeThreadId) return; + const onDismissUserInput = async (requestId: RuntimeRequestId) => { + if (!activeThreadId) return; - setRespondingUserInputRequestIds((existing) => - existing.includes(requestId) ? existing : [...existing, requestId], + setRespondingUserInputRequestIds((existing) => + existing.includes(requestId) ? existing : [...existing, requestId], + ); + const result = await dismissThreadUserInput({ + environmentId, + input: { threadId: activeThreadId, requestId }, + }); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + setThreadError( + activeThreadId, + error instanceof Error ? error.message : "Failed to dismiss the question.", ); - const result = await dismissThreadUserInput({ - environmentId, - input: { threadId: activeThreadId, requestId }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThreadId, - error instanceof Error ? error.message : "Failed to dismiss the question.", - ); - } - setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); - return result; - }, - [activeThreadId, dismissThreadUserInput, environmentId, setThreadError], - ); + } + setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); + return result; + }; + const onDismissUserInputStable = useStableCallback(onDismissUserInput); - const setActivePendingUserInputQuestionIndex = useCallback( - (nextQuestionIndex: number) => { - if (!activePendingUserInput) { - return; - } - setPendingUserInputQuestionIndexByRequestId((existing) => ({ - ...existing, - [activePendingRequestKey]: nextQuestionIndex, - })); - }, - [activePendingUserInput, activePendingRequestKey], - ); + const setActivePendingUserInputQuestionIndex = (nextQuestionIndex: number) => { + if (!activePendingUserInput) { + return; + } + setPendingUserInputQuestionIndexByRequestId((existing) => ({ + ...existing, + [activePendingRequestKey]: nextQuestionIndex, + })); + }; - const onSelectActivePendingUserInputOption = useCallback( - (questionId: string, optionValue: string) => { - if (!activePendingUserInput) { - return; + const onSelectActivePendingUserInputOption = (questionId: string, optionValue: string) => { + if (!activePendingUserInput) { + return; + } + // The option replaces the custom answer. Anything typed there is the + // user's text, so it goes back to the thread draft instead of vanishing. + const displacedAnswer = + pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer; + const currentPrompt = + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? ""; + const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer); + if (nextPrompt !== currentPrompt) { + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + if (activeThreadId) { + const store = useComposerDraftStore.getState(); + const questionTarget = questionAttachmentDraftId( + environmentId, + activeThreadId, + activePendingUserInput.requestId, + questionId, + ); + store.addThreadContexts( + composerDraftTarget, + store.getComposerDraft(questionTarget)?.threadContexts ?? [], + { appendReference: false }, + ); } - // The option replaces the custom answer. Anything typed there is the - // user's text, so it goes back to the thread draft instead of vanishing. - const displacedAnswer = - pendingUserInputAnswersByRequestId[activePendingRequestKey]?.[questionId]?.customAnswer; - const currentPrompt = - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.prompt ?? ""; - const nextPrompt = carryDisplacedCustomAnswerIntoPrompt(currentPrompt, displacedAnswer); - if (nextPrompt !== currentPrompt) { - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - if (activeThreadId) { - const store = useComposerDraftStore.getState(); - const questionTarget = questionAttachmentDraftId( - environmentId, - activeThreadId, - activePendingUserInput.requestId, - questionId, - ); - store.addThreadContexts( - composerDraftTarget, - store.getComposerDraft(questionTarget)?.threadContexts ?? [], - { appendReference: false }, - ); - } + } + setPendingUserInputAnswersByRequestId((existing) => { + const question = + (activePendingProgress?.activeQuestion?.id === questionId + ? activePendingProgress.activeQuestion + : undefined) ?? activePendingUserInput.questions.find((entry) => entry.id === questionId); + if (!question) { + return existing; } - setPendingUserInputAnswersByRequestId((existing) => { - const question = - (activePendingProgress?.activeQuestion?.id === questionId - ? activePendingProgress.activeQuestion - : undefined) ?? - activePendingUserInput.questions.find((entry) => entry.id === questionId); - if (!question) { - return existing; - } - - return { - ...existing, - [activePendingRequestKey]: { - ...existing[activePendingRequestKey], - [questionId]: togglePendingUserInputOptionSelection( - question, - existing[activePendingRequestKey]?.[questionId], - optionValue, - ), - }, - }; - }); - promptRef.current = ""; - composerRef.current?.resetCursorState({ cursor: 0 }); - }, - [ - activePendingProgress?.activeQuestion, - activePendingUserInput, - activePendingRequestKey, - activeThreadId, - composerDraftTarget, - composerRef, - environmentId, - pendingUserInputAnswersByRequestId, - setComposerDraftPrompt, - ], - ); - const onChangeActivePendingUserInputCustomAnswer = useCallback( - (questionId: string, value: string) => { - if (!activePendingUserInput) { - return; - } - const question = activePendingUserInput.questions.find((entry) => entry.id === questionId); - if (!question || question.allowCustomAnswer === false) { - return; - } - promptRef.current = value; - setPendingUserInputAnswersByRequestId((existing) => ({ + return { ...existing, [activePendingRequestKey]: { ...existing[activePendingRequestKey], - [questionId]: setPendingUserInputCustomAnswer( - existing[activePendingRequestKey]?.[questionId], - value, + [questionId]: togglePendingUserInputOptionSelection( question, + existing[activePendingRequestKey]?.[questionId], + optionValue, ), }, - })); - // The editor owns this selection. Resetting it before the answer renders - // can re-enter Lexical with offsets from the previous skill token. - }, + }; + }); + promptRef.current = ""; + composerRef.current?.resetCursorState({ cursor: 0 }); + }; + const onSelectActivePendingUserInputOptionStable = useStableCallback( + onSelectActivePendingUserInputOption, + ); + + const onChangeActivePendingUserInputCustomAnswer = useMemo( + () => + makePendingCustomAnswerSetter({ + activePendingUserInput, + activePendingRequestKey, + promptRef, + setPendingUserInputAnswersByRequestId, + }), [activePendingUserInput, activePendingRequestKey], ); - const onAdvanceActivePendingUserInput = useCallback(() => { + const onAdvanceActivePendingUserInput = () => { if ( !activePendingUserInput || activePendingUserInput.responseCapability === "not_resumable" || @@ -10587,21 +10337,18 @@ export default function ChatView(props: ChatViewProps) { return; } setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1); - }, [ - activePendingProgress, - activePendingResolvedAnswers, - activePendingUserInput, - activePendingIsResponding, - onRespondToUserInput, - setActivePendingUserInputQuestionIndex, - ]); + }; + const onAdvanceActivePendingUserInputStable = useStableCallback(onAdvanceActivePendingUserInput); - const onPreviousActivePendingUserInputQuestion = useCallback(() => { + const onPreviousActivePendingUserInputQuestion = () => { if (!activePendingProgress) { return; } setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0)); - }, [activePendingProgress, setActivePendingUserInputQuestionIndex]); + }; + const onPreviousActivePendingUserInputQuestionStable = useStableCallback( + onPreviousActivePendingUserInputQuestion, + ); async function onSubmitPlanFollowUp({ text, @@ -10751,7 +10498,7 @@ export default function ChatView(props: ChatViewProps) { return false; } - const onImplementPlanInNewThread = useCallback(async () => { + const onImplementPlanInNewThread = async () => { if ( !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || !activeThread || @@ -10889,169 +10636,128 @@ export default function ChatView(props: ChatViewProps) { } } finish(); - }, [ - activeProject, - activeProposedPlan, - activeThreadBranch, - activeThread, - beginLocalDispatch, - activeEnvironmentUnavailable, - createThread, - deleteThread, - isConnecting, - isSendBusy, - isServerThread, - navigate, - resetLocalDispatch, - defaultRuntimeMode, - startThreadTurn, - environmentId, - composerRef, - ]); + }; + const onImplementPlanInNewThreadStable = useStableCallback(onImplementPlanInNewThread); - const getModelDisabledReason = useCallback( - (instanceId: ProviderInstanceId, model: string): string | null => { - if (!activeThread) { - return null; - } - const reason = getStartedThreadModelChangeBlockReason({ - providers: providerStatuses, - hasStartedSession: activeRuntime !== null, - supportsProviderSwitchingViaHandoff, - currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, - nextModelSelection: { instanceId, model }, - }); - return reason ? `${reason.description} Start a new thread to use this model.` : null; - }, + const getModelDisabledReason = useMemo( + () => + makeModelDisabledReason( + activeThread + ? { + providers: providerStatuses, + hasStartedSession: activeRuntime !== null, + supportsProviderSwitchingViaHandoff, + currentModelSelection: activeThread.modelSelection, + currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, + } + : null, + ), [activeRuntime, activeThread, providerStatuses, supportsProviderSwitchingViaHandoff], ); - const onProviderModelSelect = useCallback( - (instanceId: ProviderInstanceId, model: string, options?: { focusComposer?: boolean }) => { - if (!activeThread) return; - // Look up the configured instance so model normalization and custom - // model lookup stay scoped to that exact instance. Unknown instance ids - // are rejected by returning early; the server remains authoritative too. - const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); - const resolvedDriverKind = entry?.driver ?? null; - if ( - !supportsProviderSwitchingViaHandoff && - lockedProvider !== null && - resolvedDriverKind !== null && - resolvedDriverKind !== lockedProvider - ) { - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } + const onProviderModelSelect = ( + instanceId: ProviderInstanceId, + model: string, + options?: { focusComposer?: boolean }, + ) => { + if (!activeThread) return; + // Look up the configured instance so model normalization and custom + // model lookup stay scoped to that exact instance. Unknown instance ids + // are rejected by returning early; the server remains authoritative too. + const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); + const resolvedDriverKind = entry?.driver ?? null; + if ( + !supportsProviderSwitchingViaHandoff && + lockedProvider !== null && + resolvedDriverKind !== null && + resolvedDriverKind !== lockedProvider + ) { + if (options?.focusComposer !== false) scheduleComposerFocus(); + return; + } + if ( + !supportsProviderSwitchingViaHandoff && + lockedProvider !== null && + activeRuntime?.providerInstanceId + ) { + const currentEntry = providerStatuses.find( + (snapshot) => snapshot.instanceId === activeRuntime.providerInstanceId, + ); if ( - !supportsProviderSwitchingViaHandoff && - lockedProvider !== null && - activeRuntime?.providerInstanceId + currentEntry?.continuation?.groupKey && + entry?.continuation?.groupKey && + currentEntry.continuation.groupKey !== entry.continuation.groupKey ) { - const currentEntry = providerStatuses.find( - (snapshot) => snapshot.instanceId === activeRuntime.providerInstanceId, - ); - if ( - currentEntry?.continuation?.groupKey && - entry?.continuation?.groupKey && - currentEntry.continuation.groupKey !== entry.continuation.groupKey - ) { - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } - } - const resolvedModel = resolveAppModelSelectionForInstance( - instanceId, - settings, - providerStatuses, - model, - ); - if (!resolvedModel) { - if (options?.focusComposer !== false) scheduleComposerFocus(); - return; - } - // Restore this model's own remembered options; without any, start it - // from its default rather than carrying the previous model's over. - const rememberedOptions = - useComposerDraftStore.getState().stickyOptionsByModelByProvider[instanceId]?.[ - resolvedModel - ]; - const nextModelSelection: ModelSelection = - rememberedOptions !== undefined && rememberedOptions.length > 0 - ? { instanceId, model: resolvedModel, options: [...rememberedOptions] } - : { instanceId, model: resolvedModel }; - const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ - providers: providerStatuses, - hasStartedSession: activeRuntime !== null, - supportsProviderSwitchingViaHandoff, - currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, - nextModelSelection, - }); - if (modelChangeBlockReason) { - toastManager.add({ - type: "warning", - title: modelChangeBlockReason.title, - description: modelChangeBlockReason.description, - }); if (options?.focusComposer !== false) scheduleComposerFocus(); return; } - setComposerDraftModelSelection( - scopeThreadRef(activeThread.environmentId, activeThread.id), - nextModelSelection, - // A complete snapshot: an absent options field means "start from the - // model default", not "keep the previous model's options". - { explicit: true, replaceOptions: true }, - ); - setStickyComposerModelSelection(nextModelSelection); + } + const resolvedModel = resolveAppModelSelectionForInstance( + instanceId, + settings, + providerStatuses, + model, + ); + if (!resolvedModel) { if (options?.focusComposer !== false) scheduleComposerFocus(); - }, - [ - activeThread, - activeRuntime, - lockedProvider, + return; + } + // Restore this model's own remembered options; without any, start it + // from its default rather than carrying the previous model's over. + const rememberedOptions = + useComposerDraftStore.getState().stickyOptionsByModelByProvider[instanceId]?.[resolvedModel]; + const nextModelSelection: ModelSelection = + rememberedOptions !== undefined && rememberedOptions.length > 0 + ? { instanceId, model: resolvedModel, options: [...rememberedOptions] } + : { instanceId, model: resolvedModel }; + const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ + providers: providerStatuses, + hasStartedSession: activeRuntime !== null, supportsProviderSwitchingViaHandoff, - scheduleComposerFocus, - setComposerDraftModelSelection, - setStickyComposerModelSelection, - providerStatuses, - settings, - ], - ); - const onEnvModeChange = useCallback( - (mode: DraftThreadEnvMode) => { - if (multipleModelSelections !== null) return; - if (canOverrideServerThreadEnvMode) { - setPendingServerThreadEnvMode(mode); - scheduleComposerFocus(); - return; - } - if (isLocalDraftThread) { - setDraftThreadContext(composerDraftTarget, { - envMode: mode, - startFromOrigin: resolveNewDraftStartFromOrigin({ - envMode: mode, - newWorktreesStartFromOrigin: activeProjectSettings.settings.newWorktreesStartFromOrigin, - }), - ...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}), - }); - } + currentModelSelection: activeThread.modelSelection, + currentProviderInstanceId: activeRuntime?.providerInstanceId ?? null, + nextModelSelection, + }); + if (modelChangeBlockReason) { + toastManager.add({ + type: "warning", + title: modelChangeBlockReason.title, + description: modelChangeBlockReason.description, + }); + if (options?.focusComposer !== false) scheduleComposerFocus(); + return; + } + setComposerDraftModelSelection( + scopeThreadRef(activeThread.environmentId, activeThread.id), + nextModelSelection, + // A complete snapshot: an absent options field means "start from the + // model default", not "keep the previous model's options". + { explicit: true, replaceOptions: true }, + ); + setStickyComposerModelSelection(nextModelSelection); + if (options?.focusComposer !== false) scheduleComposerFocus(); + }; + const onProviderModelSelectStable = useStableCallback(onProviderModelSelect); + const onEnvModeChange = (mode: DraftThreadEnvMode) => { + if (multipleModelSelections !== null) return; + if (canOverrideServerThreadEnvMode) { + setPendingServerThreadEnvMode(mode); scheduleComposerFocus(); - }, - [ - canOverrideServerThreadEnvMode, - composerDraftTarget, - draftThread?.worktreePath, - isLocalDraftThread, - multipleModelSelections, - activeProjectSettings.settings.newWorktreesStartFromOrigin, - setPendingServerThreadEnvMode, - scheduleComposerFocus, - setDraftThreadContext, - ], - ); + return; + } + if (isLocalDraftThread) { + setDraftThreadContext(composerDraftTarget, { + envMode: mode, + startFromOrigin: resolveNewDraftStartFromOrigin({ + envMode: mode, + newWorktreesStartFromOrigin: activeProjectSettings.settings.newWorktreesStartFromOrigin, + }), + ...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}), + }); + } + scheduleComposerFocus(); + }; + const onEnvModeChangeStable = useStableCallback(onEnvModeChange); // "Work locally" on the setup card: cancel the bootstrap and remember the // draft. The cancelled dispatch deletes the half-made thread and puts the @@ -11059,7 +10765,7 @@ export default function ChatView(props: ChatViewProps) { // local mode and resends. The draft is a server thread for the whole // setup (the bootstrap created it), so this keys off the route, not // `isLocalDraftThread`. - const onWorktreeSetupWorkLocally = useCallback(() => { + const onWorktreeSetupWorkLocally = () => { if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) { return; } @@ -11072,19 +10778,20 @@ export default function ChatView(props: ChatViewProps) { if (result._tag !== "Success" || !result.value.cancelled) return; setWorkLocallyResendDraftId(draftId); })(); - }, [cancelWorktreeSetup, draftId, setupTarget.environmentId, worktreeSetup]); + }; + const onWorktreeSetupWorkLocallyStable = useStableCallback(onWorktreeSetupWorkLocally); const onSendRef = useRef(onSend); onSendRef.current = onSend; const onResumeRef = useRef(onResume); onResumeRef.current = onResume; const onCompactContextRef = useRef(onCompactContext); onCompactContextRef.current = onCompactContext; - const onComposerSend = useCallback( - (...args: Parameters) => onSendRef.current(...args), - [], - ); - const onComposerResume = useCallback(() => onResumeRef.current(), []); - const onComposerCompactContext = useCallback(() => onCompactContextRef.current(), []); + const onComposerSend = (...args: Parameters) => onSendRef.current(...args); + const onComposerSendStable = useStableCallback(onComposerSend); + const onComposerResume = () => onResumeRef.current(); + const onComposerResumeStable = useStableCallback(onComposerResume); + const onComposerCompactContext = () => onCompactContextRef.current(); + const onComposerCompactContextStable = useStableCallback(onComposerCompactContext); const queuedRunsControl = useMemo( () => isServerThread && activeThread ? ( @@ -11100,14 +10807,14 @@ export default function ChatView(props: ChatViewProps) { threadId={activeThread.id} optimisticMessages={optimisticUserMessages} editingRunId={editingQueuedRun?.runId ?? null} - onEditQueuedRun={beginEditingQueuedRun} - onCancelEdit={cancelEditingQueuedRun} + onEditQueuedRun={beginEditingQueuedRunStable} + onCancelEdit={cancelEditingQueuedRunStable} /> ) : null, [ activeThread, - beginEditingQueuedRun, - cancelEditingQueuedRun, + beginEditingQueuedRunStable, + cancelEditingQueuedRunStable, editingQueuedRun?.runId, isServerThread, keybindings, @@ -11172,35 +10879,35 @@ export default function ChatView(props: ChatViewProps) { } }; - const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => { + const onExpandTimelineImage = (preview: ExpandedImagePreview) => { setExpandedImage(preview); - }, []); - const onOpenTurnDiff = useCallback( - (runId: RunId, filePath?: string) => { - if (!isServerThread || !activeThreadRef) return; - const diffOpen = - selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === - "diff"; - explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef; - useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath); - useRightPanelStore.getState().open(activeThreadRef, "diff"); - onDiffPanelOpen?.(); - }, - [activeThreadRef, isServerThread, onDiffPanelOpen], - ); - const onTimelineRollbackCheckpoint = useCallback( - (input: { readonly checkpointId: string; readonly scopeId: string }) => { - if (!paintOnlyDisplayedTimeline) void onRollbackCheckpoint(input); - }, - [onRollbackCheckpoint, paintOnlyDisplayedTimeline], - ); + }; + const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage); + const onOpenTurnDiff = (runId: RunId, filePath?: string) => { + if (!isServerThread || !activeThreadRef) return; + const diffOpen = + selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, activeThreadRef) === "diff"; + explicitDiffOpenRef.current = diffOpen ? null : activeThreadRef; + useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath); + useRightPanelStore.getState().open(activeThreadRef, "diff"); + onDiffPanelOpen?.(); + }; + const onOpenTurnDiffStable = useStableCallback(onOpenTurnDiff); + const onTimelineRollbackCheckpoint = (input: { + readonly checkpointId: string; + readonly scopeId: string; + }) => { + if (!paintOnlyDisplayedTimeline) void onRollbackCheckpoint(input); + }; + const onTimelineRollbackCheckpointStable = useStableCallback(onTimelineRollbackCheckpoint); // The revert handler is read from a ref at call-time so the callback // reference is fully stable and never busts TimelineRowCtx identity. - const onRevertToTurnCountRef = useRef(onRevertToTurnCount); - onRevertToTurnCountRef.current = onRevertToTurnCount; - const onRevertTimelineTurn = useCallback((targetTurnCount: number, messageId: MessageId) => { + const onRevertToTurnCountRef = useRef(onRevertToTurnCountStable); + onRevertToTurnCountRef.current = onRevertToTurnCountStable; + const onRevertTimelineTurn = (targetTurnCount: number, messageId: MessageId) => { void onRevertToTurnCountRef.current(targetTurnCount, messageId); - }, []); + }; + const onRevertTimelineTurnStable = useStableCallback(onRevertTimelineTurn); const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending); const consumePendingFileDrop = useSidebarPendingFileDropStore( @@ -11262,12 +10969,12 @@ export default function ChatView(props: ChatViewProps) { launchContext={activeTerminalLaunchContext ?? null} focusRequestId={terminalFocusRequestId} keybindings={keybindings} - onAddTerminalContext={addTerminalContextToDraft} - onSplitTerminal={splitPanelTerminal} - onSplitTerminalVertical={splitPanelTerminalVertical} - onNewTerminal={addTerminalSurface} - onActiveTerminalChange={activatePanelTerminal} - onCloseTerminal={closePanelTerminal} + onAddTerminalContext={addTerminalContextToDraftStable} + onSplitTerminal={splitPanelTerminalStable} + onSplitTerminalVertical={splitPanelTerminalVerticalStable} + onNewTerminal={addTerminalSurfaceStable} + onActiveTerminalChange={activatePanelTerminalStable} + onCloseTerminal={closePanelTerminalStable} splitShortcutLabel={splitTerminalShortcutLabel ?? undefined} splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined} newShortcutLabel={newTerminalShortcutLabel ?? undefined} @@ -11296,7 +11003,7 @@ export default function ChatView(props: ChatViewProps) { // reader's feet. A link the agent wrote can open any other one here, and that one has to be // checkable out like it is anywhere else. 1 - ? addPullRequestsSurface + ? addPullRequestsSurfaceStable : undefined } /> @@ -11387,8 +11094,8 @@ export default function ChatView(props: ChatViewProps) { ? renderedRightPanelSurface.revealRequestId : 0 } - onOpenFile={openFileSurface} - onPendingChange={handleFilePendingChange} + onOpenFile={openFileSurfaceStable} + onPendingChange={handleFilePendingChangeStable} selectedFilePending={ renderedRightPanelSurface.kind === "file" && pendingFileSurfaceIds.has(renderedRightPanelSurface.id) @@ -11424,11 +11131,11 @@ export default function ChatView(props: ChatViewProps) { !envLocked && canAutoBalanceEnvironments && loadBalancingSettings.loadBalancingEnabled - ? onAutoEnvironment + ? onAutoEnvironmentStable : undefined, - onEnvironmentChange, + onEnvironmentChange: onEnvironmentChangeStable, cloudRunOn: cloud.runOn, - onEnvModeChange, + onEnvModeChange: onEnvModeChangeStable, envMode, ...(canOverrideServerThreadEnvMode ? { @@ -11439,14 +11146,14 @@ export default function ChatView(props: ChatViewProps) { startFromOrigin, onStartFromOriginChange, ...(canCheckoutPullRequestIntoThread - ? { onCheckoutPullRequestRequest: openPullRequestDialog } + ? { onCheckoutPullRequestRequest: openPullRequestDialogStable } : {}), - onComposerFocusRequest: scheduleComposerFocus, - ...(isServerThread && isGitRepo ? { onOpenChanges: openChangesFromThreadPanel } : {}), - onRunProjectScript: runProjectScript, - onAddProjectScript: saveProjectScript, - onUpdateProjectScript: updateProjectScript, - onDeleteProjectScript: deleteProjectScript, + onComposerFocusRequest: scheduleComposerFocusStable, + ...(isServerThread && isGitRepo ? { onOpenChanges: openChangesFromThreadPanelStable } : {}), + onRunProjectScript: runProjectScriptStable, + onAddProjectScript: saveProjectScriptStable, + onUpdateProjectScript: updateProjectScriptStable, + onDeleteProjectScript: deleteProjectScriptStable, }; const panelToggleControlProps = { terminalAvailable: activeProject !== null, @@ -11459,9 +11166,9 @@ export default function ChatView(props: ChatViewProps) { rightPanelAvailable: activeProject !== null, rightPanelOpen, rightPanelShortcutLabel: shortcutLabelForCommand(keybindings, "rightPanel.toggle"), - onToggleTerminal: toggleTerminalVisibility, - onToggleThreadPanel: toggleThreadPanel, - onToggleRightPanel: toggleRightPanel, + onToggleTerminal: toggleTerminalVisibilityStable, + onToggleThreadPanel: toggleThreadPanelStable, + onToggleRightPanel: toggleRightPanelStable, } satisfies PanelLayoutControlsProps; const panelToggleControls = ( ) : null} @@ -11591,11 +11298,11 @@ export default function ChatView(props: ChatViewProps) { activeThreadTitle={activeThread.title} activeProject={activeProject ?? null} parentThreadLink={parentThreadLink} - onOpenThread={onOpenRelatedThread} + onOpenThread={onOpenRelatedThreadStable} rightPanelOpen={inlineRightPanelOwnsTitleBar} - onNewThreadInProject={handleNewThreadInActiveProject} + onNewThreadInProject={handleNewThreadInActiveProjectStable} {...(activeDraftLogicalProjectKey - ? { onOpenProjectSettings: handleOpenDraftProjectSettings } + ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable } : {})} /> @@ -11622,7 +11329,7 @@ export default function ChatView(props: ChatViewProps) { onDragLeave={workspaceFileDropHandlers.onDragLeave} onDrop={workspaceFileDropHandlers.onDrop} > - + {isWorkspaceFileDragActive ? (
setDismissedProviderStatusBannerKey(providerStatusBannerKey)} - onOpenProviderSetup={openProviderSetup} + onOpenProviderSetup={openProviderSetupStable} /> {} : onForkFromRun} - onRollbackCheckpoint={onTimelineRollbackCheckpoint} + onForkFromRun={paintOnlyDisplayedTimeline ? async () => {} : onForkFromRunStable} + onRollbackCheckpoint={onTimelineRollbackCheckpointStable} supportsConversationRollback={ !paintOnlyDisplayedTimeline && supportsConversationRollback } onRevertToTurnCount={ - paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurn + paintOnlyDisplayedTimeline ? noopHeldRevert : onRevertTimelineTurnStable } {...(!paintOnlyDisplayedTimeline - ? { onUseArtifactTemplate: useArtifactTemplate, onSendAppMessage: sendAppMessage } + ? { + onUseArtifactTemplate: useArtifactTemplateStable, + onSendAppMessage: sendAppMessageStable, + } : {})} isRevertingCheckpoint={isRevertingCheckpoint} - onImageExpand={onExpandTimelineImage} - onFileOpen={paintOnlyDisplayedTimeline ? noopHeldAttachment : openFileAttachment} + onImageExpand={onExpandTimelineImageStable} + onFileOpen={ + paintOnlyDisplayedTimeline ? noopHeldAttachment : openFileAttachmentStable + } onFileDownload={ - paintOnlyDisplayedTimeline ? noopHeldAttachment : downloadFileAttachment + paintOnlyDisplayedTimeline ? noopHeldAttachment : downloadFileAttachmentStable } markdownCwd={ paintOnlyDisplayedTimeline @@ -11762,14 +11481,14 @@ export default function ChatView(props: ChatViewProps) { } skills={timelineSkills} anchorMessageId={paintOnlyDisplayedTimeline ? null : timelineAnchorMessageId} - onAnchorReady={onTimelineAnchorReady} - onAnchorSizeChanged={onTimelineAnchorSizeChanged} + onAnchorReady={onTimelineAnchorReadyStable} + onAnchorSizeChanged={onTimelineAnchorSizeChangedStable} contentInsetEndAdjustment={composerTimelineInset} liveFollowEnabled={!paintOnlyDisplayedTimeline && timelineLiveFollowEnabled} - onIsAtEndChange={onIsAtEndChange} + onIsAtEndChange={onIsAtEndChangeStable} onContentOverflowChange={setTimelineOverflows} - onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEnd} - onManualNavigation={cancelTimelineLiveFollowForUserNavigation} + onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable} + onManualNavigation={cancelTimelineLiveFollowForUserNavigationStable} cancelPositionRestoreRef={cancelPositionRestoreRef} hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading} topFadeEnabled={!hasTimelineTopBanner} @@ -11886,7 +11605,7 @@ export default function ChatView(props: ChatViewProps) { true } startsCloudEnvironment={cloud.startsCloudEnvironment} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={setMultipleModelSelectionsStable} composerRef={composerRef} composerDraftTarget={composerDraftTarget} environmentId={environmentId} @@ -11942,14 +11661,14 @@ export default function ChatView(props: ChatViewProps) { bannerItems={composerBannerItems} resumeCompactionTokens={resumeCompactionTokens} keepFullHistory={keepFullHistory} - onToggleKeepFullHistory={toggleKeepFullHistory} + onToggleKeepFullHistory={toggleKeepFullHistoryStable} // With attachments or contexts aboard the pick just inserts the // text, so it sends as a prompt like the typed path would. onUsageLimitsCommand={ usageLimitsOffered && usageLimitsKey !== null && !composerHasNonPromptContent - ? openUsageLimits + ? openUsageLimitsStable : undefined } environmentUnavailable={ @@ -12005,48 +11724,50 @@ export default function ChatView(props: ChatViewProps) { (isGitRepo || showComposerEnvironmentIndicator) } onRestingControlsVisibilityChange={setRestingComposerControlsVisible} - getTimelineScrollableNode={getTimelineScrollableNode} - isTimelineAtLogicalEnd={isTimelineAtLogicalEnd} + getTimelineScrollableNode={getTimelineScrollableNodeStable} + isTimelineAtLogicalEnd={isTimelineAtLogicalEndStable} timelineOverflows={timelineOverflows} - onComposerOverlayHeightChange={publishComposerOverlayHeight} - onRestingChange={onComposerRestingChange} + onComposerOverlayHeightChange={publishComposerOverlayHeightStable} + onRestingChange={onComposerRestingChangeStable} promptRef={promptRef} composerImagesRef={composerImagesRef} composerFilesRef={composerFilesRef} composerTerminalContextsRef={composerTerminalContextsRef} - onPageScrollKeyDown={onComposerPageScrollKeyDown} - onPageScrollKeyUp={onComposerPageScrollKeyUp} - onPageScrollRelease={onComposerPageScrollRelease} - onCompactContext={onComposerCompactContext} - onSend={onComposerSend} - onResume={onComposerResume} - onInterrupt={onInterrupt} - onImplementPlanInNewThread={onImplementPlanInNewThread} - onRespondToApproval={onRespondToApproval} + onPageScrollKeyDown={onComposerPageScrollKeyDownStable} + onPageScrollKeyUp={onComposerPageScrollKeyUpStable} + onPageScrollRelease={onComposerPageScrollReleaseStable} + onCompactContext={onComposerCompactContextStable} + onSend={onComposerSendStable} + onResume={onComposerResumeStable} + onInterrupt={onInterruptStable} + onImplementPlanInNewThread={onImplementPlanInNewThreadStable} + onRespondToApproval={onRespondToApprovalStable} onSelectActivePendingUserInputOption={ - onSelectActivePendingUserInputOption + onSelectActivePendingUserInputOptionStable + } + onAdvanceActivePendingUserInput={ + onAdvanceActivePendingUserInputStable } - onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput} - onDismissActivePendingUserInput={onDismissUserInput} + onDismissActivePendingUserInput={onDismissUserInputStable} onPreviousActivePendingUserInputQuestion={ - onPreviousActivePendingUserInputQuestion + onPreviousActivePendingUserInputQuestionStable } onChangeActivePendingUserInputCustomAnswer={ onChangeActivePendingUserInputCustomAnswer } - onProviderModelSelect={onProviderModelSelect} - onOpenProviderSetup={openProviderSetup} + onProviderModelSelect={onProviderModelSelectStable} + onOpenProviderSetup={openProviderSetupStable} getModelDisabledReason={getModelDisabledReason} - toggleInteractionMode={toggleInteractionMode} - handleRuntimeModeChange={handleRuntimeModeChange} - handleInteractionModeChange={handleInteractionModeChange} - focusComposer={focusComposer} - scheduleComposerFocus={scheduleComposerFocus} + toggleInteractionMode={toggleInteractionModeStable} + handleRuntimeModeChange={handleRuntimeModeChangeStable} + handleInteractionModeChange={handleInteractionModeChangeStable} + focusComposer={focusComposerStable} + scheduleComposerFocus={scheduleComposerFocusStable} setThreadError={setThreadError} - onExpandImage={onExpandTimelineImage} - onFileOpen={openFileAttachment} + onExpandImage={onExpandTimelineImageStable} + onFileOpen={openFileAttachmentStable} editingQueuedAttachments={composerEditingQueuedAttachments} - onRemoveEditingQueuedAttachment={removeEditingQueuedAttachment} + onRemoveEditingQueuedAttachment={removeEditingQueuedAttachmentStable} /> )}
@@ -12082,7 +11803,7 @@ export default function ChatView(props: ChatViewProps) { threadId={activeThread.id} showGitControls={isGitRepo} {...(routeKind === "draft" && draftId ? { draftId } : {})} - onEnvModeChange={onEnvModeChange} + onEnvModeChange={onEnvModeChangeStable} startFromOrigin={startFromOrigin} onStartFromOriginChange={onStartFromOriginChange} envMode={envMode} @@ -12094,12 +11815,12 @@ export default function ChatView(props: ChatViewProps) { } : {})} envLocked={envLocked} - onComposerFocusRequest={scheduleComposerFocus} + onComposerFocusRequest={scheduleComposerFocusStable} {...(canCheckoutPullRequestIntoThread - ? { onCheckoutPullRequestRequest: openPullRequestDialog } + ? { onCheckoutPullRequestRequest: openPullRequestDialogStable } : {})} {...(hasMultipleEnvironments || cloud.runOn - ? { onEnvironmentChange } + ? { onEnvironmentChange: onEnvironmentChangeStable } : {})} autoEnvironmentLabel={autoEnvironmentLabel} onAutoEnvironment={ @@ -12107,7 +11828,7 @@ export default function ChatView(props: ChatViewProps) { !envLocked && canAutoBalanceEnvironments && loadBalancingSettings.loadBalancingEnabled - ? onAutoEnvironment + ? onAutoEnvironmentStable : undefined } availableEnvironments={logicalProjectEnvironments} @@ -12189,7 +11910,7 @@ export default function ChatView(props: ChatViewProps) { closePullRequestDialog(); } }} - onPrepared={handlePreparedPullRequestThread} + onPrepared={handlePreparedPullRequestThreadStable} /> ) : null} @@ -12222,7 +11943,7 @@ export default function ChatView(props: ChatViewProps) { mode="inline" open={rightPanelOpen} keybindings={keybindings} - getShortcutContext={getShortcutContext} + getShortcutContext={getShortcutContextStable} maximized={rightPanelMaximized} inlineSize={previewPanelInlineSize} surfaces={renderedRightPanelSurfaces} @@ -12233,25 +11954,25 @@ export default function ChatView(props: ChatViewProps) { desktopByTabId={activePreviewState.desktopByTabId} previewRuntimeTabId={resolvePreviewRuntimeTabId} terminalLabelsById={activeTerminalLabelsById} - onActivate={activateRightPanelSurface} - onCloseSurface={closeRightPanelSurface} + onActivate={activateRightPanelSurfaceStable} + onCloseSurface={closeRightPanelSurfaceStable} onRenameDevice={(surfaceId, title) => { if (activeThreadRef) useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title); }} - onCloseOtherSurfaces={closeOtherRightPanelSurfaces} - onCloseSurfacesToRight={closeRightPanelSurfacesToRight} - onCloseAllSurfaces={closeAllRightPanelSurfaces} - onMoveSurface={moveRightPanelSurface} - onCopyFilePath={copyRightPanelFilePath} + onCloseOtherSurfaces={closeOtherRightPanelSurfacesStable} + onCloseSurfacesToRight={closeRightPanelSurfacesToRightStable} + onCloseAllSurfaces={closeAllRightPanelSurfacesStable} + onMoveSurface={moveRightPanelSurfaceStable} + onCopyFilePath={copyRightPanelFilePathStable} onAddBrowser={() => createBrowserSurface()} - onAddBrowserInProfile={createBrowserSurface} - onAddTerminal={addTerminalSurface} - onAddDiff={addDiffSurface} - onAddFiles={addFilesSurface} - onAddPullRequest={addPullRequestSurface} - onAddPullRequests={addPullRequestsSurface} - onAddDevice={addDeviceSurface} + onAddBrowserInProfile={createBrowserSurfaceStable} + onAddTerminal={addTerminalSurfaceStable} + onAddDiff={addDiffSurfaceStable} + onAddFiles={addFilesSurfaceStable} + onAddPullRequest={addPullRequestSurfaceStable} + onAddPullRequests={addPullRequestsSurfaceStable} + onAddDevice={addDeviceSurfaceStable} browserAvailable={canOperatePreview && browserAvailable} terminalAvailable={activeProject !== null && canOperateTerminal} diffAvailable={isServerThread && isGitRepo} @@ -12267,13 +11988,13 @@ export default function ChatView(props: ChatViewProps) { { if (activeThreadRef) useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title); }} - onCloseOtherSurfaces={closeOtherRightPanelSurfaces} - onCloseSurfacesToRight={closeRightPanelSurfacesToRight} - onCloseAllSurfaces={closeAllRightPanelSurfaces} - onMoveSurface={moveRightPanelSurface} - onCopyFilePath={copyRightPanelFilePath} + onCloseOtherSurfaces={closeOtherRightPanelSurfacesStable} + onCloseSurfacesToRight={closeRightPanelSurfacesToRightStable} + onCloseAllSurfaces={closeAllRightPanelSurfacesStable} + onMoveSurface={moveRightPanelSurfaceStable} + onCopyFilePath={copyRightPanelFilePathStable} onAddBrowser={() => createBrowserSurface()} - onAddBrowserInProfile={createBrowserSurface} - onAddTerminal={addTerminalSurface} - onAddDiff={addDiffSurface} - onAddFiles={addFilesSurface} - onAddPullRequest={addPullRequestSurface} - onAddPullRequests={addPullRequestsSurface} - onAddDevice={addDeviceSurface} + onAddBrowserInProfile={createBrowserSurfaceStable} + onAddTerminal={addTerminalSurfaceStable} + onAddDiff={addDiffSurfaceStable} + onAddFiles={addFilesSurfaceStable} + onAddPullRequest={addPullRequestSurfaceStable} + onAddPullRequests={addPullRequestsSurfaceStable} + onAddDevice={addDeviceSurfaceStable} browserAvailable={canOperatePreview && browserAvailable} terminalAvailable={activeProject !== null && canOperateTerminal} diffAvailable={isServerThread && isGitRepo} @@ -12367,7 +12088,7 @@ export default function ChatView(props: ChatViewProps) { )}
diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.navigation.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.navigation.test.tsx new file mode 100644 index 000000000000..53bc7104cbc3 --- /dev/null +++ b/apps/web/src/components/ComposerPromptEditorTiptap.navigation.test.tsx @@ -0,0 +1,126 @@ +// @vitest-environment jsdom + +import type { Editor } from "@tiptap/core"; +import { TextSelection } from "@tiptap/pm/state"; +import { act, createRef } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; + +import { serializeEditorDoc } from "~/composer-rich-text-doc"; +import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor"; + +const draft = + "> **Assistant and reasoning text still save intermediate full snapshots**, using the existing 50 ms batching. Compaction still preserves their `turn-item.updated` events. [Code](/Users/yashsingh/p/projects/t3code/apps/server/src/orchestration-v2/ProjectionMaintenance.ts:235)"; + +let root: Root; +let container: HTMLDivElement; + +beforeEach(() => { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); + +async function mountEditor(value: string, richTextEnabled = true) { + await act(async () => + root.render( + ()} + value={value} + cursor={0} + richTextEnabled={richTextEnabled} + contextRecords={new Map()} + skills={[]} + disabled={false} + placeholder="" + onChange={() => {}} + onPaste={() => {}} + />, + ), + ); + const element = container.querySelector(".tiptap"); + if (!element) throw new Error("Composer did not mount"); + return element.editor; +} + +function press(editor: Editor, key: string, options: KeyboardEventInit = {}) { + const event = new KeyboardEvent("keydown", { key, cancelable: true, ...options }); + const handled = editor.view.props.handleKeyDown?.(editor.view, event); + expect(event.defaultPrevented).toBe(Boolean(handled)); + return handled; +} + +it("keeps Up before the opening bold marker in a quote, including while typing", async () => { + const editor = await mountEditor(draft); + const position = editor.state.selection.from; + await act(async () => { + editor.view.focus(); + expect(press(editor, "ArrowUp")).toBe(true); + expect(editor.state.selection.from).toBe(position); + editor.view.updateState(editor.state); + const marker = editor.view.dom.querySelector(".composer-rich-marker"); + const caret = window.getSelection()?.getRangeAt(0); + if (!marker || !caret) throw new Error("Caret or bold marker is missing"); + const markerRange = document.createRange(); + markerRange.selectNode(marker); + expect(caret.compareBoundaryPoints(Range.START_TO_START, markerRange)).toBeLessThanOrEqual(0); + // A repeated Up stays at the outside stop, ready for native navigation. + expect(press(editor, "ArrowUp")).toBe(false); + editor.commands.insertContent("x"); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe(draft.replace("> **", "> x**")); +}); + +it("keeps Down after a closing marker, including while typing", async () => { + const editor = await mountEditor("> **bold**"); + await act(async () => { + editor.view.dispatch(editor.state.tr.setSelection(TextSelection.atEnd(editor.state.doc))); + expect(press(editor, "ArrowDown")).toBe(true); + expect(press(editor, "ArrowDown")).toBe(false); + editor.commands.insertContent("x"); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe("> **bold**x"); +}); + +it("leaves vertical navigation between paragraphs to the browser", async () => { + const editor = await mountEditor("**first**\n**second**"); + await act(async () => { + const first = editor.state.doc.child(0); + editor.commands.setTextSelection(first.nodeSize + 1); + expect(press(editor, "ArrowUp")).toBe(false); + editor.commands.setTextSelection(first.nodeSize - 1); + expect(press(editor, "ArrowDown")).toBe(false); + }); +}); + +it.each([ + { shiftKey: true }, + { altKey: true }, + { metaKey: true }, + { ctrlKey: true }, + { isComposing: true }, +])("preserves modified Up behavior for %j", async (options) => { + const editor = await mountEditor(draft); + await act(async () => { + expect(press(editor, "ArrowUp", options)).toBe(false); + editor.commands.insertContent("x"); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe(draft.replace("> **", "> **x")); +}); + +it("leaves literal Markdown navigation to the browser in plain mode", async () => { + const editor = await mountEditor(draft, false); + await act(async () => { + editor.commands.setTextSelection(5); + expect(press(editor, "ArrowUp")).toBe(false); + editor.commands.insertContent("x"); + }); + expect(serializeEditorDoc(editor.state.doc).value).toBe(draft.replace("> **", "> **x")); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 3717db8e51c0..61b2a280f841 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1239,7 +1239,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { } } if ( - (event.key === "ArrowLeft" || event.key === "ArrowRight") && + ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) && !event.shiftKey && !event.altKey && !event.metaKey && @@ -1248,10 +1248,22 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { view.state.selection.empty ) { const { $from } = view.state.selection; - const direction = event.key === "ArrowLeft" ? -1 : 1; + const direction = event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 1; + const horizontal = event.key === "ArrowLeft" || event.key === "ArrowRight"; + // At the document's ends, native Up/Down can cross a marker without + // changing the document position. Record the stop so DOM selection + // synchronization does not put the caret back inside the styling. + const atDocumentEdge = + $from.pos === + (direction === -1 + ? TextSelection.atStart(view.state.doc).from + : TextSelection.atEnd(view.state.doc).to); // Take the other stop of a styled edge before skipping a chip, so // the plain stop between styled text and a chip stays reachable. - const step = stepCaretAcrossStyledEdge(view.state, direction); + const step = + horizontal || atDocumentEdge + ? stepCaretAcrossStyledEdge(view.state, direction) + : null; if (step) { event.preventDefault(); event.stopPropagation(); @@ -1259,7 +1271,7 @@ function ComposerPromptEditorTiptapInner(props: ComposerPromptEditorProps) { return true; } const adjacent = direction === -1 ? $from.nodeBefore : $from.nodeAfter; - if (adjacent?.type.name.startsWith("composer-")) { + if (horizontal && adjacent?.type.name.startsWith("composer-")) { event.preventDefault(); event.stopPropagation(); view.dispatch( diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index ec0a872f6730..92913ba6bb0e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -711,6 +711,7 @@ type ThreadStatusInput = Pick< | "hasActionableProposedPlan" | "hasPendingApprovals" | "hasPendingUserInput" + | "pendingSubagentRequest" | "interactionMode" | "latestRun" | "runtime" @@ -1037,7 +1038,7 @@ export function shouldRecedeSidebarThread(input: { type SidebarThreadStatusInput = Pick< SidebarThreadSummary, - "hasPendingApprovals" | "hasPendingUserInput" | "runtime" + "hasPendingApprovals" | "hasPendingUserInput" | "pendingSubagentRequest" | "runtime" >; export function resolveSidebarThreadStatus( @@ -1045,10 +1046,10 @@ export function resolveSidebarThreadStatus( connection?: EnvironmentConnectionPresentation, ): SidebarThreadStatus { if (connection?.blockedReason === "workspace-missing") return "expired"; - if (thread.hasPendingApprovals) { + if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") { return "approval"; } - if (thread.hasPendingUserInput) { + if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") { return "input"; } if ( @@ -1246,7 +1247,7 @@ export function resolveThreadStatusPill(input: { }): ThreadStatusPill | null { const { thread } = input; - if (thread.hasPendingApprovals) { + if (thread.hasPendingApprovals || thread.pendingSubagentRequest === "approval") { return { label: "Pending Approval", colorClass: "text-amber-600 dark:text-amber-300/90", @@ -1255,7 +1256,7 @@ export function resolveThreadStatusPill(input: { }; } - if (thread.hasPendingUserInput) { + if (thread.hasPendingUserInput || thread.pendingSubagentRequest === "user_input") { return { label: "Awaiting Input", colorClass: "text-indigo-600 dark:text-indigo-300/90", diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 58a44ad553ff..a730be28634a 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -73,6 +73,7 @@ import { CircleAlertIcon, CircleCheckIcon, CircleDashedIcon, + CircleDotDashedIcon, ClockIcon, EyeIcon, FolderIcon, @@ -131,21 +132,21 @@ import { isMacPlatform } from "~/lib/utils"; import { useOpenPrLink } from "../lib/openPullRequestLink"; import { readLocalApi } from "../localApi"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; -import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject"; +import { selectProjectGroupingSettings } from "../logicalProject"; import { - buildSidebarProjectSnapshots, projectGroupsSpanEnvironments, resolveSidebarProjectScopeKey, getSidebarProjectSettingsKey, type SidebarProjectSnapshot, } from "../sidebarProjectGrouping"; -import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore"; +import { useUiStateStore } from "../uiStateStore"; import { getThreadKeysToDeselectAfterDelete, useThreadSelectionStore, } from "../threadSelectionStore"; import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; +import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups"; import { useTerminalFocus } from "../hooks/useTerminalFocus"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; @@ -237,7 +238,6 @@ import { sidebarThreadKeyAtY, sortInboxThreadsByReturn, sortPinnedThreadsForSidebar, - sortSidebarV2ProjectGroups, sortThreadsForSidebar, sortWorkingThreadsBySend, useThreadJumpHintVisibility, @@ -281,6 +281,7 @@ import { type ProviderInstanceEntry, } from "../providerInstances"; import { useThreadRunningTerminalIds } from "../state/terminalSessions"; +import { useStableCallback } from "../hooks/useStableCallback"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { Button, InlineButton } from "./ui/button"; import { @@ -1156,7 +1157,12 @@ const SIDEBAR_TOP_STATUS: Record< working: { label: "Working", icon: "working", Icon: CircleDashedIcon, className: "text-info" }, // Waiting is calm background presence (post-settle background roster), not // active progress, so the label keeps full strength. - waiting: { label: "Waiting", icon: null, Icon: null, className: "text-muted-foreground" }, + waiting: { + label: "Waiting", + icon: "waiting", + Icon: CircleDotDashedIcon, + className: "text-muted-foreground", + }, approval: { label: "Approval", icon: "approval", @@ -2158,6 +2164,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { > {topStatus.icon === "working" ? ( + ) : topStatus.icon === "waiting" ? ( + ) : topStatus.icon === "input" ? ( ) : topStatus.icon === "approval" ? ( @@ -2175,6 +2183,12 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { + ) : status === "waiting" ? ( + // Waiting starts when the turn ends and background + // work keeps the thread held. + + + ) : null} ) @@ -2516,14 +2530,12 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { export default function Sidebar() { const projects = useProjects(); - const projectOrder = useUiStateStore((store) => store.projectOrder); const threads = useThreadShells(); const router = useRouter(); const { isMobile, setOpenMobile } = useSidebar(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive); - const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); const timestampFormat = useClientSettings((s) => s.timestampFormat); const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled); const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); @@ -2659,41 +2671,7 @@ export default function Sidebar() { [environments], ); const environmentMachineById = useEnvironmentMachines(); - const orderedProjects = useMemo( - () => - orderItemsByPreferredIds({ - items: projects, - preferredIds: projectOrder, - getId: getProjectOrderKey, - getPreferenceIds: (project) => [ - getProjectOrderKey(project), - legacyProjectCwdPreferenceKey(project.workspaceRoot), - ], - }), - [projectOrder, projects], - ); - const unsortedProjectGroups = useMemo( - () => - buildSidebarProjectSnapshots({ - projects: sidebarProjectSortOrder === "manual" ? orderedProjects : projects, - groupScratchProjects: true, - settings: projectGroupingSettings, - primaryEnvironmentId, - resolveEnvironmentLabel: (environmentId) => environmentLabelById.get(environmentId) ?? null, - }), - [ - environmentLabelById, - orderedProjects, - primaryEnvironmentId, - projectGroupingSettings, - projects, - sidebarProjectSortOrder, - ], - ); - const projectGroups = useMemo( - () => sortSidebarV2ProjectGroups(unsortedProjectGroups, threads, sidebarProjectSortOrder), - [sidebarProjectSortOrder, threads, unsortedProjectGroups], - ); + const projectGroups = useSidebarProjectGroups(); const projectGroupsRef = useRef(projectGroups); projectGroupsRef.current = projectGroups; // Threads on non-primary environments (T3 Connect, hosted) resolve their @@ -2781,20 +2759,19 @@ export default function Sidebar() { () => projectGroupsSpanEnvironments(projectGroups), [projectGroups], ); - const scratchMachineLabelFor = useCallback( - (thread: Pick) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }, - [environmentLabelById, projectByKey, serverConfigs, showProjectEnvironments], - ); + const scratchMachineLabelFor = ( + thread: Pick, + ) => { + if (!showProjectEnvironments) return null; + const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); + if ( + !project || + !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) + ) { + return null; + } + return environmentLabelById.get(thread.environmentId) ?? null; + }; const projectGroupByScopeKey = useMemo( () => new Map(projectGroups.map((project) => [project.projectKey, project] as const)), [projectGroups], @@ -2898,7 +2875,7 @@ export default function Sidebar() { clearSelection(); }, [clearSelection, projectScopeKey]); - const openProjectSettings = useCallback( + const openProjectSettings = useStableCallback( (projectGroup: SidebarProjectSnapshot, projectRef?: ScopedProjectRef) => { if (isMobile) { setOpenMobile(false); @@ -2915,7 +2892,6 @@ export default function Sidebar() { }, }); }, - [isMobile, projectGroupingSettings, projects, router, setOpenMobile], ); // Anchor for the scope popup: the header search field, not its icon trigger. const headerSearchRef = useRef(null); @@ -2923,7 +2899,7 @@ export default function Sidebar() { // selection, then clear the guard when the picker opens again. const suppressNextScopeChangeRef = useRef(false); const highlightedProjectScopeKeyRef = useRef(null); - const handleProjectSettings = useCallback( + const handleProjectSettings = useStableCallback( ( event: ReactMouseEvent | ReactKeyboardEvent, projectGroup: SidebarProjectSnapshot, @@ -2934,7 +2910,6 @@ export default function Sidebar() { dispatchProjectScopeMenu({ type: "project-settings-opened" }); openProjectSettings(projectGroup); }, - [openProjectSettings], ); // Keep a dropped row at its destination while its server applies the @@ -3762,7 +3737,7 @@ export default function Sidebar() { action: SidebarSweepAction; keys: ReadonlySet; } | null>(null); - const startActionSweep = useCallback( + const startActionSweep = useStableCallback( (threadRef: ScopedThreadRef, action: SidebarSweepAction, event: PointerEvent) => { const originKey = scopedThreadKey(threadRef); const originSection = sectionByThreadKeyRef.current.get(originKey); @@ -3821,7 +3796,6 @@ export default function Sidebar() { onAbort: () => {}, }); }, - [attemptUnsettle, attemptUnsnooze, serverConfigs, settleThreads], ); const pinnedKeys = useMemo( () => @@ -4440,7 +4414,7 @@ export default function Sidebar() { ); const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection); - const handleMultiSelectContextMenu = useCallback( + const handleMultiSelectContextMenu = useStableCallback( async (position: { x: number; y: number }) => { const api = readLocalApi(); if (!api) return; @@ -4700,22 +4674,9 @@ export default function Sidebar() { }), ); }, - [ - attemptUnpin, - clearSelection, - confirmThreadDelete, - deleteThread, - markThreadUnread, - performSnooze, - removeFromSelection, - serverConfigs, - settleThreads, - updateThreadMetadata, - timestampFormat, - ], ); - const handleDraftContextMenu = useCallback( + const handleDraftContextMenu = useStableCallback( (draftId: DraftId, position: { x: number; y: number }) => { void (async () => { const api = readLocalApi(); @@ -4765,10 +4726,9 @@ export default function Sidebar() { } })(); }, - [copyBranchToClipboard, copyPathToClipboard, openProjectSettings, projectByKey], ); - const handleThreadContextMenu = useCallback( + const handleThreadContextMenu = useStableCallback( (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { void (async () => { const api = readLocalApi(); @@ -5042,33 +5002,6 @@ export default function Sidebar() { } })(); }, - [ - archiveThread, - attemptPin, - attemptSettle, - attemptSnooze, - attemptUnpin, - attemptUnsettle, - attemptUnsnooze, - confirmThreadArchive, - confirmThreadDelete, - copyBranchToClipboard, - copyPathToClipboard, - copyThreadIdToClipboard, - deleteThread, - stopProvisionedCloudMachine, - handleMultiSelectContextMenu, - markThreadUnread, - openProjectSettings, - projectScopeKey, - projectByKey, - serverConfigs, - setProjectScopeKey, - setThreadAutoSettle, - startThreadRename, - updateThreadMetadata, - timestampFormat, - ], ); // Thread jump (cmd+1..9) and prev/next traversal reuse the same commands as diff --git a/apps/web/src/components/ThreadNotificationCoordinator.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.test.tsx index 36709813ef0e..89ad8c722125 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.test.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.test.tsx @@ -21,6 +21,7 @@ const state = vi.hoisted(() => ({ limited: false, subagent: false, background: [] as Array<{ taskId: string; kind: "command" | "monitor" }>, + delegatedChild: null as "running" | "approval" | null, add: vi.fn( (_toast: { title: string; description: string; actionProps: { onClick: () => void } }) => "toast-1", @@ -87,10 +88,33 @@ function mockThreadShell() { }; } +// A delegated child changes while its parent's shell object stays the same. +let stableParent: ReturnType | null = null; +function mockThreads() { + if (state.delegatedChild === null) return [mockThreadShell()]; + stableParent ??= mockThreadShell(); + const child = { + ...mockThreadShell(), + id: "child-1", + title: "Review the login form", + creationSource: "mcp", + lineage: { + rootThreadId: "thread-1", + parentThreadId: "thread-1", + relationshipToParent: "subagent", + }, + pendingRuntimeRequest: + state.delegatedChild === "approval" + ? { id: "request-2", kind: "command", createdAt: SHELL_NOW } + : null, + }; + return [stableParent, child]; +} + vi.mock("@effect/atom-react", () => ({ useAtomValue: () => ({ status: state.live ? "live" : "disconnected", - snapshot: Option.some({ threads: [mockThreadShell()] }), + snapshot: Option.some({ threads: mockThreads() }), }), })); vi.mock("@tanstack/react-router", () => ({ @@ -154,7 +178,9 @@ beforeEach(() => { limited: false, subagent: false, background: [], + delegatedChild: null, }); + stableParent = null; vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); vi.stubGlobal("window", new EventTarget()); vi.stubGlobal("document", { @@ -188,6 +214,19 @@ describe("thread notifications", () => { expect(state.notification).not.toHaveBeenCalled(); }); + it("alerts on the parent when its delegated subagent asks for approval", async () => { + state.mode = "notifications-and-sound"; + state.delegatedChild = "running"; + await render(); + state.delegatedChild = "approval"; + await render(); + await render(); + expect(state.add).toHaveBeenCalledTimes(1); + expect(state.add).toHaveBeenLastCalledWith( + expect.objectContaining({ title: "Approval needed", description: "Fix the login form" }), + ); + }); + it("alerts once with system alerts off and opens the completed thread", async () => { await render(); await complete(); diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsx index d1f31bc1f33d..ac15d8aeefca 100644 --- a/apps/web/src/components/ThreadNotificationCoordinator.tsx +++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx @@ -1,4 +1,8 @@ -import { presentThreadShell } from "@t3tools/client-runtime/state/models"; +import { + type PendingSubagentRequest, + presentThreadShell, +} from "@t3tools/client-runtime/state/models"; +import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads"; import { useAtomValue } from "@effect/atom-react"; import { useNavigate, useParams } from "@tanstack/react-router"; import { @@ -102,6 +106,7 @@ export function ThreadNotificationCoordinator() { interface NotificationState { readonly raw: OrchestrationV2ThreadShell; + readonly subagentRequest: PendingSubagentRequest | null; readonly attention: string | null; readonly completion: number | null; } @@ -136,15 +141,18 @@ function EnvironmentNotifications({ return; } const next = new Map(); + // Subagents are skipped below, so their requests notify through the thread above them. + const subagentRequests = pendingSubagentRequestsByThread(threads); for (const rawThread of threads) { if (rawThread.lineage.relationshipToParent === "subagent") continue; const prior = previous.current.get(rawThread.id); + const subagentRequest = subagentRequests.get(rawThread.id) ?? null; // The same object cannot produce a new notification. - if (prior?.raw === rawThread) { + if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) { next.set(rawThread.id, prior); continue; } - const thread = presentThreadShell(environmentId, rawThread); + const thread = presentThreadShell(environmentId, rawThread, subagentRequest); let status = resolveSidebarThreadStatus(thread); if (status === "ready" && thread.latestRun?.status === "failed") status = "failed"; const attention = @@ -159,7 +167,7 @@ function EnvironmentNotifications({ Number.isFinite(completedAt) ? completedAt : (prior?.completion ?? null); - next.set(thread.id, { raw: rawThread, attention, completion }); + next.set(thread.id, { raw: rawThread, subagentRequest, attention, completion }); if (!prior || thread.archivedAt !== null) continue; const kind = attention && attention !== prior.attention diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index d42a39e3a70d..de314137fb9e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -44,6 +44,7 @@ import type { SnapShotSource, } from "@t3tools/contracts"; import { + EnvironmentRequestInvalidError, AuthOrchestrationOperateScope, ProviderDriverKind, ProviderInstanceId, @@ -53,6 +54,8 @@ import { PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import * as Schema from "effect/Schema"; import { isPasteAsTextShortcut, nextPastedTextFileName, @@ -69,6 +72,7 @@ import { type ReactNode, useCallback, useEffect, + useEffectEvent, useId, useImperativeHandle, useLayoutEffect, @@ -248,7 +252,7 @@ import { threadContextReference, } from "~/lib/composerContextRecords"; import { matchComposerThreadItems } from "@t3tools/client-runtime/composerThreadItems"; -import { THREAD_CONTEXT_DROP_EVENT, threadContextDropTargetProps } from "./threadContextDrag"; +import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; import { readThreadShell, useThreadShells } from "~/state/entities"; import { requestConfirmDialog } from "~/confirmDialog"; import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; @@ -261,6 +265,8 @@ import { resolveAssetUrl } from "~/assets/assetUrls"; import { assetEnvironment } from "~/state/assets"; import { readPreparedConnection } from "~/state/session"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; +import { orchestrationEnvironment } from "~/state/orchestration"; +import { threadContextAttachment } from "~/lib/threadContextAttachment"; import { pullRequestEnvironment, usePullRequestList, @@ -339,6 +345,10 @@ import { import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { pendingDraftWork } from "./pendingDraftWork"; +import { + importComposerThreadAttachment, + remainingComposerAttachmentSlots, +} from "./composerThreadImport"; import { isTimelineScrollTarget } from "./timelineScrollTarget"; import { createComposerScrollGestureState, @@ -420,6 +430,7 @@ function SnapShotAttachmentFrame({ } const COMPOSER_PULL_REQUEST_LIST_LIMIT = 99; +const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); const COMPOSER_PULL_REQUEST_RESULT_LIMIT = 12; const EMPTY_PULL_REQUEST_LIST_TARGETS: ReadonlyArray> = []; @@ -1145,6 +1156,7 @@ import { import { searchProviderSkills } from "../../providerSkillSearch"; import { useDelayedStatus } from "../../hooks/useDelayedStatus"; import { useMediaQuery } from "../../hooks/useMediaQuery"; +import { useStableCallback } from "../../hooks/useStableCallback"; import { usePanelAnimationSettings } from "../../panelAnimations"; import { useAtomCommand } from "../../state/use-atom-command"; import { readEnvironmentScope } from "../../state/session"; @@ -2554,6 +2566,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) * the next draft. */ const pendingImageCompressionsRef = useRef>(new Map()); + const pendingThreadImportsRef = useRef>(new Map()); const isRevertingCheckpointRef = useRef(isRevertingCheckpoint); isRevertingCheckpointRef.current = isRevertingCheckpoint; @@ -3012,27 +3025,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Provider traits UI // ------------------------------------------------------------------ - const setPromptFromTraits = useCallback( - (nextPrompt: string) => { - if (nextPrompt === promptRef.current) { - scheduleComposerFocus(); - return; - } - promptRef.current = nextPrompt; - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length); - setComposerCursor(nextCursor); - setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); + const setPromptFromTraits = (nextPrompt: string) => { + if (nextPrompt === promptRef.current) { scheduleComposerFocus(); - }, - [ - composerDraftTarget, - promptRef, - scheduleComposerFocus, - setComposerDraftPrompt, - setComposerTrigger, - ], - ); + return; + } + promptRef.current = nextPrompt; + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length); + setComposerCursor(nextCursor); + setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); + scheduleComposerFocus(); + }; + const setPromptFromTraitsStable = useStableCallback(setPromptFromTraits); const providerTraitsMenuContent = renderProviderTraitsMenuContent({ provider: selectedProvider, @@ -3044,7 +3049,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) modelOptions: composerModelOptions?.[selectedInstanceId], reportedModelSelection, prompt, - onPromptChange: setPromptFromTraits, + onPromptChange: setPromptFromTraitsStable, planModeEnabled: settings.planModeEnabled, }); const providerTraitsPickerInput = { @@ -3057,7 +3062,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) modelOptions: composerModelOptions?.[selectedInstanceId], reportedModelSelection, prompt, - onPromptChange: setPromptFromTraits, + onPromptChange: setPromptFromTraitsStable, planModeEnabled: settings.planModeEnabled, isComposerOwned: true, } satisfies Parameters[0]; @@ -3118,66 +3123,39 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Prompt helpers // ------------------------------------------------------------------ - const setPrompt = useCallback( - (nextPrompt: string) => { - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - }, - [composerDraftTarget, setComposerDraftPrompt], - ); + const setPrompt = (nextPrompt: string) => { + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + }; - const addComposerImage = useCallback( - (image: ComposerImageAttachment) => addComposerDraftImages(attachmentDraftTarget, [image]), - [attachmentDraftTarget, addComposerDraftImages], - ); + const addComposerImage = (image: ComposerImageAttachment) => + addComposerDraftImages(attachmentDraftTarget, [image]); - const addComposerImagesToDraft = useCallback( - (images: ComposerImageAttachment[]) => addComposerDraftImages(attachmentDraftTarget, images), - [attachmentDraftTarget, addComposerDraftImages], - ); + const addComposerImagesToDraft = (images: ComposerImageAttachment[]) => + addComposerDraftImages(attachmentDraftTarget, images); - const addComposerFilesToDraft = useCallback( - (files: ComposerFileAttachment[]) => - addComposerDraftFiles(attachmentDraftTarget, files, { - appendReference: questionAttachmentTarget === null, - }), - [addComposerDraftFiles, attachmentDraftTarget, questionAttachmentTarget], - ); + const addComposerFilesToDraft = (files: ComposerFileAttachment[]) => + addComposerDraftFiles(attachmentDraftTarget, files, { + appendReference: questionAttachmentTarget === null, + }); - const removeComposerImageFromDraft = useCallback( - (imageId: string) => { - if (questionAttachmentTarget && activePendingIsResponding) return; - releaseAttachmentUpload(imageId); - removeComposerDraftImage(attachmentDraftTarget, imageId); - }, - [ - attachmentDraftTarget, - questionAttachmentTarget, - activePendingIsResponding, - removeComposerDraftImage, - ], - ); + const removeComposerImageFromDraft = (imageId: string) => { + if (questionAttachmentTarget && activePendingIsResponding) return; + releaseAttachmentUpload(imageId); + removeComposerDraftImage(attachmentDraftTarget, imageId); + }; - const removeComposerFileFromDraft = useCallback( - (fileId: string) => { - if (questionAttachmentTarget && activePendingIsResponding) return; - // Release by the draft attachment, not the bare queue key: a hydrated - // file's upload lives server-side under its persisted attachment id. - const file = composerFilesRef.current.find((candidate) => candidate.id === fileId); - if (file) { - releaseDraftAttachment(file); - } else { - releaseAttachmentUpload(fileId); - } - removeComposerDraftFile(attachmentDraftTarget, fileId); - }, - [ - attachmentDraftTarget, - questionAttachmentTarget, - activePendingIsResponding, - composerFilesRef, - removeComposerDraftFile, - ], - ); + const removeComposerFileFromDraft = (fileId: string) => { + if (questionAttachmentTarget && activePendingIsResponding) return; + // Release by the draft attachment, not the bare queue key: a hydrated + // file's upload lives server-side under its persisted attachment id. + const file = composerFilesRef.current.find((candidate) => candidate.id === fileId); + if (file) { + releaseDraftAttachment(file); + } else { + releaseAttachmentUpload(fileId); + } + removeComposerDraftFile(attachmentDraftTarget, fileId); + }; const addComposerDraftTerminalContexts = useComposerDraftStore( (store) => store.addTerminalContexts, @@ -3188,300 +3166,314 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts); const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts); - const buildContextClipboardFragment = useCallback( - (contextIds: ReadonlyArray): string | null => { - const wanted = new Set(contextIds); - // An annotation's screenshot is referenced by the annotation record, not by the copied - // text. Pull it in so the round-trip keeps the image the annotation points at. - for (const annotation of composerPreviewAnnotations) { - if ( - wanted.has(previewAnnotationContextId(annotation.id)) && - composerImages.some((image) => image.id === annotation.id) - ) { - wanted.add(toKindScopedComposerContextId("image", annotation.id)); - } + const buildContextClipboardFragment = (contextIds: ReadonlyArray): string | null => { + const wanted = new Set(contextIds); + // An annotation's screenshot is referenced by the annotation record, not by the copied + // text. Pull it in so the round-trip keeps the image the annotation points at. + for (const annotation of composerPreviewAnnotations) { + if ( + wanted.has(previewAnnotationContextId(annotation.id)) && + composerImages.some((image) => image.id === annotation.id) + ) { + wanted.add(toKindScopedComposerContextId("image", annotation.id)); } - const records: ComposerContextRecord[] = [ - ...composerTerminalContexts - .filter((c) => wanted.has(terminalContextReference(c).contextId)) - .map(terminalContextRecord), - ...composerThreadContexts.filter((record) => wanted.has(record.contextId)), - ...composerReviewComments - .filter((c) => wanted.has(reviewCommentContextId(c.id))) - .map(reviewCommentContextRecord), - ...composerPreviewAnnotations - .filter((a) => wanted.has(previewAnnotationContextId(a.id))) - .map((annotation) => - previewAnnotationContextRecord(annotation, { - screenshotContextId: composerImages.some((image) => image.id === annotation.id) - ? annotation.id - : undefined, - }), - ), - ...[...composerImages, ...composerFiles] - .filter((attachment) => - wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)), - ) - .flatMap((attachment) => { - const record = uploadedAttachmentContextRecord( - attachment, - uploadsByImageId[attachment.id], - ); - return record ? [record] : []; + } + const records: ComposerContextRecord[] = [ + ...composerTerminalContexts + .filter((c) => wanted.has(terminalContextReference(c).contextId)) + .map(terminalContextRecord), + ...composerThreadContexts.filter((record) => wanted.has(record.contextId)), + ...composerReviewComments + .filter((c) => wanted.has(reviewCommentContextId(c.id))) + .map(reviewCommentContextRecord), + ...composerPreviewAnnotations + .filter((a) => wanted.has(previewAnnotationContextId(a.id))) + .map((annotation) => + previewAnnotationContextRecord(annotation, { + screenshotContextId: composerImages.some((image) => image.id === annotation.id) + ? annotation.id + : undefined, }), - ]; - if (records.length === 0) return null; - return encodeComposerContextFragment({ - version: 1, - source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) }, - records, - }); - }, - [ - activeThread, - composerFiles, - composerImages, - composerPreviewAnnotations, - composerReviewComments, - composerTerminalContexts, - composerThreadContexts, - environmentId, - uploadsByImageId, - ], - ); + ), + ...[...composerImages, ...composerFiles] + .filter((attachment) => + wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)), + ) + .flatMap((attachment) => { + const record = uploadedAttachmentContextRecord( + attachment, + uploadsByImageId[attachment.id], + ); + return record ? [record] : []; + }), + ]; + if (records.length === 0) return null; + return encodeComposerContextFragment({ + version: 1, + source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) }, + records, + }); + }; + const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { reportFailure: false }); + const loadThreadTranscript = useAtomCommand(orchestrationEnvironment.threadTranscript, { + reportFailure: false, + }); + const countReservedAttachments = () => { + const questionRequest = pendingUserInputs[0]; + const otherQuestionKeys = + questionAttachmentTarget && questionRequest && activeThreadId + ? questionRequest.questions + .map((question) => + questionAttachmentDraftId( + environmentId, + activeThreadId, + questionRequest.requestId, + question.id, + ), + ) + .filter((key) => key !== questionAttachmentTarget) + : []; + const draft = getComposerDraft(attachmentDraftTarget); + return ( + (draft?.images.length ?? 0) + + (draft?.files.length ?? 0) + + (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) + + (pendingThreadImportsRef.current.get(attachmentTargetKey) ?? 0) + + countQuestionAttachments(otherQuestionKeys) + ); + }; + const countReservedAttachmentsStable = useStableCallback(countReservedAttachments); /** * Bytes for a pasted image or file come back through the source environment's asset URL * (the client is the only party that can reach both) and re-enter this draft as a normal * attachment under a fresh id. The pasted chip is rewritten to that id and reads as * unresolved until the bytes land; a failed transfer says so and leaves the chip to remove. */ - const runAttachmentImport = useCallback( - async ( - record: Extract, - localId: string, - sourceEnvironmentId: EnvironmentId, - importTargetKey: string, - ) => { - const fail = (reason: string) => { - toastManager.add({ - type: "error", - title: `Couldn't bring ${record.name} into this message`, - description: `${reason} Remove the chip or attach the file again.`, - }); - }; - const sourceConnection = readPreparedConnection(sourceEnvironmentId); - if (!sourceConnection) { - fail("The environment it came from is not connected."); - return; - } - const result = await createAssetUrl({ - environmentId: sourceEnvironmentId, - input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } }, + const runAttachmentImport = async ( + record: Extract, + localId: string, + sourceEnvironmentId: EnvironmentId, + importTargetKey: string, + ) => { + const fail = (reason: string) => { + toastManager.add({ + type: "error", + title: `Couldn't bring ${record.name} into this message`, + description: `${reason} Remove the chip or attach the file again.`, }); - const url = - result._tag === "Success" - ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl) - : null; - if (!url) { - fail("The original attachment is no longer available."); - return; - } - let blob: Blob; - try { - const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - blob = await response.blob(); - } catch { - fail("Downloading it from the source failed."); - return; - } - const file = new File([blob], record.name, { type: record.mimeType || blob.type }); - // The draft these bytes belong to may have been sent or switched away from while they - // downloaded. Dropping them here keeps them out of whatever draft is open now. - if (attachmentTargetKeyRef.current !== importTargetKey) return; - if (record.kind === "image") { - const accepted = addComposerImage({ - type: "image", + }; + const sourceConnection = readPreparedConnection(sourceEnvironmentId); + if (!sourceConnection) { + fail("The environment it came from is not connected."); + return; + } + const result = await createAssetUrl({ + environmentId: sourceEnvironmentId, + input: { resource: { _tag: "attachment", attachmentId: record.attachmentId } }, + }); + const url = + result._tag === "Success" + ? resolveAssetUrl(sourceConnection.httpBaseUrl, result.value.relativeUrl) + : null; + if (!url) { + fail("The original attachment is no longer available."); + return; + } + let blob: Blob; + try { + const response = await fetch(url, { signal: AbortSignal.timeout(60_000) }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + blob = await response.blob(); + } catch { + fail("Downloading it from the source failed."); + return; + } + const file = new File([blob], record.name, { type: record.mimeType || blob.type }); + // The draft these bytes belong to may have been sent or switched away from while they + // downloaded. Dropping them here keeps them out of whatever draft is open now. + if (attachmentTargetKeyRef.current !== importTargetKey) return; + const replacesFileMarker = + record.kind === "file" && + composerFilesRef.current.some( + (candidate) => + composerFileNeedsReattach(candidate) && + composerFileMatchesReattachMarker(candidate, { + name: record.name, + mimeType: file.type, + sizeBytes: file.size, + }), + ); + if ( + !replacesFileMarker && + (pendingThreadImportsRef.current.get(importTargetKey) ?? 0) > 0 && + countReservedAttachments() >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS + ) { + fail("The attachment limit has been reached."); + return; + } + if (record.kind === "image") { + const accepted = addComposerImage({ + type: "image", + id: localId, + name: record.name, + mimeType: file.type, + sizeBytes: file.size, + previewUrl: URL.createObjectURL(file), + file, + }); + if (!accepted.includes(localId)) + fail("The draft rejected this attachment (duplicate or attachment limit reached)."); + } else { + const accepted = addComposerFilesToDraft([ + { + type: "file", id: localId, name: record.name, mimeType: file.type, sizeBytes: file.size, - previewUrl: URL.createObjectURL(file), file, - }); - if (!accepted.includes(localId)) - fail("The draft rejected this attachment (duplicate or attachment limit reached)."); - } else { - const accepted = addComposerFilesToDraft([ - { - type: "file", - id: localId, - name: record.name, - mimeType: file.type, - sizeBytes: file.size, - file, - }, - ]); - if (!accepted.includes(localId)) - fail("The draft rejected this attachment (duplicate or attachment limit reached)."); - } - }, - [addComposerFilesToDraft, addComposerImage, attachmentTargetKey, createAssetUrl], - ); - const importAttachmentRecord = useCallback( - async ( - record: Extract, - localId: string, - sourceEnvironmentId: EnvironmentId, - ) => { - // The chip lands in the draft immediately while these bytes are still downloading. Count - // the transfer against its own draft so a send cannot snapshot a message whose chip has no - // attachment behind it, and so bytes for an abandoned draft never enter the next one. - const importTargetKey = attachmentTargetKey; - pendingDraftWork.begin(importTargetKey); - try { - await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey); - } finally { - pendingDraftWork.end(importTargetKey); - } - }, - [attachmentTargetKey, runAttachmentImport], - ); + }, + ]); + if (!accepted.includes(localId)) + fail("The draft rejected this attachment (duplicate or attachment limit reached)."); + } + }; + const importAttachmentRecord = async ( + record: Extract, + localId: string, + sourceEnvironmentId: EnvironmentId, + ) => { + // The chip lands in the draft immediately while these bytes are still downloading. Count + // the transfer against its own draft so a send cannot snapshot a message whose chip has no + // attachment behind it, and so bytes for an abandoned draft never enter the next one. + const importTargetKey = attachmentTargetKey; + pendingDraftWork.begin(importTargetKey); + try { + await runAttachmentImport(record, localId, sourceEnvironmentId, importTargetKey); + } finally { + pendingDraftWork.end(importTargetKey); + } + }; /** * Brings records into this draft (paste, stash restore). Binaries are transferred only * when `sourceEnvironmentId` is given; the stash restores its own images and files. */ - const importContextRecords = useCallback( - ( - records: ReadonlyArray, - sourceEnvironmentId: EnvironmentId | null, - ): ReadonlyMap => { - const rewritten = new Map(); - const dependentAttachmentLocalIds = new Map(); - const skippedDependentAttachmentIds = new Set(); - // Resolve annotations before their dependent screenshot records even if a foreign - // clipboard producer emitted the records in a different order. - const orderedRecords = records.toSorted((left, right) => - left.kind === "preview-annotation" && right.kind !== "preview-annotation" - ? -1 - : right.kind === "preview-annotation" && left.kind !== "preview-annotation" - ? 1 - : 0, - ); - for (const candidate of orderedRecords) { - // Producer ids fold into context ids, so two different excerpts can collide. Only skip - // when the draft already holds the same payload; a colliding but different record is - // re-minted under a fresh id so both survive the paste. - const record = asKnownContextRecord(candidate); - if (!record) continue; - const existing = composerContextImportLookupIds(record).flatMap((contextId) => { - const found = composerContextRecords.get(contextId); - return found ? [found] : []; - })[0]; - const existingRecord = - existing?.kind === "terminal" - ? terminalContextRecord(existing.record) - : existing?.kind === "review-comment" - ? reviewCommentContextRecord(existing.record) - : existing?.kind === "preview-annotation" - ? previewAnnotationContextRecord(existing.record) - : existing?.kind === "thread" - ? existing.record - : existing - ? (uploadedContextRecordFromDraft(existing) ?? undefined) - : undefined; - if (existingRecord && isSameComposerContextPayload(existingRecord, record)) { + const importContextRecords = ( + records: ReadonlyArray, + sourceEnvironmentId: EnvironmentId | null, + ): ReadonlyMap => { + const rewritten = new Map(); + const dependentAttachmentLocalIds = new Map(); + const skippedDependentAttachmentIds = new Set(); + // Resolve annotations before their dependent screenshot records even if a foreign + // clipboard producer emitted the records in a different order. + const orderedRecords = records.toSorted((left, right) => + left.kind === "preview-annotation" && right.kind !== "preview-annotation" + ? -1 + : right.kind === "preview-annotation" && left.kind !== "preview-annotation" + ? 1 + : 0, + ); + for (const candidate of orderedRecords) { + // Producer ids fold into context ids, so two different excerpts can collide. Only skip + // when the draft already holds the same payload; a colliding but different record is + // re-minted under a fresh id so both survive the paste. + const record = asKnownContextRecord(candidate); + if (!record) continue; + const existing = composerContextImportLookupIds(record).flatMap((contextId) => { + const found = composerContextRecords.get(contextId); + return found ? [found] : []; + })[0]; + const existingRecord = + existing?.kind === "terminal" + ? terminalContextRecord(existing.record) + : existing?.kind === "review-comment" + ? reviewCommentContextRecord(existing.record) + : existing?.kind === "preview-annotation" + ? previewAnnotationContextRecord(existing.record) + : existing?.kind === "thread" + ? existing.record + : existing + ? (uploadedContextRecordFromDraft(existing) ?? undefined) + : undefined; + if (existingRecord && isSameComposerContextPayload(existingRecord, record)) { + if (record.kind === "preview-annotation" && record.screenshotContextId) { + skippedDependentAttachmentIds.add(record.screenshotContextId); + } + continue; + } + const conflicts = existing !== undefined; + switch (record.kind) { + case "terminal": { + const threadId = activeThread?.id ?? activeThreadId; + if (!threadId) break; + const imported = terminalContextDraftFromRecord(record, threadId); + const draft = conflicts ? { ...imported, id: randomUUID() } : imported; + addComposerDraftTerminalContexts(composerDraftTarget, [draft], { + appendReference: false, + }); + rewritten.set(record.contextId, terminalContextReference(draft).contextId); + break; + } + case "review-comment": { + const imported = reviewCommentFromRecord(record); + const comment = conflicts ? { ...imported, id: randomUUID() } : imported; + addComposerDraftReviewComment(composerDraftTarget, comment, { + appendReference: false, + }); + rewritten.set(record.contextId, reviewCommentContextId(comment.id)); + break; + } + case "element": + case "preview-annotation": { + const imported = + record.kind === "element" + ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString()) + : previewAnnotationFromRecord(record); + const annotation = conflicts ? { ...imported, id: randomUUID() } : imported; if (record.kind === "preview-annotation" && record.screenshotContextId) { - skippedDependentAttachmentIds.add(record.screenshotContextId); + dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id); } - continue; + addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, { + appendReference: false, + }); + rewritten.set(record.contextId, previewAnnotationContextId(annotation.id)); + break; } - const conflicts = existing !== undefined; - switch (record.kind) { - case "terminal": { - const threadId = activeThread?.id ?? activeThreadId; - if (!threadId) break; - const imported = terminalContextDraftFromRecord(record, threadId); - const draft = conflicts ? { ...imported, id: randomUUID() } : imported; - addComposerDraftTerminalContexts(composerDraftTarget, [draft], { - appendReference: false, - }); - rewritten.set(record.contextId, terminalContextReference(draft).contextId); - break; - } - case "review-comment": { - const imported = reviewCommentFromRecord(record); - const comment = conflicts ? { ...imported, id: randomUUID() } : imported; - addComposerDraftReviewComment(composerDraftTarget, comment, { - appendReference: false, - }); - rewritten.set(record.contextId, reviewCommentContextId(comment.id)); - break; - } - case "element": - case "preview-annotation": { - const imported = - record.kind === "element" - ? elementContextToPreviewAnnotation(record, randomUUID(), new Date().toISOString()) - : previewAnnotationFromRecord(record); - const annotation = conflicts ? { ...imported, id: randomUUID() } : imported; - if (record.kind === "preview-annotation" && record.screenshotContextId) { - dependentAttachmentLocalIds.set(record.screenshotContextId, annotation.id); - } - addComposerDraftPreviewAnnotation(composerDraftTarget, annotation, { - appendReference: false, - }); - rewritten.set(record.contextId, previewAnnotationContextId(annotation.id)); - break; - } - case "thread": { - // The agent can only read threads on its own server; a pasted foreign one is dropped. - if (record.environmentId !== environmentId) break; - addComposerDraftThreadContexts(attachmentDraftTarget, [record], { - appendReference: false, - }); + case "thread": { + // The agent can only read threads on its own server; a pasted foreign one is dropped. + if (record.environmentId !== environmentId) break; + addComposerDraftThreadContexts(attachmentDraftTarget, [record], { + appendReference: false, + }); + rewritten.set(record.contextId, record.contextId); + break; + } + case "image": + case "file": { + if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (sourceEnvironmentId === null && !conflicts) { rewritten.set(record.contextId, record.contextId); break; } - case "image": - case "file": { - if (skippedDependentAttachmentIds.has(record.contextId)) break; - if (sourceEnvironmentId === null && !conflicts) { - rewritten.set(record.contextId, record.contextId); - break; - } - if (sourceEnvironmentId === null) break; - const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID(); - rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId)); - void importAttachmentRecord(record, localId, sourceEnvironmentId); - break; - } - default: - break; + if (sourceEnvironmentId === null) break; + const localId = dependentAttachmentLocalIds.get(record.contextId) ?? randomUUID(); + rewritten.set(record.contextId, toKindScopedComposerContextId(record.kind, localId)); + void importAttachmentRecord(record, localId, sourceEnvironmentId); + break; } + default: + break; } - return rewritten; - }, - [ - activeThread, - activeThreadId, - addComposerDraftPreviewAnnotation, - addComposerDraftReviewComment, - addComposerDraftTerminalContexts, - addComposerDraftThreadContexts, - composerContextRecords, - attachmentDraftTarget, - composerDraftTarget, - environmentId, - importAttachmentRecord, - ], - ); - const importContextFragment = useCallback( - (fragment: ComposerContextClipboardFragment): ReadonlyMap => - importContextRecords(fragment.records, fragment.source.environmentId), - [importContextRecords], - ); + } + return rewritten; + }; + const importContextFragment = ( + fragment: ComposerContextClipboardFragment, + ): ReadonlyMap => + importContextRecords(fragment.records, fragment.source.environmentId); + const importContextFragmentStable = useStableCallback(importContextFragment); // ------------------------------------------------------------------ // Sync refs back to parent @@ -3744,7 +3736,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Callbacks: prompt change // ------------------------------------------------------------------ - const expandComposerForEditorChange = useCallback(() => { + const expandComposerForEditorChange = () => { // Editor changes win over the momentum tail of the active scroll gesture. suppressActiveComposerScrollGesture( composerScrollGestureRef.current, @@ -3752,7 +3744,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) COMPOSER_SCROLL_GESTURE_RESET_MS, ); setIsComposerScrollCollapsed(false); - }, [setIsComposerScrollCollapsed]); + }; + const expandComposerForEditorChangeStable = useStableCallback(expandComposerForEditorChange); /** * Payloads for chips the prompt no longer references. History undo restores the @@ -3769,260 +3762,216 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) previewAnnotations: new Map(), }); - const onPromptChange = useCallback( - ( - nextPrompt: string, - nextCursor: number, - expandedCursor: number, - cursorAdjacentToMention: boolean, - contextIds: string[], - ) => { - expandComposerForEditorChange(); - if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) { - if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return; - setComposerCursor(nextCursor); - setComposerTrigger( - cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), - ); - onChangeActivePendingUserInputCustomAnswer( - activePendingProgress.activeQuestion.id, - nextPrompt, - nextCursor, - expandedCursor, - cursorAdjacentToMention, - ); - return; - } - onTypingGuardDraftChange(); - promptRef.current = nextPrompt; - setPrompt(nextPrompt); - // Any edit ends browsing, even one later undone by hand: typing a - // character and deleting it leaves the text equal to the recall, and - // ArrowDown must move the caret then, not clear the composer. - if (promptHistoryPositionRef.current?.recalled !== nextPrompt) { - promptHistoryPositionRef.current = null; - } - const referenced = new Set(contextIds); - const retained = removedContextPayloadsRef.current; - - // An undone delete brings the reference back; restore the payload it points at. - const liveTerminalIds = new Set( - composerTerminalContexts.map((context) => terminalContextReference(context).contextId), + const onPromptChange = ( + nextPrompt: string, + nextCursor: number, + expandedCursor: number, + cursorAdjacentToMention: boolean, + contextIds: string[], + ) => { + expandComposerForEditorChange(); + if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) { + if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return; + setComposerCursor(nextCursor); + setComposerTrigger( + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), ); - const restoredTerminals = [...referenced].flatMap((contextId) => { - if (liveTerminalIds.has(contextId)) return []; - const context = retained.terminals.get(contextId); - return context ? [context] : []; - }); - const nextTerminals = [ - ...composerTerminalContexts.filter((context) => - referenced.has(terminalContextReference(context).contextId), - ), - ...restoredTerminals, - ]; - for (const context of composerTerminalContexts) { - const contextId = terminalContextReference(context).contextId; - if (!referenced.has(contextId)) retained.terminals.set(contextId, context); - } - if ( - nextTerminals.length !== composerTerminalContexts.length || - restoredTerminals.length > 0 - ) { - setComposerDraftTerminalContexts(composerDraftTarget, nextTerminals); - } - - const liveThreadIds = new Set( - composerThreadContexts.map((record) => record.contextId), + onChangeActivePendingUserInputCustomAnswer( + activePendingProgress.activeQuestion.id, + nextPrompt, + nextCursor, + expandedCursor, + cursorAdjacentToMention, ); - const restoredThreads = [...referenced].flatMap((contextId) => { - if (liveThreadIds.has(contextId)) return []; - const record = retained.threads.get(contextId); - return record ? [record] : []; - }); - const nextThreads = [ - ...composerThreadContexts.filter((record) => referenced.has(record.contextId)), - ...restoredThreads, - ]; - for (const record of composerThreadContexts) { - if (!referenced.has(record.contextId)) retained.threads.set(record.contextId, record); - } - if (nextThreads.length !== composerThreadContexts.length || restoredThreads.length > 0) { - setComposerDraftThreadContexts(composerDraftTarget, nextThreads); - } + return; + } + onTypingGuardDraftChange(); + promptRef.current = nextPrompt; + setPrompt(nextPrompt); + // Any edit ends browsing, even one later undone by hand: typing a + // character and deleting it leaves the text equal to the recall, and + // ArrowDown must move the caret then, not clear the composer. + if (promptHistoryPositionRef.current?.recalled !== nextPrompt) { + promptHistoryPositionRef.current = null; + } + const referenced = new Set(contextIds); + const retained = removedContextPayloadsRef.current; - for (const comment of composerReviewComments) { - const contextId = reviewCommentContextId(comment.id); - if (!referenced.has(contextId)) { - retained.reviewComments.set(contextId, comment); - removeComposerDraftReviewComment(composerDraftTarget, comment.id); - } + // An undone delete brings the reference back; restore the payload it points at. + const liveTerminalIds = new Set( + composerTerminalContexts.map((context) => terminalContextReference(context).contextId), + ); + const restoredTerminals = [...referenced].flatMap((contextId) => { + if (liveTerminalIds.has(contextId)) return []; + const context = retained.terminals.get(contextId); + return context ? [context] : []; + }); + const nextTerminals = [ + ...composerTerminalContexts.filter((context) => + referenced.has(terminalContextReference(context).contextId), + ), + ...restoredTerminals, + ]; + for (const context of composerTerminalContexts) { + const contextId = terminalContextReference(context).contextId; + if (!referenced.has(contextId)) retained.terminals.set(contextId, context); + } + if (nextTerminals.length !== composerTerminalContexts.length || restoredTerminals.length > 0) { + setComposerDraftTerminalContexts(composerDraftTarget, nextTerminals); + } + + const liveThreadIds = new Set(composerThreadContexts.map((record) => record.contextId)); + const restoredThreads = [...referenced].flatMap((contextId) => { + if (liveThreadIds.has(contextId)) return []; + const record = retained.threads.get(contextId); + return record ? [record] : []; + }); + const nextThreads = [ + ...composerThreadContexts.filter((record) => referenced.has(record.contextId)), + ...restoredThreads, + ]; + for (const record of composerThreadContexts) { + if (!referenced.has(record.contextId)) retained.threads.set(record.contextId, record); + } + if (nextThreads.length !== composerThreadContexts.length || restoredThreads.length > 0) { + setComposerDraftThreadContexts(composerDraftTarget, nextThreads); + } + + for (const comment of composerReviewComments) { + const contextId = reviewCommentContextId(comment.id); + if (!referenced.has(contextId)) { + retained.reviewComments.set(contextId, comment); + removeComposerDraftReviewComment(composerDraftTarget, comment.id); } - const liveReviewIds = new Set( - composerReviewComments.map((comment) => reviewCommentContextId(comment.id)), - ); - for (const contextId of referenced) { - if (liveReviewIds.has(contextId)) continue; - const comment = retained.reviewComments.get(contextId); - if (comment) { - addComposerDraftReviewComment(composerDraftTarget, comment, { appendReference: false }); - } + } + const liveReviewIds = new Set( + composerReviewComments.map((comment) => reviewCommentContextId(comment.id)), + ); + for (const contextId of referenced) { + if (liveReviewIds.has(contextId)) continue; + const comment = retained.reviewComments.get(contextId); + if (comment) { + addComposerDraftReviewComment(composerDraftTarget, comment, { appendReference: false }); } + } - const attachmentChanges = reconcileAttachmentContextReferences({ - referencedContextIds: referenced, - files: composerFiles, - images: composerImages, - previewAnnotations: composerPreviewAnnotations, - retained: removedAttachmentContextPayloadsRef.current, + const attachmentChanges = reconcileAttachmentContextReferences({ + referencedContextIds: referenced, + files: composerFiles, + images: composerImages, + previewAnnotations: composerPreviewAnnotations, + retained: removedAttachmentContextPayloadsRef.current, + }); + for (const annotationId of attachmentChanges.annotationIdsToRemove) { + // Keep the upload queue entry alive: undo restores the image that owns it. + removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId); + } + for (const restored of attachmentChanges.annotationsToRestore) { + if (restored.image) addComposerDraftImages(attachmentDraftTarget, [restored.image]); + addComposerDraftPreviewAnnotation(composerDraftTarget, restored.annotation, { + appendReference: false, }); - for (const annotationId of attachmentChanges.annotationIdsToRemove) { - // Keep the upload queue entry alive: undo restores the image that owns it. - removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId); - } - for (const restored of attachmentChanges.annotationsToRestore) { - if (restored.image) addComposerDraftImages(attachmentDraftTarget, [restored.image]); - addComposerDraftPreviewAnnotation(composerDraftTarget, restored.annotation, { - appendReference: false, - }); - } - for (const fileId of attachmentChanges.filesToRemove) { - // The retained File and upload are still sendable if the editor restores the chip. - removeComposerDraftFile(attachmentDraftTarget, fileId); - } - if (attachmentChanges.filesToRestore.length > 0) { - addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); - } - setComposerCursor(nextCursor); - setComposerTrigger( - cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), - ); - }, - [ - activePendingProgress?.activeQuestion, - expandComposerForEditorChange, - onTypingGuardDraftChange, - pendingUserInputs.length, - onChangeActivePendingUserInputCustomAnswer, - promptRef, - setPrompt, - setComposerTrigger, - composerDraftTarget, - composerTerminalContexts, - setComposerDraftTerminalContexts, - composerThreadContexts, - setComposerDraftThreadContexts, - composerReviewComments, - composerPreviewAnnotations, - composerImages, - composerFiles, - removeComposerDraftReviewComment, - removeComposerDraftPreviewAnnotation, - removeComposerDraftFile, - addComposerDraftReviewComment, - addComposerDraftPreviewAnnotation, - addComposerDraftImages, - addComposerDraftFiles, - attachmentDraftTarget, - ], - ); + } + for (const fileId of attachmentChanges.filesToRemove) { + // The retained File and upload are still sendable if the editor restores the chip. + removeComposerDraftFile(attachmentDraftTarget, fileId); + } + if (attachmentChanges.filesToRestore.length > 0) { + addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); + } + setComposerCursor(nextCursor); + setComposerTrigger( + cursorAdjacentToMention ? null : detectComposerTrigger(nextPrompt, expandedCursor), + ); + }; + const onPromptChangeStable = useStableCallback(onPromptChange); // ------------------------------------------------------------------ // Callbacks: prompt replacement / menu // ------------------------------------------------------------------ - const applyPromptReplacement = useCallback( - ( - rangeStart: number, - rangeEnd: number, - replacement: string, - options?: { - expectedText?: string; - expandedCursorAfterReplace?: number; - focusEditorAfterReplace?: boolean; - citationComment?: { - start: number; - sourceAnchor: AssistantCitationSourceAnchor; - insertedSpaces: ComposerCitationCommentRequest["insertedSpaces"]; - }; - }, - ): boolean => { - if ( - activePendingUserInput && - activePendingProgress?.activeQuestion?.allowCustomAnswer === false - ) { - return false; - } - const currentText = promptRef.current; - const safeStart = Math.max(0, Math.min(currentText.length, rangeStart)); - const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd)); - if ( - options?.expectedText !== undefined && - currentText.slice(safeStart, safeEnd) !== options.expectedText - ) { - return false; - } - const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement); - const nextCursor = collapseExpandedComposerCursor( - next.text, - options?.expandedCursorAfterReplace ?? next.cursor, - isLiteralPendingAnswer, - ); - const nextExpandedCursor = expandCollapsedComposerCursor( + const applyPromptReplacement = ( + rangeStart: number, + rangeEnd: number, + replacement: string, + options?: { + expectedText?: string; + expandedCursorAfterReplace?: number; + focusEditorAfterReplace?: boolean; + citationComment?: { + start: number; + sourceAnchor: AssistantCitationSourceAnchor; + insertedSpaces: ComposerCitationCommentRequest["insertedSpaces"]; + }; + }, + ): boolean => { + if ( + activePendingUserInput && + activePendingProgress?.activeQuestion?.allowCustomAnswer === false + ) { + return false; + } + const currentText = promptRef.current; + const safeStart = Math.max(0, Math.min(currentText.length, rangeStart)); + const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd)); + if ( + options?.expectedText !== undefined && + currentText.slice(safeStart, safeEnd) !== options.expectedText + ) { + return false; + } + const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement); + const nextCursor = collapseExpandedComposerCursor( + next.text, + options?.expandedCursorAfterReplace ?? next.cursor, + isLiteralPendingAnswer, + ); + const nextExpandedCursor = expandCollapsedComposerCursor( + next.text, + nextCursor, + isLiteralPendingAnswer, + ); + if (options?.citationComment) { + composerEditorRef.current?.requestCitationComment({ + previousValue: currentText, + value: next.text, + citationStart: options.citationComment.start, + sourceAnchor: options.citationComment.sourceAnchor, + insertedSpaces: options.citationComment.insertedSpaces, + }); + } + promptRef.current = next.text; + const activePendingQuestion = activePendingProgress?.activeQuestion; + if (activePendingQuestion && activePendingUserInput) { + onChangeActivePendingUserInputCustomAnswer( + activePendingQuestion.id, next.text, nextCursor, + nextExpandedCursor, isLiteralPendingAnswer, ); - if (options?.citationComment) { - composerEditorRef.current?.requestCitationComment({ - previousValue: currentText, - value: next.text, - citationStart: options.citationComment.start, - sourceAnchor: options.citationComment.sourceAnchor, - insertedSpaces: options.citationComment.insertedSpaces, - }); - } - promptRef.current = next.text; - const activePendingQuestion = activePendingProgress?.activeQuestion; - if (activePendingQuestion && activePendingUserInput) { - onChangeActivePendingUserInputCustomAnswer( - activePendingQuestion.id, - next.text, - nextCursor, - nextExpandedCursor, - isLiteralPendingAnswer, - ); - } else { - setPrompt(next.text); - onTypingGuardDraftChange(); - } - setComposerCursor(nextCursor); - setComposerTrigger( - isLiteralPendingAnswer ? null : detectComposerTrigger(next.text, nextExpandedCursor), - ); - if (options?.focusEditorAfterReplace !== false) { - window.requestAnimationFrame(() => { - // Type-to-focus routes only the first key through here; once the - // controlled update focuses the editor, later keys land natively. - // Skip the deferred caret placement when the draft has moved on, - // or it drags the caret back behind what was typed since. - if (promptRef.current !== next.text) return; - composerEditorRef.current?.focusAt(nextCursor); - }); - } - return true; - }, - [ - activePendingProgress?.activeQuestion, - activePendingUserInput, - isLiteralPendingAnswer, - onChangeActivePendingUserInputCustomAnswer, - onTypingGuardDraftChange, - promptRef, - setPrompt, - setComposerTrigger, - ], - ); + } else { + setPrompt(next.text); + onTypingGuardDraftChange(); + } + setComposerCursor(nextCursor); + setComposerTrigger( + isLiteralPendingAnswer ? null : detectComposerTrigger(next.text, nextExpandedCursor), + ); + if (options?.focusEditorAfterReplace !== false) { + window.requestAnimationFrame(() => { + // Type-to-focus routes only the first key through here; once the + // controlled update focuses the editor, later keys land natively. + // Skip the deferred caret placement when the draft has moved on, + // or it drags the caret back behind what was typed since. + if (promptRef.current !== next.text) return; + composerEditorRef.current?.focusAt(nextCursor); + }); + } + return true; + }; + const applyPromptReplacementStable = useStableCallback(applyPromptReplacement); - const readComposerSnapshot = useCallback((): { + const readComposerSnapshot = (): { value: string; cursor: number; expandedCursor: number; @@ -4042,9 +3991,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ), contextIds: isLiteralPendingAnswer ? [] : collectInlineContextIds(promptRef.current), }; - }, [composerCursor, isLiteralPendingAnswer, promptRef]); + }; + const readComposerSnapshotStable = useStableCallback(readComposerSnapshot); - const resolveActiveComposerTrigger = useCallback((): { + const resolveActiveComposerTrigger = (): { snapshot: { value: string; cursor: number; expandedCursor: number }; trigger: ComposerTrigger | null; } => { @@ -4055,200 +4005,167 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? null : resolveComposerTrigger(detectComposerTrigger(snapshot.value, snapshot.expandedCursor)), }; - }, [isLiteralPendingAnswer, readComposerSnapshot, resolveComposerTrigger]); + }; const { onUsageLimitsCommand } = props; - const onSelectComposerItem = useCallback( - (item: ComposerCommandItem) => { - if (composerSelectLockRef.current) return; - composerSelectLockRef.current = true; - window.requestAnimationFrame(() => { - composerSelectLockRef.current = false; + const onSelectComposerItem = (item: ComposerCommandItem) => { + if (composerSelectLockRef.current) return; + composerSelectLockRef.current = true; + window.requestAnimationFrame(() => { + composerSelectLockRef.current = false; + }); + const { snapshot, trigger } = resolveActiveComposerTrigger(); + if (!trigger) return; + if (item.type === "path") { + const replacement = `${serializeComposerFileLink(item.path)} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), }); - const { snapshot, trigger } = resolveActiveComposerTrigger(); - if (!trigger) return; - if (item.type === "path") { - const replacement = `${serializeComposerFileLink(item.path)} `; - const replacementRangeEnd = extendReplacementRangeForTrailingSpace( - snapshot.value, - trigger.rangeEnd, - replacement, - ); - const applied = applyPromptReplacement( - trigger.rangeStart, - replacementRangeEnd, - replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, - ); - if (applied) { - setComposerHighlightedItemId(null); - } - return; + if (applied) { + setComposerHighlightedItemId(null); } - if (item.type === "slash-command") { - if (item.command === "model") { - const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { - expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), - focusEditorAfterReplace: false, - }); - if (applied) { - setComposerHighlightedItemId(null); - setIsComposerModelPickerOpen(true); - } - return; - } - if (!planModeUiEnabled) return; - void handleInteractionModeChange(item.command === "plan" ? "plan" : "default"); + return; + } + if (item.type === "slash-command") { + if (item.command === "model") { const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + focusEditorAfterReplace: false, }); if (applied) { setComposerHighlightedItemId(null); + setIsComposerModelPickerOpen(true); } return; } - if (item.type === "provider-slash-command") { - if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) { - const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { - expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), - focusEditorAfterReplace: false, - }); - if (applied) { - setComposerHighlightedItemId(null); - onUsageLimitsCommand(); - } - return; - } - const replacement = `/${item.command.name} `; - const replacementRangeEnd = extendReplacementRangeForTrailingSpace( - snapshot.value, - trigger.rangeEnd, - replacement, - ); - const applied = applyPromptReplacement( - trigger.rangeStart, - replacementRangeEnd, - replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, - ); - if (applied) { - setComposerHighlightedItemId(null); - } - return; + if (!planModeUiEnabled) return; + void handleInteractionModeChange(item.command === "plan" ? "plan" : "default"); + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); } - if (item.type === "skill") { - const replacement = `$${item.skill.name} `; - const replacementRangeEnd = extendReplacementRangeForTrailingSpace( - snapshot.value, - trigger.rangeEnd, - replacement, - ); - const applied = applyPromptReplacement( - trigger.rangeStart, - replacementRangeEnd, - replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, - ); + return; + } + if (item.type === "provider-slash-command") { + if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) { + const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { + expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), + focusEditorAfterReplace: false, + }); if (applied) { setComposerHighlightedItemId(null); + onUsageLimitsCommand(); } return; } - if (item.type === "pull-request") { - if ( - trigger.kind !== "pull-request" || - !composerMenuItemsRef.current.some((candidate) => candidate.id === item.id) - ) { - return; - } - const comment = buildPullRequestReferenceContext(item.pullRequest); - const replacement = `${formatInlineContextReference( - reviewCommentContextReference(comment), - )} `; - const replacementRangeEnd = extendReplacementRangeForTrailingSpace( - snapshot.value, - trigger.rangeEnd, - replacement, - ); - const applied = applyPromptReplacement( - trigger.rangeStart, - replacementRangeEnd, - replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, - ); - if (applied) { - addComposerDraftReviewComment(composerDraftTarget, comment, { - appendReference: false, - }); - setComposerHighlightedItemId(null); - } - return; + const replacement = `/${item.command.name} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); } - if (item.type === "thread") { - if (trigger.kind !== "path") return; - const shell = readThreadShell(item.thread); - if (!shell) return; - const record = threadContextRecord(item.thread, shell.title); - const replacement = `${formatInlineContextReference(threadContextReference(record))} `; - const replacementRangeEnd = extendReplacementRangeForTrailingSpace( - snapshot.value, - trigger.rangeEnd, - replacement, - ); - const applied = applyPromptReplacement( - trigger.rangeStart, - replacementRangeEnd, - replacement, - { expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd) }, - ); - if (applied) { - addComposerDraftThreadContexts(attachmentDraftTarget, [record], { - appendReference: false, - }); - setComposerHighlightedItemId(null); - } + return; + } + if (item.type === "skill") { + const replacement = `$${item.skill.name} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } + if (item.type === "pull-request") { + if ( + trigger.kind !== "pull-request" || + !composerMenuItemsRef.current.some((candidate) => candidate.id === item.id) + ) { return; } - }, - [ - addComposerDraftReviewComment, - addComposerDraftThreadContexts, - applyPromptReplacement, - attachmentDraftTarget, - composerDraftTarget, - handleInteractionModeChange, - planModeUiEnabled, - onUsageLimitsCommand, - resolveActiveComposerTrigger, - ], - ); + const comment = buildPullRequestReferenceContext(item.pullRequest); + const replacement = `${formatInlineContextReference( + reviewCommentContextReference(comment), + )} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), + }); + if (applied) { + addComposerDraftReviewComment(composerDraftTarget, comment, { + appendReference: false, + }); + setComposerHighlightedItemId(null); + } + return; + } + if (item.type === "thread") { + if (trigger.kind !== "path") return; + const shell = readThreadShell(item.thread); + if (!shell) return; + const record = threadContextRecord(item.thread, shell.title); + const replacement = `${formatInlineContextReference(threadContextReference(record))} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), + }); + if (applied) { + addComposerDraftThreadContexts(attachmentDraftTarget, [record], { + appendReference: false, + }); + setComposerHighlightedItemId(null); + } + return; + } + }; + const onSelectComposerItemStable = useStableCallback(onSelectComposerItem); - const onComposerMenuItemHighlighted = useCallback( - (itemId: string | null) => { - setComposerHighlightedItemId(itemId); - setComposerHighlightedSearchKey(composerMenuSearchKey); - }, - [composerMenuSearchKey], - ); + const onComposerMenuItemHighlighted = (itemId: string | null) => { + setComposerHighlightedItemId(itemId); + setComposerHighlightedSearchKey(composerMenuSearchKey); + }; + const onComposerMenuItemHighlightedStable = useStableCallback(onComposerMenuItemHighlighted); - const nudgeComposerMenuHighlight = useCallback( - (key: "ArrowDown" | "ArrowUp") => { - if (composerMenuItems.length === 0) return; - const highlightedIndex = composerMenuItems.findIndex( - (item) => item.id === composerHighlightedItemId, - ); - const normalizedIndex = - highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0; - const offset = key === "ArrowDown" ? 1 : -1; - const nextIndex = - (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length; - const nextItem = composerMenuItems[nextIndex]; - setComposerHighlightedItemId(nextItem?.id ?? null); - }, - [composerHighlightedItemId, composerMenuItems], - ); + const nudgeComposerMenuHighlight = (key: "ArrowDown" | "ArrowUp") => { + if (composerMenuItems.length === 0) return; + const highlightedIndex = composerMenuItems.findIndex( + (item) => item.id === composerHighlightedItemId, + ); + const normalizedIndex = highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0; + const offset = key === "ArrowDown" ? 1 : -1; + const nextIndex = + (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length; + const nextItem = composerMenuItems[nextIndex]; + setComposerHighlightedItemId(nextItem?.id ?? null); + }; - const blurMobileComposerAfterSend = useCallback(() => { + const blurMobileComposerAfterSend = () => { if (!isMobileViewport) return; if (composerBlurFrameRef.current !== null) { window.cancelAnimationFrame(composerBlurFrameRef.current); @@ -4259,9 +4176,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeElement.blur(); } setIsComposerFocused(false); - }, [isMobileViewport, setIsComposerFocused]); + }; - const shouldBlurMobileComposerOnSubmit = useCallback(() => { + const shouldBlurMobileComposerOnSubmit = () => { if (!isMobileViewport) return false; if ( isSendBusy || @@ -4277,120 +4194,87 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } return showPlanFollowUpPrompt || composerSendState.hasSendableContent; - }, [ - activePendingProgress, - activePendingResolvedAnswers, - composerSendState.hasSendableContent, - environmentUnavailable, - isConnecting, - isMobileViewport, - isSendBusy, - isSendDisabled, - noProviderAvailable, - phase, - showPlanFollowUpPrompt, - ]); + }; - const submitComposer = useCallback( - ( - event?: { preventDefault: () => void }, - dispatchMode?: ComposerDispatchMode, - submissionIntent?: ComposerSubmissionIntent, - ) => { - if ( - noProviderAvailable || - isSendDisabled || - !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) - ) { - event?.preventDefault(); - return; - } - // A send while a pasted image is still compressing would strand that - // image: the turn snapshot wouldn't include it, and it would surface - // in the *next* draft instead. Only oversized images hit this — small - // files clear the pending counter within a microtask. - if ( - activeThreadId && - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0 - ) { - event?.preventDefault(); - toastManager.add({ - type: "info", - title: "Still compressing a pasted image.", - description: "Send again once its thumbnail appears.", - }); - return; - } - // A pasted chip's bytes arrive over the network, so the same hazard applies for longer: - // sending now would snapshot a chip with no attachment behind it. - if (pendingDraftWork.has(attachmentTargetKey)) { - event?.preventDefault(); - toastManager.add({ - type: "info", - title: "Still bringing a pasted attachment into this message.", - description: "Send again once its chip resolves.", - }); - return; - } - const submission = submitComposerDraft({ - prompt: promptRef.current, - submissionTarget: activePendingProgress ? "pending-user-input" : "provider-turn", - event, - onSend: (sendEvent) => { - // ChatView reports its final composed-input preflight through the - // composer handle before its first asynchronous send step. - providerInputRejectedRef.current = false; - onSend( - sendEvent, - dispatchMode ?? - resolveComposerDispatchMode({ - running: phase === "running", - alternateModifier: false, - activeTurnDefault: settings.followUpBehavior, - }), - submissionIntent, - ); - return !providerInputRejectedRef.current; - }, + const submitComposer = ( + event?: { preventDefault: () => void }, + dispatchMode?: ComposerDispatchMode, + submissionIntent?: ComposerSubmissionIntent, + ) => { + if ( + noProviderAvailable || + isSendDisabled || + !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) + ) { + event?.preventDefault(); + return; + } + // A send while a pasted image is still compressing would strand that + // image: the turn snapshot wouldn't include it, and it would surface + // in the *next* draft instead. Only oversized images hit this — small + // files clear the pending counter within a microtask. + if (activeThreadId && (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0) { + event?.preventDefault(); + toastManager.add({ + type: "info", + title: "Still compressing a pasted image.", + description: "Send again once its thumbnail appears.", }); - setComposerSubmissionError(submission.validationMessage); - if (!submission.didDispatch) return; - onTypingGuardSend(); - if (shouldBlurMobileComposerOnSubmit()) { - blurMobileComposerAfterSend(); - } - }, - [ - activeThreadId, - activePendingProgress, - attachmentTargetKey, - onTypingGuardSend, - blurMobileComposerAfterSend, - environmentId, - isSendDisabled, - noProviderAvailable, - onSend, - settings.followUpBehavior, - phase, - promptRef, - shouldBlurMobileComposerOnSubmit, - ], - ); - const handleSubmitMessage = useCallback( - (event: React.MouseEvent) => { - event.preventDefault(); - submitComposer( - event, - resolveComposerDispatchMode({ - running: phase === "running", - alternateModifier: event.metaKey || event.ctrlKey, - activeTurnDefault: settings.followUpBehavior, - }), - ); - }, - [phase, settings.followUpBehavior, submitComposer], - ); - const submitCitationAndSend = useCallback(() => { + return; + } + // A pasted chip's bytes arrive over the network, so the same hazard applies for longer: + // sending now would snapshot a chip with no attachment behind it. + if (pendingDraftWork.has(attachmentTargetKey)) { + event?.preventDefault(); + toastManager.add({ + type: "info", + title: "Still bringing attached context into this message.", + description: "Send again once its chip resolves.", + }); + return; + } + const submission = submitComposerDraft({ + prompt: promptRef.current, + submissionTarget: activePendingProgress ? "pending-user-input" : "provider-turn", + event, + onSend: (sendEvent) => { + // ChatView reports its final composed-input preflight through the + // composer handle before its first asynchronous send step. + providerInputRejectedRef.current = false; + onSend( + sendEvent, + dispatchMode ?? + resolveComposerDispatchMode({ + running: phase === "running", + alternateModifier: false, + activeTurnDefault: settings.followUpBehavior, + }), + submissionIntent, + ); + return !providerInputRejectedRef.current; + }, + }); + setComposerSubmissionError(submission.validationMessage); + if (!submission.didDispatch) return; + onTypingGuardSend(); + if (shouldBlurMobileComposerOnSubmit()) { + blurMobileComposerAfterSend(); + } + }; + const submitComposerStable = useStableCallback(submitComposer); + const handleSubmitMessage = (event: React.MouseEvent) => { + event.preventDefault(); + submitComposer( + event, + resolveComposerDispatchMode({ + running: phase === "running", + alternateModifier: event.metaKey || event.ctrlKey, + activeTurnDefault: settings.followUpBehavior, + }), + ); + }; + const handleSubmitMessageStable = useStableCallback(handleSubmitMessage); + const submitCitationAndSend = () => { submitComposer( undefined, resolveComposerDispatchMode({ @@ -4399,18 +4283,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeTurnDefault: settings.followUpBehavior, }), ); - }, [phase, settings.followUpBehavior, submitComposer]); + }; + const submitCitationAndSendStable = useStableCallback(submitCitationAndSend); // A question or approval took the editor while a citation comment was // unsaved. Keep the comment in the prompt that comes back afterward. - const saveCitationDraftToPrompt = useCallback( - (replacedValue: string, savedValue: string) => { - if (replacedValue !== prompt) return; - if (promptRef.current === replacedValue) promptRef.current = savedValue; - setPrompt(savedValue); - }, - [prompt, promptRef, setPrompt], - ); - const compactThreadContext = useCallback(() => { + const saveCitationDraftToPrompt = (replacedValue: string, savedValue: string) => { + if (replacedValue !== prompt) return; + if (promptRef.current === replacedValue) promptRef.current = savedValue; + setPrompt(savedValue); + }; + const saveCitationDraftToPromptStable = useStableCallback(saveCitationDraftToPrompt); + const compactThreadContext = () => { if ( !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || compactDisabled || @@ -4425,20 +4308,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return; } onCompactContext(); - }, [ - activePendingApproval, - activeThreadId, - compactDisabled, - composerDraftTarget, - environmentId, - isConnecting, - isSendBusy, - noProviderAvailable, - onCompactContext, - pendingUserInputs.length, - phase, - ]); - const expandMobileComposer = useCallback(() => { + }; + const compactThreadContextStable = useStableCallback(compactThreadContext); + const expandMobileComposer = () => { if (composerBlurFrameRef.current !== null) { window.cancelAnimationFrame(composerBlurFrameRef.current); composerBlurFrameRef.current = null; @@ -4459,7 +4331,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) mobileComposerExpandInFlightRef.current = false; }); }); - }, [setIsComposerFocused]); + }; + const expandMobileComposerStable = useStableCallback(expandMobileComposer); // ------------------------------------------------------------------ // Prompt history (ArrowUp / ArrowDown) @@ -4477,68 +4350,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptHistoryPositionRef.current = null; }, [promptHistoryTargetKey]); - const replacePromptFromHistory = useCallback( - (nextPrompt: string) => { - promptRef.current = nextPrompt; - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); - setComposerTrigger(null); - setComposerHighlightedItemId(null); - }, - [composerDraftTarget, promptRef, setComposerDraftPrompt, setComposerTrigger], - ); + const replacePromptFromHistory = (nextPrompt: string) => { + promptRef.current = nextPrompt; + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); + setComposerTrigger(null); + setComposerHighlightedItemId(null); + }; - const navigatePromptHistory = useCallback( - (direction: "backward" | "forward", event: KeyboardEvent): boolean => { - if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) { - return false; - } - if (isComposerApprovalState || pendingUserInputs.length > 0) return false; - // A composer holding an image, file, picked element, preview - // annotation, or review comment is not empty. Recalling text into it - // would send the old prompt with the new context, which is never what - // ArrowUp meant. - if ( - composerImagesRef.current.length > 0 || - composerFilesRef.current.length > 0 || - composerTerminalContextsRef.current.length > 0 || - composerPreviewAnnotations.length > 0 || - composerReviewComments.length > 0 - ) { - return false; - } - // A typed draft with no active recall can never step, so skip the - // layout read and the entry build for that common case. - if (promptHistoryPositionRef.current === null && promptRef.current.length > 0) { - return false; - } - const editor = composerEditorRef.current; - if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) { - return false; - } - const step = stepComposerPromptHistory({ - direction, - entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current), - position: promptHistoryPositionRef.current, - currentPrompt: promptRef.current, - }); - if (!step) return false; - promptHistoryPositionRef.current = step.position; - replacePromptFromHistory(step.prompt); - return true; - }, - [ - composerTerminalContextsRef, - composerFilesRef, - composerImagesRef, - composerPreviewAnnotations.length, - composerReviewComments.length, - isComposerApprovalState, - pendingUserInputs.length, - promptRef, - replacePromptFromHistory, - ], - ); + const navigatePromptHistory = ( + direction: "backward" | "forward", + event: KeyboardEvent, + ): boolean => { + if (event.shiftKey || event.altKey || event.metaKey || event.ctrlKey || event.isComposing) { + return false; + } + if (isComposerApprovalState || pendingUserInputs.length > 0) return false; + // A composer holding an image, file, picked element, preview + // annotation, or review comment is not empty. Recalling text into it + // would send the old prompt with the new context, which is never what + // ArrowUp meant. + if ( + composerImagesRef.current.length > 0 || + composerFilesRef.current.length > 0 || + composerTerminalContextsRef.current.length > 0 || + composerPreviewAnnotations.length > 0 || + composerReviewComments.length > 0 + ) { + return false; + } + // A typed draft with no active recall can never step, so skip the + // layout read and the entry build for that common case. + if (promptHistoryPositionRef.current === null && promptRef.current.length > 0) { + return false; + } + const editor = composerEditorRef.current; + if (!editor?.isCaretOnVisualEdge(direction === "backward" ? "start" : "end")) { + return false; + } + const step = stepComposerPromptHistory({ + direction, + entries: buildComposerPromptHistoryEntries(promptHistoryMessagesRef.current), + position: promptHistoryPositionRef.current, + currentPrompt: promptRef.current, + }); + if (!step) return false; + promptHistoryPositionRef.current = step.position; + replacePromptFromHistory(step.prompt); + return true; + }; // ------------------------------------------------------------------ // Callbacks: command key @@ -4648,7 +4508,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, []); /** Briefly highlight the badge so the save registers without a flourish. */ - const pulseStashBadge = useCallback(() => { + const pulseStashBadge = () => { stashPulseKeyRef.current += 1; setStashPulse({ key: stashPulseKeyRef.current, active: true }); if (stashPulseTimeoutRef.current !== null) { @@ -4658,345 +4518,324 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) stashPulseTimeoutRef.current = null; setStashPulse((current) => ({ ...current, active: false })); }, 1200); - }, []); - - const restoreStashEntry = useCallback( - async (menuEntry: PromptStashEntry) => { - const filesToVerify = menuEntry.files ?? []; - if (filesToVerify.some((file) => file.environmentId !== environmentId)) { - toastManager.add({ - type: "error", - title: "Stashed files belong to another environment", - description: "Restore this prompt in the environment that received its files.", - }); - return; - } - setIsStashMenuOpen(false); + }; - // The server sweeps pending uploads after 24 hours, so ask before - // reattaching. An expired upload restores as a needs-reattach row - // instead of a reference the next send would fail to verify. Verify - // BEFORE taking: the take removes the entry from durable storage, and a - // tab closed during this await must still find it there after reload. - const verifications = await Promise.all( - filesToVerify.map((file) => - verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }), - ), - ); - const expiredAttachmentIds = new Set( - filesToVerify - .filter((_, index) => verifications[index]?.status === "missing") - .map((file) => file.attachmentId), - ); + const restoreStashEntry = async (menuEntry: PromptStashEntry) => { + const filesToVerify = menuEntry.files ?? []; + if (filesToVerify.some((file) => file.environmentId !== environmentId)) { + toastManager.add({ + type: "error", + title: "Stashed files belong to another environment", + description: "Restore this prompt in the environment that received its files.", + }); + return; + } + setIsStashMenuOpen(false); - // A thread switch during the verify await would mix the new thread's - // prompt with this invocation's captured target. Nothing was taken yet, - // so abort and leave the entry restorable where the user now is. - if ( - isRevertingCheckpointRef.current || - composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current - ) { - return; - } + // The server sweeps pending uploads after 24 hours, so ask before + // reattaching. An expired upload restores as a needs-reattach row + // instead of a reference the next send would fail to verify. Verify + // BEFORE taking: the take removes the entry from durable storage, and a + // tab closed during this await must still find it there after reload. + const verifications = await Promise.all( + filesToVerify.map((file) => + verifyStashedAttachmentUpload({ environmentId, attachmentId: file.attachmentId }), + ), + ); + const expiredAttachmentIds = new Set( + filesToVerify + .filter((_, index) => verifications[index]?.status === "missing") + .map((file) => file.attachmentId), + ); - // The take is also the double-activation guard (click + Enter): the - // second caller finds the entry gone and stops here. - const { entry, durable } = takeStashEntry(menuEntry.id); - if (!entry) return; - if (!durable) { - toastManager.add({ - type: "warning", - title: "Restored prompt may reappear in the stash", - description: - "Browser storage rejected the update, so this entry could still be there after a reload.", - data: { hideCopyButton: true }, - }); - } + // A thread switch during the verify await would mix the new thread's + // prompt with this invocation's captured target. Nothing was taken yet, + // so abort and leave the entry restorable where the user now is. + if ( + isRevertingCheckpointRef.current || + composerTargetKey(composerDraftTarget) !== composerDraftTargetKeyRef.current + ) { + return; + } - const rewrittenContextIds = entry.records - ? importContextRecords(entry.records, null) - : new Map(); - const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { - const contextId = rewrittenContextIds.get(reference.contextId); - return contextId - ? formatInlineContextReference({ - ...reference, - contextId, - kind: reference.kind === "element" ? "preview-annotation" : reference.kind, - }) - : reference.source; + // The take is also the double-activation guard (click + Enter): the + // second caller finds the entry gone and stops here. + const { entry, durable } = takeStashEntry(menuEntry.id); + if (!entry) return; + if (!durable) { + toastManager.add({ + type: "warning", + title: "Restored prompt may reappear in the stash", + description: + "Browser storage rejected the update, so this entry could still be there after a reload.", + data: { hideCopyButton: true }, }); - const currentPrompt = promptRef.current; - // An image-only stash must not append blank lines to whatever is - // already in the composer. - const nextPrompt = - restoredPrompt.length === 0 - ? currentPrompt - : currentPrompt.trim().length - ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}` - : restoredPrompt; - let promptChanged = nextPrompt !== currentPrompt; - if (promptChanged) { - promptRef.current = nextPrompt; - setComposerDraftPrompt(composerDraftTarget, nextPrompt); - setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); - setComposerTrigger(null); - } + } - let unrestoredFileNames: string[] = []; - const expiredFileNames: string[] = []; - let restoredFileCount = 0; - const stashedFiles = entry.files ?? []; - if (stashedFiles.length > 0) { - const composerFilesNow = composerFilesRef.current; - const existingFileIds = new Set(composerFilesNow.map((file) => file.id)); - const retainedUploadIds = new Set( - composerFilesNow.flatMap((file) => - file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [], - ), - ); - const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey)); - const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach); - const restoredMarkerIds = new Set(); - const duplicateFiles: PersistedComposerFileAttachment[] = []; - const markerReplacements: ComposerFileAttachment[] = []; - const appendedFiles: ComposerFileAttachment[] = []; - for (const file of stashedFiles) { - const expired = expiredAttachmentIds.has(file.attachmentId); - const key = composerFileDedupKey(file); - const restored: ComposerFileAttachment = { - type: "file", - id: file.id, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - file: null, - ...(file.source ? { source: file.source } : {}), - // An expired upload carries no ids, so it hydrates as a - // needs-reattach row and the "Attach again" flow takes over. - ...(expired - ? {} - : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }), - }; - if (existingFileIds.has(file.id)) { - if (!expired && !retainedUploadIds.has(file.attachmentId)) { - duplicateFiles.push(file); - } - continue; - } - const reattachMarker = reattachMarkers.find( - (marker) => - !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file), - ); - if (reattachMarker) { - restoredMarkerIds.add(reattachMarker.id); - existingFileIds.add(file.id); - existingFileKeys.add(key); - if (expired) { - expiredFileNames.push(file.name); - } else { - retainedUploadIds.add(file.attachmentId); - markerReplacements.push(restored); - } - continue; - } - if (existingFileKeys.has(key)) { - if (!expired && !retainedUploadIds.has(file.attachmentId)) { - duplicateFiles.push(file); - } - continue; + const rewrittenContextIds = entry.records + ? importContextRecords(entry.records, null) + : new Map(); + const restoredPrompt = replaceComposerContextReferences(entry.prompt, (reference) => { + const contextId = rewrittenContextIds.get(reference.contextId); + return contextId + ? formatInlineContextReference({ + ...reference, + contextId, + kind: reference.kind === "element" ? "preview-annotation" : reference.kind, + }) + : reference.source; + }); + const currentPrompt = promptRef.current; + // An image-only stash must not append blank lines to whatever is + // already in the composer. + const nextPrompt = + restoredPrompt.length === 0 + ? currentPrompt + : currentPrompt.trim().length + ? `${currentPrompt.replace(/\s+$/, "")}\n\n${restoredPrompt}` + : restoredPrompt; + let promptChanged = nextPrompt !== currentPrompt; + if (promptChanged) { + promptRef.current = nextPrompt; + setComposerDraftPrompt(composerDraftTarget, nextPrompt); + setComposerCursor(collapseExpandedComposerCursor(nextPrompt, nextPrompt.length)); + setComposerTrigger(null); + } + + let unrestoredFileNames: string[] = []; + const expiredFileNames: string[] = []; + let restoredFileCount = 0; + const stashedFiles = entry.files ?? []; + if (stashedFiles.length > 0) { + const composerFilesNow = composerFilesRef.current; + const existingFileIds = new Set(composerFilesNow.map((file) => file.id)); + const retainedUploadIds = new Set( + composerFilesNow.flatMap((file) => + file.uploadedAttachmentId ? [file.uploadedAttachmentId] : [], + ), + ); + const existingFileKeys = new Set(composerFilesNow.map(composerFileDedupKey)); + const reattachMarkers = composerFilesNow.filter(composerFileNeedsReattach); + const restoredMarkerIds = new Set(); + const duplicateFiles: PersistedComposerFileAttachment[] = []; + const markerReplacements: ComposerFileAttachment[] = []; + const appendedFiles: ComposerFileAttachment[] = []; + for (const file of stashedFiles) { + const expired = expiredAttachmentIds.has(file.attachmentId); + const key = composerFileDedupKey(file); + const restored: ComposerFileAttachment = { + type: "file", + id: file.id, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + file: null, + ...(file.source ? { source: file.source } : {}), + // An expired upload carries no ids, so it hydrates as a + // needs-reattach row and the "Attach again" flow takes over. + ...(expired + ? {} + : { uploadedAttachmentId: file.attachmentId, uploadEnvironmentId: environmentId }), + }; + if (existingFileIds.has(file.id)) { + if (!expired && !retainedUploadIds.has(file.attachmentId)) { + duplicateFiles.push(file); } + continue; + } + const reattachMarker = reattachMarkers.find( + (marker) => + !restoredMarkerIds.has(marker.id) && composerFileMatchesReattachMarker(marker, file), + ); + if (reattachMarker) { + restoredMarkerIds.add(reattachMarker.id); existingFileIds.add(file.id); existingFileKeys.add(key); if (expired) { expiredFileNames.push(file.name); } else { retainedUploadIds.add(file.attachmentId); + markerReplacements.push(restored); } - appendedFiles.push(restored); + continue; } - const capacity = Math.max( - 0, - PROVIDER_SEND_TURN_MAX_ATTACHMENTS - - composerImagesRef.current.length - - composerFilesNow.length, - ); - // Marker replacements reuse their marker's slot; only appended files - // consume capacity. - const filesToAppend = appendedFiles.slice(0, capacity); - const skippedFiles = appendedFiles.slice(capacity); - unrestoredFileNames = skippedFiles.map((file) => file.name); - // A non-durable take can resurrect the stash entry after a reload; - // deleting these uploads would leave it pointing at nothing. - if (durable) { - for (const file of duplicateFiles) { + if (existingFileKeys.has(key)) { + if (!expired && !retainedUploadIds.has(file.attachmentId)) { + duplicateFiles.push(file); + } + continue; + } + existingFileIds.add(file.id); + existingFileKeys.add(key); + if (expired) { + expiredFileNames.push(file.name); + } else { + retainedUploadIds.add(file.attachmentId); + } + appendedFiles.push(restored); + } + const capacity = remainingComposerAttachmentSlots( + composerImagesRef.current.length + composerFilesNow.length, + pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, + ); + // Marker replacements reuse their marker's slot; only appended files + // consume capacity. + const filesToAppend = appendedFiles.slice(0, capacity); + const skippedFiles = appendedFiles.slice(capacity); + unrestoredFileNames = skippedFiles.map((file) => file.name); + // A non-durable take can resurrect the stash entry after a reload; + // deleting these uploads would leave it pointing at nothing. + if (durable) { + for (const file of duplicateFiles) { + releasePersistedAttachmentUpload({ + id: file.id, + environmentId, + attachmentId: file.attachmentId, + }); + } + for (const file of skippedFiles) { + if (file.uploadedAttachmentId) { releasePersistedAttachmentUpload({ id: file.id, environmentId, - attachmentId: file.attachmentId, + attachmentId: file.uploadedAttachmentId, }); } - for (const file of skippedFiles) { - if (file.uploadedAttachmentId) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId, - attachmentId: file.uploadedAttachmentId, - }); - } - } } - const restoredFiles = [...markerReplacements, ...filesToAppend]; - if (restoredFiles.length > 0) { - addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true }); - const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt; - if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) { - promptRef.current = restoredFilePrompt; - setComposerCursor( - collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length), - ); - setComposerTrigger(null); - promptChanged = true; - } - restoredFileCount = filesToAppend.length; + } + const restoredFiles = [...markerReplacements, ...filesToAppend]; + if (restoredFiles.length > 0) { + addComposerDraftFiles(composerDraftTarget, restoredFiles, { appendReference: true }); + const restoredFilePrompt = getComposerDraft(composerDraftTarget)?.prompt; + if (restoredFilePrompt !== undefined && restoredFilePrompt !== promptRef.current) { + promptRef.current = restoredFilePrompt; + setComposerCursor( + collapseExpandedComposerCursor(restoredFilePrompt, restoredFilePrompt.length), + ); + setComposerTrigger(null); + promptChanged = true; } + restoredFileCount = filesToAppend.length; } + } - let unrestoredImageNames: string[] = []; - if (entry.attachments.length > 0) { - const existingIds = new Set(composerImagesRef.current.map((image) => image.id)); - // The draft store also dedupes by mimeType+sizeBytes+name, so filter - // on the same key here. Counting a duplicate against capacity would - // burn a slot the store then refuses to fill, pushing a genuinely - // unique image into the overflow list for nothing. - const existingDedupKeys = new Set( - composerImagesRef.current.map( - (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`, + let unrestoredImageNames: string[] = []; + if (entry.attachments.length > 0) { + const existingIds = new Set(composerImagesRef.current.map((image) => image.id)); + // The draft store also dedupes by mimeType+sizeBytes+name, so filter + // on the same key here. Counting a duplicate against capacity would + // burn a slot the store then refuses to fill, pushing a genuinely + // unique image into the overflow list for nothing. + const existingDedupKeys = new Set( + composerImagesRef.current.map( + (image) => `${image.mimeType}\0${image.sizeBytes}\0${image.name}`, + ), + ); + const capacity = remainingComposerAttachmentSlots( + composerImagesRef.current.length + composerFilesRef.current.length + restoredFileCount, + pendingThreadImportsRef.current.get(composerTargetKey(composerDraftTarget)) ?? 0, + ); + const pending = entry.attachments.filter( + (attachment) => + !existingIds.has(attachment.id) && + !existingDedupKeys.has( + `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`, ), - ); - const capacity = Math.max( - 0, - PROVIDER_SEND_TURN_MAX_ATTACHMENTS - - composerImagesRef.current.length - - composerFilesRef.current.length - - restoredFileCount, - ); - const pending = entry.attachments.filter( - (attachment) => - !existingIds.has(attachment.id) && - !existingDedupKeys.has( - `${attachment.mimeType}\0${attachment.sizeBytes}\0${attachment.name}`, - ), - ); - // Anything past the attachment limit cannot be restored. The entry is - // already out of the queue, so report the overflow by name instead of - // discarding it silently. - unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name); - const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity)); - if (restoredImages.length > 0) { - addComposerDraftImages(composerDraftTarget, restoredImages); - } + ); + // Anything past the attachment limit cannot be restored. The entry is + // already out of the queue, so report the overflow by name instead of + // discarding it silently. + unrestoredImageNames = pending.slice(capacity).map((attachment) => attachment.name); + const restoredImages = hydrateImagesFromPersisted(pending.slice(0, capacity)); + if (restoredImages.length > 0) { + addComposerDraftImages(composerDraftTarget, restoredImages); } + } - // Deliberately no model/provider restore: the stash exists to carry a - // prompt across threads and providers, so whatever the composer has - // selected right now stays selected. - - // Each cause gets its own sentence so "too large" is never blamed for a - // file that actually failed to decode, or for one the composer simply - // had no room to take back. - const missingImageReasons: string[] = []; - if (entry.droppedImageNames.length > 0) { - missingImageReasons.push( - `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, - ); - } - if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) { - missingImageReasons.push( - `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`, - ); - } - if (unrestoredImageNames.length > 0) { - missingImageReasons.push( - `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (unrestoredFileNames.length > 0) { - missingImageReasons.push( - `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, - ); - } - if (expiredFileNames.length > 0) { - missingImageReasons.push( - `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`, - ); - } - if (missingImageReasons.length > 0) { - toastManager.add({ - type: "warning", - title: "Some attachments were not restored", - description: missingImageReasons.join(" "), - }); - } + // Deliberately no model/provider restore: the stash exists to carry a + // prompt across threads and providers, so whatever the composer has + // selected right now stays selected. + + // Each cause gets its own sentence so "too large" is never blamed for a + // file that actually failed to decode, or for one the composer simply + // had no room to take back. + const missingImageReasons: string[] = []; + if (entry.droppedImageNames.length > 0) { + missingImageReasons.push( + `${entry.droppedImageNames.join(", ")} exceeded the stash size limit when this prompt was saved.`, + ); + } + if (entry.unreadableImageNames && entry.unreadableImageNames.length > 0) { + missingImageReasons.push( + `${entry.unreadableImageNames.join(", ")} could not be read when this prompt was saved.`, + ); + } + if (unrestoredImageNames.length > 0) { + missingImageReasons.push( + `${unrestoredImageNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, + ); + } + if (unrestoredFileNames.length > 0) { + missingImageReasons.push( + `${unrestoredFileNames.join(", ")} could not be restored: the composer is at its ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}-attachment limit.`, + ); + } + if (expiredFileNames.length > 0) { + missingImageReasons.push( + `${expiredFileNames.join(", ")}: stashed files are kept for 24 hours and this upload expired. Attach the file again.`, + ); + } + if (missingImageReasons.length > 0) { + toastManager.add({ + type: "warning", + title: "Some attachments were not restored", + description: missingImageReasons.join(" "), + }); + } - // Only yank the caret to the end when text was actually inserted; - // restoring images alone should leave the user where they were typing. - if (promptChanged) { - window.requestAnimationFrame(() => { - composerEditorRef.current?.focusAtEnd(); - }); - } - }, - [ - addComposerDraftFiles, - addComposerDraftImages, - composerDraftTarget, - composerFilesRef, - composerImagesRef, - environmentId, - promptRef, - setComposerDraftPrompt, - setComposerTrigger, - takeStashEntry, - importContextRecords, - ], - ); + // Only yank the caret to the end when text was actually inserted; + // restoring images alone should leave the user where they were typing. + if (promptChanged) { + window.requestAnimationFrame(() => { + composerEditorRef.current?.focusAtEnd(); + }); + } + }; + const restoreStashEntryStable = useStableCallback(restoreStashEntry); - const deleteStashEntry = useCallback( - (entry: PromptStashEntry) => { - const { entry: removed, durable } = takeStashEntry(entry.id); - if (!stashQueue.some((candidate) => candidate.id !== entry.id)) { - setIsStashMenuOpen(false); - } - if (durable && removed) { - for (const file of removed.files ?? []) { - releasePersistedAttachmentUpload({ - id: file.id, - environmentId: file.environmentId, - attachmentId: file.attachmentId, - }); - } - } - if (!durable) { - toastManager.add({ - type: "warning", - title: "Stash entry may come back", - description: - "Browser storage rejected the delete, so this prompt could reappear after a reload.", - data: { hideCopyButton: true }, + const deleteStashEntry = (entry: PromptStashEntry) => { + const { entry: removed, durable } = takeStashEntry(entry.id); + if (!stashQueue.some((candidate) => candidate.id !== entry.id)) { + setIsStashMenuOpen(false); + } + if (durable && removed) { + for (const file of removed.files ?? []) { + releasePersistedAttachmentUpload({ + id: file.id, + environmentId: file.environmentId, + attachmentId: file.attachmentId, }); } - }, - [stashQueue, takeStashEntry], - ); + } + if (!durable) { + toastManager.add({ + type: "warning", + title: "Stash entry may come back", + description: + "Browser storage rejected the delete, so this prompt could reappear after a reload.", + data: { hideCopyButton: true }, + }); + } + }; + const deleteStashEntryStable = useStableCallback(deleteStashEntry); - const stashCurrentPrompt = useCallback(async () => { + const stashCurrentPrompt = async () => { // Stashing clears the draft. A pasted attachment still downloading would then land in the // emptied composer instead of travelling with the entry it belongs to. if (pendingDraftWork.has(attachmentTargetKeyRef.current)) { toastManager.add({ type: "info", - title: "Still bringing a pasted attachment into this message.", + title: "Still bringing attached context into this message.", description: "Stash again once its chip resolves.", }); return; @@ -5216,38 +5055,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // snapshot's ⌘S until the composer remounts. stashInFlightRef.current.delete(snapshotKey); } - }, [ - clearComposerDraftPromptAndImages, - clearComposerDraftTerminalContexts, - setComposerDraftPrompt, - setComposerTrigger, - composerDraftTarget, - composerFilesRef, - composerImagesRef, - composerTerminalContextsRef, - composerReviewComments, - composerPreviewAnnotations, - removeComposerDraftReviewComment, - removeComposerDraftPreviewAnnotation, - environmentId, - finalizeStashEntryImages, - promptRef, - pulseStashBadge, - restoreStashEntry, - stashEntryToQueue, - ]); + }; + const stashCurrentPromptStable = useStableCallback(stashCurrentPrompt); - const toggleStashMenu = useCallback(() => { + const toggleStashMenu = () => { if (isComposerCollapsedMobile) { expandMobileComposer(); setIsStashMenuOpen(true); return; } setIsStashMenuOpen((open) => !open); - }, [expandMobileComposer, isComposerCollapsedMobile]); - const toggleTasksDrawer = useCallback(() => { + }; + const toggleStashMenuStable = useStableCallback(toggleStashMenu); + const toggleTasksDrawer = () => { setIsTasksDrawerOpen((open) => !open); - }, []); + }; + const toggleTasksDrawerStable = useStableCallback(toggleTasksDrawer); const hasBannerItems = props.bannerItems.length > 0; const hasBlockingComposerTopDrawer = activePendingApproval !== null || pendingUserInputs.length > 0; @@ -5260,7 +5083,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const inlineTasksBadge = showInlineTasksBadge ? ( @@ -5813,7 +5637,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (isComposerApprovalState || projectSelectionRequired || activePendingProgress !== null) { return; } - void stashCurrentPrompt(); + void stashCurrentPromptStable(); }; window.addEventListener("keydown", handler, true); return () => window.removeEventListener("keydown", handler, true); @@ -5824,7 +5648,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) keybindings, pendingUserInputs.length, projectSelectionRequired, - stashCurrentPrompt, + stashCurrentPromptStable, isRevertingCheckpoint, terminalOpen, ]); @@ -5832,28 +5656,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Callbacks: attachments // ------------------------------------------------------------------ - const countReservedAttachments = () => { - const questionRequest = pendingUserInputs[0]; - const otherQuestionKeys = - questionAttachmentTarget && questionRequest && activeThreadId - ? questionRequest.questions - .map((question) => - questionAttachmentDraftId( - environmentId, - activeThreadId, - questionRequest.requestId, - question.id, - ), - ) - .filter((key) => key !== questionAttachmentTarget) - : []; - return ( - composerImagesRef.current.length + - composerFilesRef.current.length + - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) + - countQuestionAttachments(otherQuestionKeys) - ); - }; /** Resolves true when at least one chip was inserted for the accepted attachments. */ const addComposerAttachments = async ( files: File[], @@ -6234,94 +6036,81 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event.stopPropagation(); }; - const insertComposerText = useCallback( - ( - text: string, - position: "cursor" | "end", - options?: { - ensureLeadingBoundary?: boolean; - citationCommentAnchor?: AssistantCitationSourceAnchor; - clipboardData?: DataTransfer; - }, - ): boolean => { - if ( - text.length === 0 || - isConnecting || - isComposerApprovalState || - pendingUserInputs.length > 0 || - projectSelectionRequired || - (options?.citationCommentAnchor && !composerEditorRef.current) - ) { - return false; - } - if (options?.clipboardData) { - text = importPastedComposerText(options.clipboardData, importContextFragment); - } - const prompt = promptRef.current; - const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; - const needsLeadingSpace = - (options?.ensureLeadingBoundary ?? false) && - cursor > 0 && - !/\s/.test(prompt[cursor - 1] ?? ""); - const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text); - return applyPromptReplacement( - cursor, - rangeEnd, - needsLeadingSpace ? ` ${text}` : text, - options?.citationCommentAnchor - ? { - citationComment: { - start: cursor + (needsLeadingSpace ? 1 : 0), - sourceAnchor: options.citationCommentAnchor, - // An existing space after the cursor is consumed and re-emitted, so it stays. - insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor }, - }, - focusEditorAfterReplace: false, - } - : undefined, - ); - }, - [ - applyPromptReplacement, - isComposerApprovalState, - isConnecting, - pendingUserInputs.length, - projectSelectionRequired, - promptRef, - readComposerSnapshot, - importContextFragment, - ], - ); - - const insertComposerTextAtEnd = useCallback( - (text, options) => { - const inserted = insertComposerText(text, "end", options); - if (inserted && isComposerCollapsedMobile) { - // The expanded editor is hidden at phone widths, so its scheduled - // focus cannot expand the composer by itself. Reveal it before the - // focus frame runs to preserve type-to-focus and external inserts. - expandMobileComposer(); - } - return inserted; + const insertComposerText = ( + text: string, + position: "cursor" | "end", + options?: { + ensureLeadingBoundary?: boolean; + citationCommentAnchor?: AssistantCitationSourceAnchor; + clipboardData?: DataTransfer; }, - [expandMobileComposer, insertComposerText, isComposerCollapsedMobile], - ); + ): boolean => { + if ( + text.length === 0 || + isConnecting || + isComposerApprovalState || + pendingUserInputs.length > 0 || + projectSelectionRequired || + (options?.citationCommentAnchor && !composerEditorRef.current) + ) { + return false; + } + if (options?.clipboardData) { + text = importPastedComposerText(options.clipboardData, importContextFragment); + } + const prompt = promptRef.current; + const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; + const needsLeadingSpace = + (options?.ensureLeadingBoundary ?? false) && + cursor > 0 && + !/\s/.test(prompt[cursor - 1] ?? ""); + const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text); + return applyPromptReplacement( + cursor, + rangeEnd, + needsLeadingSpace ? ` ${text}` : text, + options?.citationCommentAnchor + ? { + citationComment: { + start: cursor + (needsLeadingSpace ? 1 : 0), + sourceAnchor: options.citationCommentAnchor, + // An existing space after the cursor is consumed and re-emitted, so it stays. + insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor }, + }, + focusEditorAfterReplace: false, + } + : undefined, + ); + }; + const insertComposerTextStable = useStableCallback(insertComposerText); + + const insertComposerTextAtEnd: ChatComposerHandle["insertTextAtEnd"] = (text, options) => { + const inserted = insertComposerText(text, "end", options); + if (inserted && isComposerCollapsedMobile) { + // The expanded editor is hidden at phone widths, so its scheduled + // focus cannot expand the composer by itself. Reveal it before the + // focus frame runs to preserve type-to-focus and external inserts. + expandMobileComposer(); + } + return inserted; + }; + const insertComposerTextAtEndStable = useStableCallback(insertComposerTextAtEnd); // Context produced by other panels (diff comments, preview picks) asks the store to place // its chip; while this composer is mounted for the draft, that means the caret. - const insertContextReferencesAtCaret = useCallback( - (references: ReadonlyArray): boolean => - insertComposerText(`${references.map(formatInlineContextReference).join(" ")} `, "cursor", { - ensureLeadingBoundary: true, - }), - [insertComposerText], - ); + const insertContextReferencesAtCaret = ( + references: ReadonlyArray, + ): boolean => + insertComposerText(`${references.map(formatInlineContextReference).join(" ")} `, "cursor", { + ensureLeadingBoundary: true, + }); + const insertContextReferencesAtCaretStable = useStableCallback(insertContextReferencesAtCaret); const setContextInsertionHandler = useComposerDraftStore( (store) => store.setContextInsertionHandler, ); useEffect(() => { - return setContextInsertionHandler(composerDraftTarget, insertContextReferencesAtCaret); - }, [composerDraftTarget, insertContextReferencesAtCaret, setContextInsertionHandler]); + return setContextInsertionHandler(composerDraftTarget, insertContextReferencesAtCaretStable); + }, [composerDraftTarget, insertContextReferencesAtCaretStable, setContextInsertionHandler]); // File-tree drags land as mentions. Handled in the capture phase so the // editor never sees the drop; the load-bearing rules (native stop, "move" @@ -6338,78 +6127,110 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, }); - // Sidebar thread drops arrive as a DOM event on the form (see threadContextDrag.ts). - useEffect(() => { - const form = composerFormRef.current; - if (!form) return; - const onThreadDrop = (event: Event) => { - const refs = (event as CustomEvent>).detail; - if (refs.some((ref) => ref.environmentId !== environmentId)) { + const attachDroppedThreadFile = useEffectEvent((file: File) => addComposerAttachments([file])); + const importDroppedThread = useEffectEvent( + async (ref: ScopedThreadRef, isActive: () => boolean) => { + const targetKey = attachmentTargetKey; + pendingDraftWork.begin(targetKey); + const loadingToast = toastManager.add({ + type: "loading", + title: "Loading thread context…", + timeout: 0, + data: { threadRef: routeThreadRef, hideCopyButton: true }, + }); + try { + await importComposerThreadAttachment({ + targetKey, + pendingImports: pendingThreadImportsRef.current, + countReservedAttachments: countReservedAttachmentsStable, + load: async () => { + const result = await loadThreadTranscript({ + environmentId: ref.environmentId, + input: { threadId: ref.threadId }, + }); + if (result._tag !== "Success") { + throw squashAtomCommandFailure(result); + } + return threadContextAttachment(ref.environmentId, result.value); + }, + isActive, + attach: attachDroppedThreadFile, + onLimitReached: () => { + if (activeThreadId) { + setThreadError( + activeThreadId, + `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`, + ); + } + }, + }); + } catch (error) { + if (!isActive()) return; toastManager.add({ type: "error", - title: "Use threads from this environment", - description: "The agent can only read threads on its own server.", + title: "Unable to read the dropped thread", + description: + isEnvironmentRequestInvalidError(error) && + error.reason === "thread_transcript_too_large" + ? "This thread exceeds the attachment size limit. Try a shorter thread." + : "Check that its environment is connected and up to date, then try again.", }); - return; + } finally { + toastManager.close(loadingToast); + pendingDraftWork.end(targetKey); } - const records = refs.flatMap((ref) => { - const shell = readThreadShell(ref); - return shell ? [threadContextRecord(ref, shell.title)] : []; - }); - if (records.length === 0) return; - if (questionAttachmentTarget !== null) { - const canAnswer = - canOperateThread && - !isConnecting && - !isComposerApprovalState && - !activePendingIsResponding && - activePendingProgress?.activeQuestion?.allowCustomAnswer !== false; - const text = `${records - .map((record) => formatInlineContextReference(threadContextReference(record))) - .join(" ")} `; - const snapshot = readComposerSnapshot(); - const cursor = snapshot.expandedCursor; - const leadingSpace = cursor > 0 && !/\s/.test(snapshot.value[cursor - 1] ?? ""); - const inserted = - canAnswer && - applyPromptReplacement( - cursor, - extendReplacementRangeForTrailingSpace(snapshot.value, cursor, text), - leadingSpace ? ` ${text}` : text, - ); - if (!inserted) { - toastManager.add({ - type: "error", - title: "Unable to add thread", - description: "The composer is busy; try again once it is ready.", - }); - return; - } - addComposerDraftThreadContexts(questionAttachmentTarget, records, { - appendReference: false, + }, + ); + + useThreadContextDrop(composerFormRef, environmentId, attachmentTargetKey, (refs, isActive) => { + const records = refs.flatMap((ref) => { + if (ref.environmentId !== environmentId) { + void importDroppedThread( + ref, + () => isActive() && attachmentTargetKeyRef.current === attachmentTargetKey, + ); + return []; + } + const shell = readThreadShell(ref); + return shell ? [threadContextRecord(ref, shell.title)] : []; + }); + if (records.length === 0) return; + if (questionAttachmentTarget !== null) { + const canAnswer = + canOperateThread && + !isConnecting && + !isComposerApprovalState && + !activePendingIsResponding && + activePendingProgress?.activeQuestion?.allowCustomAnswer !== false; + const text = `${records + .map((record) => formatInlineContextReference(threadContextReference(record))) + .join(" ")} `; + const snapshot = readComposerSnapshotStable(); + const cursor = snapshot.expandedCursor; + const leadingSpace = cursor > 0 && !/\s/.test(snapshot.value[cursor - 1] ?? ""); + const inserted = + canAnswer && + applyPromptReplacementStable( + cursor, + extendReplacementRangeForTrailingSpace(snapshot.value, cursor, text), + leadingSpace ? ` ${text}` : text, + ); + if (!inserted) { + toastManager.add({ + type: "error", + title: "Unable to add thread", + description: "The composer is busy; try again once it is ready.", }); - if (isComposerCollapsedMobile) expandMobileComposer(); - } else { - addComposerDraftThreadContexts(composerDraftTarget, records); + return; } - }; - form.addEventListener(THREAD_CONTEXT_DROP_EVENT, onThreadDrop); - return () => form.removeEventListener(THREAD_CONTEXT_DROP_EVENT, onThreadDrop); - }, [ - activePendingIsResponding, - activePendingProgress?.activeQuestion?.allowCustomAnswer, - addComposerDraftThreadContexts, - applyPromptReplacement, - canOperateThread, - composerDraftTarget, - environmentId, - expandMobileComposer, - isComposerApprovalState, - isComposerCollapsedMobile, - isConnecting, - questionAttachmentTarget, - readComposerSnapshot, - ]); + addComposerDraftThreadContexts(questionAttachmentTarget, records, { + appendReference: false, + }); + if (isComposerCollapsedMobile) expandMobileComposerStable(); + } else { + addComposerDraftThreadContexts(composerDraftTarget, records); + } + }); const onComposerMentionDragLeaveCapture = (event: React.DragEvent) => { if (!dataTransferHasComposerMention(event.dataTransfer.types)) return; @@ -6431,15 +6252,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) window.addEventListener("dragend", onWindowDragEnd); return () => window.removeEventListener("dragend", onWindowDragEnd); }, [isDragOverComposer]); - const handleInterruptPrimaryAction = useCallback(() => { + const handleInterruptPrimaryAction = () => { void onInterrupt(); - }, [onInterrupt]); - const handleImplementPlanInNewThreadPrimaryAction = useCallback(() => { + }; + const handleInterruptPrimaryActionStable = useStableCallback(handleInterruptPrimaryAction); + const handleImplementPlanInNewThreadPrimaryAction = () => { void onImplementPlanInNewThread(); - }, [onImplementPlanInNewThread]); + }; + const handleImplementPlanInNewThreadPrimaryActionStable = useStableCallback( + handleImplementPlanInNewThreadPrimaryAction, + ); // The phone composer collapses when the editor loses focus. Desktop only // rests on a timeline scroll, so losing focus there changes nothing. - const scheduleComposerCollapseCheck = useCallback(() => { + const scheduleComposerCollapseCheck = () => { if (!isMobileViewport || mobileComposerExpandInFlightRef.current) { return; } @@ -6466,7 +6291,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } setIsComposerFocused(false); }); - }, [isMobileViewport, setIsComposerFocused]); + }; useEffect(() => { return () => { @@ -6485,7 +6310,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ // Imperative handle // ------------------------------------------------------------------ - const openModelPicker = useCallback(() => { + const openModelPicker = () => { if (composerControlsHidden) { if (composerBlurFrameRef.current !== null) { window.cancelAnimationFrame(composerBlurFrameRef.current); @@ -6495,7 +6320,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setIsComposerFocused(true); } setIsComposerModelPickerOpen(true); - }, [composerControlsHidden, setIsComposerFocused, setIsComposerScrollCollapsed]); + }; + const openModelPickerStable = useStableCallback(openModelPicker); useImperativeHandle( composerRef, @@ -6551,15 +6377,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }); continue; } - insertComposerTextAtEnd(`${serializeComposerFileLink(path)} `, { + insertComposerTextAtEndStable(`${serializeComposerFileLink(path)} `, { ensureLeadingBoundary: true, }); } focusComposer(); }, hasPendingAttachments: () => - (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0, - insertTextAtEnd: insertComposerTextAtEnd, + (pendingImageCompressionsRef.current.get(attachmentTargetKey) ?? 0) > 0 || + pendingDraftWork.has(attachmentTargetKey), + insertTextAtEnd: insertComposerTextAtEndStable, pasteTextAtEnd: (text: string, options) => { const bypassAutoAttachment = options?.bypassAutoAttachment === true || @@ -6578,17 +6405,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return true; }, citeAssistantText: (citation, sourceAnchor) => - insertComposerText( + insertComposerTextStable( formatAssistantCitationForComposer(citation, citation.comment), "cursor", { ensureLeadingBoundary: true, citationCommentAnchor: sourceAnchor }, ), - openModelPicker, + openModelPicker: openModelPickerStable, toggleModelPicker: () => { if (isComposerModelPickerOpen) { setIsComposerModelPickerOpen(false); } else { - openModelPicker(); + openModelPickerStable(); } }, openControl: (command) => { @@ -6613,14 +6440,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) trigger.focus({ preventScroll: true }); trigger.click(); }, - compactContext: compactThreadContext, + compactContext: compactThreadContextStable, isModelPickerOpen: () => isComposerModelPickerOpen, isCaretAtStart: () => { const range = composerEditorRef.current?.readSelectionRange(); return range !== undefined && range.start === 0 && range.end === 0; }, readSnapshot: () => { - return readComposerSnapshot(); + return readComposerSnapshotStable(); }, resetCursorState: (options?: { cursor?: number; @@ -6646,7 +6473,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }, addTerminalContext: (selection: TerminalContextSelection) => { if (!activeThread || isChoiceOnlyPendingQuestion || isLiteralPendingAnswer) return; - const snapshot = readComposerSnapshot(); + const snapshot = readComposerSnapshotStable(); const context = { id: randomUUID(), threadId: activeThread.id, @@ -6727,8 +6554,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress, composerTerminalContexts, insertComposerDraftTerminalContext, - insertComposerText, - insertComposerTextAtEnd, + insertComposerTextStable, + insertComposerTextAtEndStable, promptRef, composerImagesRef, composerFilesRef, @@ -6744,10 +6571,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isLiteralPendingAnswer, pendingUserInputs.length, projectSelectionRequired, - applyPromptReplacement, + applyPromptReplacementStable, isComposerModelPickerOpen, - openModelPicker, - readComposerSnapshot, + openModelPickerStable, + readComposerSnapshotStable, resetComposerTrigger, setComposerTrigger, selectedModel, @@ -6763,7 +6590,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedProviderModels, interactionMode, planModeUiEnabled, - compactThreadContext, + compactThreadContextStable, restoreAfterTimelineReachedEnd, getTimelineScrollableNode, isTimelineAtLogicalEnd, @@ -6776,7 +6603,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return (
{ const target = event.target; if (isInsideRestingComposerControlScope(target)) return; @@ -6979,7 +6806,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) !activePendingProgress?.activeQuestion?.multiSelect && "px-3 py-2", )} onPointerDown={(event) => event.preventDefault()} - onClick={expandMobileComposer} + onClick={expandMobileComposerStable} aria-label="Write custom answer" > {activePendingProgress?.customAnswer || "Write custom answer"} @@ -7006,9 +6833,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) hasSendableContent={false} preserveComposerFocusOnPointerDown onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} - onInterrupt={handleInterruptPrimaryAction} + onInterrupt={handleInterruptPrimaryActionStable} onImplementPlanInNewThread={ - handleImplementPlanInNewThreadPrimaryAction + handleImplementPlanInNewThreadPrimaryActionStable } /> ) : null} @@ -7026,7 +6853,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeTasksProgress && activeTaskSteps ? ( @@ -7035,7 +6862,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) @@ -7048,7 +6875,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) menuOpen={isStashMenuOpen} pulseKey={stashPulse.key} pulsing={stashPulse.active} - onToggleMenu={toggleStashMenu} + onToggleMenu={toggleStashMenuStable} /> ) : null} @@ -7085,7 +6912,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : "text-placeholder", )} onPointerDown={(event) => event.preventDefault()} - onClick={isChoiceOnlyPendingQuestion ? undefined : expandMobileComposer} + onClick={isChoiceOnlyPendingQuestion ? undefined : expandMobileComposerStable} disabled={isChoiceOnlyPendingQuestion} aria-label="Expand composer" > @@ -7155,8 +6982,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) modelPickerOpen: false, }, })} - onRestore={restoreStashEntry} - onDelete={deleteStashEntry} + onRestore={restoreStashEntryStable} + onDelete={deleteStashEntryStable} onClose={() => setIsStashMenuOpen(false)} /> @@ -7181,8 +7008,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) triggerKind={composerTriggerKind} emptyStateText={composerMenuEmptyState} activeItemId={activeComposerMenuItem?.id ?? null} - onHighlightedItemChange={onComposerMenuItemHighlighted} - onSelect={onSelectComposerItem} + onHighlightedItemChange={onComposerMenuItemHighlightedStable} + onSelect={onSelectComposerItemStable} /> )} @@ -7622,8 +7449,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } cursor={composerCursor} contextRecords={composerContextRecords} - buildContextClipboardFragment={buildContextClipboardFragment} - importContextFragment={importContextFragment} + buildContextClipboardFragment={buildContextClipboardFragmentStable} + importContextFragment={importContextFragmentStable} skills={selectedProviderSkills} containerClassName={cn(isComposerResting && "min-w-0 flex-1")} className={cn( @@ -7636,14 +7463,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComposerResting && "flex items-center overflow-hidden whitespace-nowrap leading-8", )} - onChange={onPromptChange} - onVisibleSelectionChange={expandComposerForEditorChange} + onChange={onPromptChangeStable} + onVisibleSelectionChange={expandComposerForEditorChangeStable} onCommandKeyDown={onComposerCommandKey} onPageScrollKeyDown={onPageScrollKeyDown} onPageScrollKeyUp={onPageScrollKeyUp} onPageScrollRelease={onPageScrollRelease} - onCitationSubmitAndSend={submitCitationAndSend} - onCitationDraftSave={saveCitationDraftToPrompt} + onCitationSubmitAndSend={submitCitationAndSendStable} + onCitationDraftSave={saveCitationDraftToPromptStable} onPaste={onComposerPaste} placeholder={ isComposerApprovalState @@ -7697,8 +7524,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) hasSendableContent={false} preserveComposerFocusOnPointerDown onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} - onInterrupt={handleInterruptPrimaryAction} - onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction} + onInterrupt={handleInterruptPrimaryActionStable} + onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryActionStable} />
) : null} @@ -7824,11 +7651,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canResume={showResumeAction} preserveComposerFocusOnPointerDown={isMobileViewport || isComposerResting} isEditingQueuedMessage={isEditingQueuedMessage} - onSubmitMessage={handleSubmitMessage} + onSubmitMessage={handleSubmitMessageStable} onResume={onResume} onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} - onInterrupt={handleInterruptPrimaryAction} - onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction} + onInterrupt={handleInterruptPrimaryActionStable} + onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryActionStable} compactBeforeSendTokens={props.resumeCompactionTokens} keepFullHistory={props.keepFullHistory} onToggleKeepFullHistory={props.onToggleKeepFullHistory} @@ -7836,7 +7663,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) compactDisabled || noProviderAvailable || isSendBusy || isConnecting } compactDisabledReason={resolvedCompactDisabledReason} - {...(compactCommandAvailable ? { onCompactContext: compactThreadContext } : {})} + {...(compactCommandAvailable + ? { onCompactContext: compactThreadContextStable } + : {})} /> diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 72320e81dae2..80c697d6fc8c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -2669,7 +2669,7 @@ function UserMessageIntentMarker({ const presentation = intent === "queued_turn" ? { - label: "Queued", + label: "From queue", icon: null, } : intent === "promoted_queued_to_steer" @@ -2697,7 +2697,7 @@ function UserMessageIntentMarker({ {intent === "queued_turn" - ? "Queued behind the active turn" + ? "Queued while the agent was busy" : intent === "promoted_queued_to_steer" ? "Originally queued, then promoted to steer the active turn" : "Steered the active turn"} diff --git a/apps/web/src/components/chat/ProviderPackageIcon.tsx b/apps/web/src/components/chat/ProviderPackageIcon.tsx index 98c27693dc1e..675c619a702d 100644 --- a/apps/web/src/components/chat/ProviderPackageIcon.tsx +++ b/apps/web/src/components/chat/ProviderPackageIcon.tsx @@ -1,4 +1,4 @@ -import type { CSSProperties, SVGProps } from "react"; +import { useId, type CSSProperties, type SVGProps } from "react"; import type { ProviderIcon } from "@t3tools/provider-core/client"; @@ -13,11 +13,14 @@ export function ProviderPackageIcon({ className, ...props }: { readonly icon: ProviderIcon } & SVGProps) { + const gradientId = useId(); return ( - {icon.paths.map((path) => ( + {icon.paths.some((path) => path.gradient) ? ( + + {icon.paths.map((path, index) => + path.gradient ? ( + + {path.gradient.stops.map((stop) => ( + + ))} + + ) : null, + )} + + ) : null} + {icon.paths.map((path, index) => ( } > diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 40421a34e3b7..5206d33acde0 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -15,7 +15,6 @@ import { type HandoffEndpoints, type HandoffTimelineRun, } from "@t3tools/client-runtime/handoff"; -import { Fragment } from "react"; import { formatSubagentDisplayTitle } from "@t3tools/client-runtime/state/subagent-display"; import { ProviderDriverKind, @@ -562,18 +561,21 @@ export function HandoffRow(props: { detail={ {fromEndpoints.map((endpoint, index) => ( - - {index > 0 ? ( - - ) : null} + - + {index < fromEndpoints.length - 1 ? ( + + ) : null} + ))} {fromEndpoints.length > 0 ? (