diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index e8af344d2d..68d51af648 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -121,7 +121,19 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; const snapshot = yield* store.getShellSnapshot(); const shells = snapshot.threads; - const index = yield* store.listActiveShellIndex(); + const indexRead = traceSqlStatements(); + const index = yield* store.listActiveShellIndex().pipe(Effect.withTracer(indexRead.tracer)); + // Migration 132's index answers every payload field the read selects, so no row is parsed. + const indexProgram = yield* (yield* SqlClient.SqlClient).unsafe<{ + readonly opcode: string; + readonly p4: unknown; + }>(`EXPLAIN ${indexRead.statements[0]}`); + assert.deepEqual( + indexProgram + .filter((op) => op.opcode.startsWith("Function") && String(op.p4).startsWith("json_extract")) + .map((op) => op.p4), + [], + ); const { tracer, statements, queryTransactions } = traceSqlStatements(); const activity = yield* store.getAgentAwarenessSnapshot().pipe(Effect.withTracer(tracer)); assert.equal(activity.snapshotSequence, snapshot.snapshotSequence); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 1212233e02..e9a0187a30 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -142,6 +142,7 @@ import Migration0128 from "./Migrations/128_WorkflowRunSubject.ts"; import Migration0129 from "./Migrations/129_EscapedLinkLabelsAsText.ts"; import Migration0130 from "./Migrations/130_PeerLinkReachabilityErrors.ts"; import Migration0131 from "./Migrations/131_ScheduledSessionRuns.ts"; +import Migration0132 from "./Migrations/132_ActiveShellIndexDelegatedFrom.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -276,6 +277,7 @@ const migrationEntries = [ [129, "EscapedLinkLabelsAsText", Migration0129], [130, "PeerLinkReachabilityErrors", Migration0130], [131, "ScheduledSessionRuns", Migration0131], + [132, "ActiveShellIndexDelegatedFrom", Migration0132], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/132_ActiveShellIndexDelegatedFrom.ts b/apps/server/src/persistence/Migrations/132_ActiveShellIndexDelegatedFrom.ts new file mode 100644 index 0000000000..8640e9f95c --- /dev/null +++ b/apps/server/src/persistence/Migrations/132_ActiveShellIndexDelegatedFrom.ts @@ -0,0 +1,33 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Migration 118's index, with the delegatedFrom fields ProjectionStore.listActiveShellIndex now + // reads too. Keep the expressions identical to that query's. + yield* sql`DROP INDEX IF EXISTS orchestration_v2_projection_threads_active_shell_idx`; + yield* sql` + CREATE INDEX orchestration_v2_projection_threads_active_shell_idx + ON orchestration_v2_projection_threads( + updated_at, + thread_id, + project_id, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.relationshipToParent') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.parentThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.rootThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.sideChat') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.workflowStep') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.delegatedFrom.environmentId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.delegatedFrom.threadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.delegatedFrom.title') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledOverride') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinnedAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinOrderKey') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.snoozedUntil') END, + CASE WHEN json_valid(payload_json) THEN json_type(payload_json, '$.pullRequests[0]') END + ) + WHERE deleted_at IS NULL AND archived_at IS NULL + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 14db91820f..52c3ff0941 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -111,6 +111,7 @@ describe("V2 preview upgrade", () => { [129, "EscapedLinkLabelsAsText"], [130, "PeerLinkReachabilityErrors"], [131, "ScheduledSessionRuns"], + [132, "ActiveShellIndexDelegatedFrom"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -265,6 +266,7 @@ describe("V2 preview upgrade", () => { [129, "EscapedLinkLabelsAsText"], [130, "PeerLinkReachabilityErrors"], [131, "ScheduledSessionRuns"], + [132, "ActiveShellIndexDelegatedFrom"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 86fff735cb..84bdf8011b 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -2295,63 +2295,49 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(NodeServices.layer)), ); - it("refreshes once per checkout in either event order, and on every soft reset", () => { - // Each event says whether HEAD's identity was already the one last seen. - const cases = [ - { - events: [ - ["lock", false], - ["head", true], - ], - refreshes: [true, false], - }, - { - events: [ - ["head", false], - ["lock", true], - ], - refreshes: [true, false], - }, - { - events: [ - ["lock", true], - ["lock", true], - ], - refreshes: [true, true], - }, - { - events: [ - ["head", false], - ["lock", true], - ["lock", true], - ], - refreshes: [true, false, true], - }, - { - events: [ - ["poll", false], - ["lock", true], - ], - refreshes: [true, true], - }, - { - events: [ - ["head", true], - ["lock", true], - ], - refreshes: [false, true], - }, - ] as const; - for (const { events, refreshes } of cases) { - let checkoutAwaitsLock = false; - const seen = events.map(([kind, reported]) => { - const next = VcsStatusBroadcaster.nextHeadWatch(kind, reported, checkoutAwaitsLock); - checkoutAwaitsLock = next.checkoutAwaitsLock; - return next.refresh; - }); - assert.deepStrictEqual(seen, [...refreshes], JSON.stringify(events)); - } - }); + it.effect( + "a repeated event for one ref move sees no change, and each soft reset or commit does", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const commonDir = yield* fs.makeTempDirectoryScoped({ prefix: "vcs-checkout-state-" }); + const gitDir = path.join(commonDir, "worktrees", "wt"); + const headPath = path.join(gitDir, "HEAD"); + const refPath = path.join(commonDir, "refs", "heads", "main"); + yield* fs.makeDirectory(gitDir, { recursive: true }); + yield* fs.makeDirectory(path.dirname(refPath), { recursive: true }); + yield* fs.writeFileString(headPath, "ref: refs/heads/main\n"); + yield* fs.writeFileString(refPath, "88a38bfa\n"); + const replace = (file: string, content: string) => + fs + .writeFileString(`${file}.lock`, content) + .pipe(Effect.andThen(fs.rename(`${file}.lock`, file))); + const state = VcsStatusBroadcaster.checkoutState("head", headPath, commonDir); + + const before = yield* state; + assert.equal(yield* state, before); + // `git reset --soft`: only the branch ref in the common directory moves. + yield* replace(refPath, "4b825dc6\n"); + const reset = yield* state; + assert.notEqual(reset, before); + assert.equal(yield* state, reset); + yield* replace(refPath, "88a38bfa\n"); + const resetAgain = yield* state; + assert.notEqual(resetAgain, reset); + // `git commit` or `git add` rewrites the worktree's index. + yield* replace(path.join(gitDir, "index"), "index"); + const committed = yield* state; + assert.notEqual(committed, resetAgain); + // A branch that lives only in packed-refs moves when packed-refs is rewritten. + yield* fs.remove(refPath); + yield* replace(path.join(commonDir, "packed-refs"), "88a38bfa refs/heads/main\n"); + const packed = yield* state; + assert.notEqual(packed, committed); + yield* replace(path.join(commonDir, "packed-refs"), "4b825dc6 refs/heads/main\n"); + assert.notEqual(yield* state, packed); + }).pipe(Effect.provide(NodeServices.layer)), + ); it.live("a terminal commit or soft reset refreshes local-only Changes totals", () => Effect.gen(function* () { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 1e232d7ecb..3364e87bf1 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -59,18 +59,37 @@ const UNREADABLE_HEAD = "unreadable"; // Edits outside a turn move no ref, so idle polls still re-read local status this often. const POLLS_PER_FORCED_LOCAL_READ = 4; -// A checkout raises HEAD and HEAD.lock events in either order and refreshes once; a soft reset -// leaves HEAD as it was and raises only the HEAD.lock one. -export function nextHeadWatch( - kind: "head" | "poll" | "lock", - reported: boolean, - checkoutAwaitsLock: boolean, -): { readonly refresh: boolean; readonly checkoutAwaitsLock: boolean } { - if (kind === "lock") - return { refresh: !(reported && checkoutAwaitsLock), checkoutAwaitsLock: false }; - if (reported) return { refresh: false, checkoutAwaitsLock }; - return { refresh: true, checkoutAwaitsLock: kind === "head" }; -} +const fileIdentity = (info: FileSystem.File.Info) => + `${info.dev}:${Option.getOrUndefined(info.ino)}:${Option.getOrUndefined(info.mtime)?.getTime()}:${info.size}`; + +// What a ref move changes: HEAD for a checkout, the branch ref for a soft reset, ref and index for a +// commit. One move raises several events (Linux reports HEAD.lock's create and unlink as two +// Removes), so an event refreshes only when this differs from what the previous event saw. +export const checkoutState = Effect.fnUntraced(function* ( + headIdentity: string, + headPath: string, + commonDirectory: string, +) { + if (headIdentity === UNREADABLE_HEAD) return UNREADABLE_HEAD; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const ref = yield* fs.readFileString(headPath).pipe( + Effect.map((head) => /^ref: (refs\/\S+)/u.exec(head)?.[1]), + Effect.orElseSucceed(() => undefined), + ); + const files = [ + path.join(path.dirname(headPath), "index"), + path.join(commonDirectory, "packed-refs"), + ...(ref ? [path.join(commonDirectory, ref)] : []), + ]; + const identities = yield* Effect.forEach(files, (file) => + fs.stat(file).pipe( + Effect.map(fileIdentity), + Effect.orElseSucceed(() => "absent"), + ), + ); + return [headIdentity, ...identities].join("|"); +}); function boundedDiagnosticValue(value: string): string { return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH); @@ -1366,29 +1385,32 @@ export const make = Effect.gen(function* () { Effect.map((info) => info.type === "Directory"), Effect.orElseSucceed(() => false), ); + const commonDirectory = yield* fs.readFileString(path.join(headDirectory, "commondir")).pipe( + Effect.map((v) => (v.trim() ? path.resolve(headDirectory, v.trim()) : headDirectory)), + Effect.orElseSucceed(() => headDirectory), + ); const reftableDirs: Array = []; const headReftable = path.resolve(headDirectory, "reftable"); if (yield* isDir(headReftable)) { reftableDirs.push(headReftable); - const common = yield* fs.readFileString(path.join(headDirectory, "commondir")).pipe( - Effect.map((v) => (v.trim() ? path.resolve(headDirectory, v.trim(), "reftable") : null)), - Effect.orElseSucceed(() => null), - ); - if (common && common !== headReftable && (yield* isDir(common))) reftableDirs.push(common); + const common = path.resolve(commonDirectory, "reftable"); + if (common !== headReftable && (yield* isDir(common))) reftableDirs.push(common); } // Reftable repos keep a static HEAD placeholder, so the check also covers each tables.list. const identityFiles = [headPath, ...reftableDirs.map((dir) => path.join(dir, "tables.list"))]; const headIdentity = Effect.forEach(identityFiles, (file) => fs.stat(file).pipe( - Effect.map( - (info) => - `${info.dev}:${Option.getOrUndefined(info.ino)}:${Option.getOrUndefined(info.mtime)?.getTime()}:${info.size}`, - ), + Effect.map(fileIdentity), Effect.orElseSucceed(() => UNREADABLE_HEAD), ), ).pipe(Effect.map((ids) => (ids.includes(UNREADABLE_HEAD) ? UNREADABLE_HEAD : ids.join("|")))); + const readCheckoutState = (head: string) => + checkoutState(head, headPath, commonDirectory).pipe( + withFileSystem, + Effect.provideService(Path.Path, path), + ); const seenHead = yield* SubscriptionRef.make(yield* headIdentity); - let checkoutAwaitsLock = false; + let seenState = yield* readCheckoutState(yield* SubscriptionRef.get(seenHead)); const watching = yield* Deferred.make(); // Subscribers wait for the watch and for the check that covers its start. const covered = Deferred.await(watching).pipe( @@ -1445,25 +1467,13 @@ export const make = Effect.gen(function* () { name === "HEAD" || name === "index" || (name === "HEAD.lock" && event._tag === "Remove") ); }), - Stream.map((event) => { - const name = path.basename(event.path); - return name === "HEAD" - ? ("head" as const) - : name === "index" - ? ("index" as const) - : ("lock" as const); - }), // A checkout made as the watch starts raises no event on macOS. Reftable repos keep a static // HEAD placeholder and replace tables.list (and commondir's in worktrees) instead. Stream.merge( Stream.mergeAll( [ - pollUnreportedChanges(headIdentity, seenHead, covered).pipe( - Stream.map(() => "poll" as const), - ), - ...reftableDirs.map((dir) => - watchReftable(dir).pipe(Stream.map(() => "reftable" as const)), - ), + pollUnreportedChanges(headIdentity, seenHead, covered), + ...reftableDirs.map(watchReftable), ], { concurrency: "unbounded" }, ), @@ -1476,24 +1486,17 @@ export const make = Effect.gen(function* () { headGenerations.set(cwd, (headGenerations.get(cwd) ?? 0) + 1); }), ), - // An event for a HEAD or tables.list change the check above already published is dropped - // here; index updates always refresh. - Stream.filterEffect((kind) => - kind === "index" - ? Effect.succeed(true) - : Effect.gen(function* () { - const head = yield* headIdentity; - const reported = - head !== UNREADABLE_HEAD && head === (yield* SubscriptionRef.get(seenHead)); - if (!reported) yield* SubscriptionRef.set(seenHead, head); - const next = nextHeadWatch( - kind === "reftable" ? "poll" : kind, - reported, - checkoutAwaitsLock, - ); - checkoutAwaitsLock = next.checkoutAwaitsLock; - return next.refresh; - }), + Stream.filterEffect(() => + Effect.gen(function* () { + const head = yield* headIdentity; + const reported = + head !== UNREADABLE_HEAD && head === (yield* SubscriptionRef.get(seenHead)); + if (!reported) yield* SubscriptionRef.set(seenHead, head); + const state = yield* readCheckoutState(head); + const changed = state === UNREADABLE_HEAD || state !== seenState; + seenState = state; + return changed; + }), ), // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh. Stream.buffer({ capacity: 1, strategy: "sliding" }), diff --git a/apps/web/src/components/BranchToolbar.logic.test.ts b/apps/web/src/components/BranchToolbar.logic.test.ts index f54102ed31..af1c0fe430 100644 --- a/apps/web/src/components/BranchToolbar.logic.test.ts +++ b/apps/web/src/components/BranchToolbar.logic.test.ts @@ -15,6 +15,7 @@ import { sanitizeNewRefName, shouldIncludeBranchPickerItem, isBranchHoldCurrent, + beginDraftBranchPick, offersWorkspaceModes, } from "./BranchToolbar.logic"; @@ -453,3 +454,46 @@ describe("resolveConfirmedSelectedRef", () => { ); }); }); + +describe("beginDraftBranchPick", () => { + const draftStore = (draft: { worktreePath: string | null }) => { + let state = { draft }; + const listeners = new Set<(next: typeof state) => void>(); + return { + getState: () => state, + subscribe: (listener: (next: typeof state) => void) => { + listeners.add(listener); + return () => listeners.delete(listener); + }, + set: (next: { worktreePath: string | null }) => { + state = { ...state, draft: next }; + for (const listener of listeners) listener(state); + }, + listeners, + }; + }; + const readDraft = (state: { draft: { worktreePath: string | null } }) => state.draft; + + it("stops watching the draft once the pick settles", () => { + const store = draftStore({ worktreePath: null }); + const pick = beginDraftBranchPick(new Map(), "draft", store, readDraft); + expect(store.listeners.size).toBe(1); + pick.settle(); + expect(store.listeners.size).toBe(0); + expect(pick.isCurrent()).toBe(false); + }); + + it("goes stale on a workspace change or a later pick, leaving one watcher", () => { + const picks = new Map(); + const store = draftStore({ worktreePath: null }); + const moved = beginDraftBranchPick(picks, "draft", store, readDraft); + store.set({ worktreePath: "/repo/wt" }); + expect([moved.isCurrent(), store.listeners.size]).toEqual([false, 0]); + + const first = beginDraftBranchPick(picks, "draft", store, readDraft); + const second = beginDraftBranchPick(picks, "draft", store, readDraft); + expect([first.isCurrent(), second.isCurrent(), store.listeners.size]).toEqual([false, true, 1]); + first.settle(); + expect([second.isCurrent(), store.listeners.size]).toEqual([true, 1]); + }); +}); diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index c2335e1506..3b30c5c681 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -422,3 +422,55 @@ export function shouldIncludeBranchPickerItem(input: { lowerItemValue.includes(sanitizedQuery) ); } + +interface PickedDraftWorkspace { + readonly environmentId?: unknown; + readonly projectId?: unknown; + readonly envMode?: unknown; + readonly worktreePath?: unknown; + readonly promotedTo?: unknown; +} + +export interface DraftBranchPick { + readonly isCurrent: () => boolean; + /** Stops watching the draft once the pick has applied or given up. */ + readonly settle: () => void; +} + +/** + * Watches a draft's workspace for one branch pick's lifetime, not the selector's: closing Thread + * Details must not drop a checkout that lands later, but a workspace change or a later pick must. + */ +export function beginDraftBranchPick( + picks: Map void }>, + key: string, + store: { + readonly getState: () => State; + readonly subscribe: (listener: (state: State) => void) => () => void; + }, + readDraft: (state: State) => PickedDraftWorkspace | null, +): DraftBranchPick { + const token = Symbol(); + picks.get(key)?.stop(); + const settle = () => { + if (picks.get(key)?.token !== token) return; + picks.delete(key); + unsubscribe(); + }; + let previous = readDraft(store.getState()); + const unsubscribe = store.subscribe((state) => { + const current = readDraft(state); + if ( + current?.environmentId !== previous?.environmentId || + current?.projectId !== previous?.projectId || + current?.envMode !== previous?.envMode || + current?.worktreePath !== previous?.worktreePath || + current?.promotedTo !== previous?.promotedTo + ) { + settle(); + } + previous = current; + }); + picks.set(key, { token, stop: unsubscribe }); + return { isCurrent: () => picks.get(key)?.token === token, settle }; +} diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index db94981cc6..c2e72de729 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -51,6 +51,8 @@ import { changeRequestTermKind } from "./pullRequest/changeRequestTerm"; import { useComposerMenuProps } from "./chat/composerEventScope"; import { type BranchHold, + beginDraftBranchPick, + type DraftBranchPick, deriveLocalBranchNameFromRemoteRef, isBranchHoldCurrent, isWorktreeChangeBlocked, @@ -103,7 +105,7 @@ interface BranchToolbarBranchSelectorProps { const WORKTREE_CHANGE_BLOCKED_MESSAGE = msg("Stop the current turn to switch worktrees."); // Both branch pickers for a draft share the latest selection. -const latestDraftPicks = new Map void }>(); +const latestDraftPicks = new Map void }>(); // Picker checkouts by environment and checkout: null while in flight, then the branch it landed // on. Shared because a draft thread mounts two selectors on one checkout, and the switch's own @@ -435,7 +437,7 @@ export function BranchToolbarBranchSelector({ }); }; - const runBranchAction = (action: () => Promise) => { + const runBranchAction = (action: () => Promise, settle: () => void) => { if ( !readEnvironmentScope(environmentId, AuthSourceControlWriteScope) || (hasServerThread && !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) @@ -447,43 +449,28 @@ export function BranchToolbarBranchSelector({ description: gt("This connection cannot change the thread's branch."), }), ); + settle(); return; } startBranchActionTransition(async () => { - await action(); + await action().finally(settle); branchRefState.refresh(); }); }; const latestSelectionRef = useRef(null); - const beginBranchPick = () => { + const beginBranchPick = (): DraftBranchPick => { const token = Symbol(); latestSelectionRef.current = token; - if (hasServerThread) return () => latestSelectionRef.current === token; + const isLatestSelection = () => latestSelectionRef.current === token; + if (hasServerThread) return { isCurrent: isLatestSelection, settle: () => {} }; const store = useComposerDraftStore.getState(); const target = draftId ?? threadRef; const targetId = draftId ?? store.getDraftIdByRef(threadRef); - if (!targetId) return () => latestSelectionRef.current === token; - latestDraftPicks.get(targetId)?.stop(); - // Watches the draft for the pick's own lifetime, not the selector's: closing Thread Details - // must not drop a checkout that lands later, but any workspace change in between must. - let previous = store.getDraftThread(target); - const stop = useComposerDraftStore.subscribe((state) => { - const current = state.getDraftThread(target); - if ( - current?.environmentId !== previous?.environmentId || - current?.projectId !== previous?.projectId || - current?.envMode !== previous?.envMode || - current?.worktreePath !== previous?.worktreePath || - current?.promotedTo !== previous?.promotedTo - ) { - stop(); - if (latestDraftPicks.get(targetId)?.token === token) latestDraftPicks.delete(targetId); - } - previous = current; - }); - latestDraftPicks.set(targetId, { token, stop }); - return () => latestDraftPicks.get(targetId)?.token === token; + if (!targetId) return { isCurrent: isLatestSelection, settle: () => {} }; + return beginDraftBranchPick(latestDraftPicks, targetId, useComposerDraftStore, (state) => + state.getDraftThread(target), + ); }; // The picker's list, and the server's coalesced ref listing, can predate a checkout an agent @@ -499,15 +486,25 @@ export function BranchToolbarBranchSelector({ const selectBranch = async (listedRef: VcsRef) => { if (!canUpdateThreadBranch || !branchCwd || !activeProjectCwd || isBranchActionPending) return; - const isCurrentPick = beginBranchPick(); + const pick = beginBranchPick(); + // The checkout's own action settles the pick; every way out before it settles it here. + const handedOff = await pickBranch(listedRef, pick).catch((error: unknown) => { + pick.settle(); + throw error; + }); + if (!handedOff) pick.settle(); + }; + + const pickBranch = async (listedRef: VcsRef, pick: DraftBranchPick): Promise => { + if (!branchCwd || !activeProjectCwd) return false; let latest = readLatestThreadState(); if (isSelectingWorktreeBase) { - if (latest.worktreePath) return; + if (latest.worktreePath) return false; setThreadBranch(listedRef.name, null); setIsBranchMenuOpen(false); onComposerFocusRequest?.(); - return; + return false; } setIsBranchMenuOpen(false); @@ -517,7 +514,7 @@ export function BranchToolbarBranchSelector({ ? await readSelectedRef(listedRef.worktreePath, listedRef) : listedRef; // A later pick made while this one was confirming its worktree wins. - if (!isCurrentPick()) return; + if (!pick.isCurrent()) return false; latest = readLatestThreadState(); const selectionTarget = resolveBranchSelectionTarget({ activeProjectCwd, @@ -533,14 +530,14 @@ export function BranchToolbarBranchSelector({ nextWorktreePath: selectionTarget.nextWorktreePath, }) ) - return; + return false; if ( selectionTarget.reuseExistingWorktree && !(selectionTarget.staysInActiveCheckout && canWriteSourceControl) ) { setThreadBranch(refName.name, selectionTarget.nextWorktreePath); - return; + return false; } const selectedBranchName = refName.isRemote @@ -567,7 +564,7 @@ export function BranchToolbarBranchSelector({ const movesCheckout = selectionTarget.checkoutCwd !== branchCwd; let hold: BranchHold | null = null; const applied = - (hasServerThread || isCurrentPick()) && + (hasServerThread || pick.isCurrent()) && setThreadBranch( nextBranchName, selectionTarget.nextWorktreePath, @@ -610,14 +607,15 @@ export function BranchToolbarBranchSelector({ }), ); } - }); + }, pick.settle); + return true; }; const createRef = (rawName: string) => { if (!canChangeThreadBranch) return; const name = sanitizeNewRefName(rawName); if (!branchCwd || !name || isBranchActionPending) return; - const isCurrentPick = beginBranchPick(); + const pick = beginBranchPick(); setIsBranchMenuOpen(false); onComposerFocusRequest?.(); @@ -639,7 +637,7 @@ export function BranchToolbarBranchSelector({ const nextBranchName = createBranchResult.value.refName; pickerCheckouts.set(checkoutKey, nextBranchName); const applied = - (hasServerThread || isCurrentPick()) && + (hasServerThread || pick.isCurrent()) && setThreadBranch(nextBranchName, activeWorktreePath); if (applied) { setBranchHold({ @@ -662,7 +660,7 @@ export function BranchToolbarBranchSelector({ }), ); } - }); + }, pick.settle); }; const worktreeBaseBranchCandidate = isInitialBranchesLoadPending diff --git a/patches/@e2e-dev__mobile@0.12.9.patch b/patches/@e2e-dev__mobile@0.12.9.patch index 7959fb8cc8..f4c725e83b 100644 --- a/patches/@e2e-dev__mobile@0.12.9.patch +++ b/patches/@e2e-dev__mobile@0.12.9.patch @@ -179,7 +179,7 @@ index 9b90379..82b1c03 100644 isAppInstalled: { ...action, label: (app) => appLabel(app ?? surface.pinnedApp ?? 'app') }, openApp: { ...action, label: (app) => appLabel(app) }, diff --git a/dist/support.js b/dist/support.js -index e307753..9f21e66 100644 +index e307753..a2b3eaf 100644 --- a/dist/support.js +++ b/dist/support.js @@ -1,4 +1,5 @@ @@ -188,10 +188,18 @@ index e307753..9f21e66 100644 import { EngineError, withTimeout } from '@e2e-dev/core/engine'; export function cancelled(text) { return new EngineError('CANCELLED', text, { retryable: false }); -@@ -8,6 +9,29 @@ export function cancelled(text) { +@@ -8,6 +9,37 @@ export function cancelled(text) { * was left: a tap that lands is then not reported as cut off. */ const MIN_ANSWER_MS = 250; ++/** ++ * A fill clears, types and checks every character on the device, so once sent ++ * it gets at least this to answer, however little of the budget the waits for ++ * its target left: a loaded host then sees it finish rather than cut off. ++ */ ++export function fillAnswerMs(text) { ++ return 5_000 + 100 * [...text].length; ++} +/** The first and the longest wait before a command the busy iOS runner refused is sent again. */ +const RUNNER_BUSY_FIRST_WAIT_MS = 250; +const RUNNER_BUSY_MAX_WAIT_MS = 2000; @@ -218,17 +226,27 @@ index e307753..9f21e66 100644 /** * One operation's budget (its `timeoutMs`), which the harness signal does not * enforce. Every device command the operation sends runs under it: the -@@ -46,6 +70,9 @@ export class InputBudget { +@@ -45,14 +77,17 @@ export class InputBudget { + * it is refused unsent. An input that does not answer in time may have * landed, so it is `ACTION_MAY_HAVE_COMMITTED` and the runner never repeats it. */ - send(dispatch, holdMs = 0) { -+ return this.untilRunnerFree(() => this.sendOnce(dispatch, holdMs), holdMs + MIN_ANSWER_MS); +- send(dispatch, holdMs = 0) { ++ send(dispatch, holdMs = 0, minAnswerMs = MIN_ANSWER_MS) { ++ return this.untilRunnerFree(() => this.sendOnce(dispatch, holdMs, minAnswerMs), holdMs + MIN_ANSWER_MS); + } -+ sendOnce(dispatch, holdMs) { ++ sendOnce(dispatch, holdMs, minAnswerMs) { const remaining = this.remainingMs(); if (remaining <= 0) return Promise.reject(this.spent()); -@@ -69,6 +96,9 @@ export class InputBudget { + if (holdMs >= remaining) { + return Promise.reject(new EngineError('NOT_ACTIONABLE', `${this.label} holds for ${holdMs} ms, but only ${Math.floor(remaining)} ms of its timeout are left; raise the timeout or shorten the hold`, { retryable: false })); + } +- const answerMs = Math.max(remaining, MIN_ANSWER_MS); ++ const answerMs = Math.max(remaining, minAnswerMs); + const deadline = new AbortController(); + const requestSignal = AbortSignal.any([this.signal, deadline.signal]); + const pending = this.track(dispatch(requestSignal)); +@@ -69,6 +104,9 @@ export class InputBudget { * so the runner never repeats that input. */ read(dispatch) { @@ -238,7 +256,7 @@ index e307753..9f21e66 100644 const remaining = this.remainingMs(); if (remaining <= 0) return Promise.reject(this.spent()); -@@ -76,6 +106,42 @@ export class InputBudget { +@@ -76,6 +114,42 @@ export class InputBudget { ? this.maybeCommitted() : new EngineError('OPERATION_TIMEOUT', `${this.label} timed out before the device answered`, { retryable: false })); } @@ -282,9 +300,18 @@ index e307753..9f21e66 100644 remainingMs() { return this.endsAt - Date.now(); diff --git a/dist/surface.js b/dist/surface.js -index 449d286..bcd5622 100644 +index 449d286..a10688d 100644 --- a/dist/surface.js +++ b/dist/surface.js +@@ -28,7 +28,7 @@ import { deviceLabel, deviceSelection, pinnedApp } from './bindings.js'; + import { assertAppId } from './links.js'; + import { bootRequest, DevicePool } from './pool.js'; + import { recordLease, travelledLease } from './provider.js'; +-import { installedIdentity, invalidState, notActionable, logicalScreenSize, readPngSize, sanitizeFilename, screenLocation, swipeWithin, unsupported, InputBudget, } from './support.js'; ++import { installedIdentity, invalidState, notActionable, logicalScreenSize, readPngSize, sanitizeFilename, screenLocation, swipeWithin, unsupported, InputBudget, fillAnswerMs, } from './support.js'; + /** Why nothing is pinned with `appPath` alone: the install is the suite's. */ + const UNINSTALLED_BUILD = "the build the target's `app.appPath` names installed first with `device.installApp()`"; + /** @@ -389,11 +389,13 @@ export class AgentDeviceSurface { /** * Runs one agent-device command under an operation budget and translates @@ -475,6 +502,19 @@ index 449d286..bcd5622 100644 return apps.some((entry) => listsApp(entry, target)); } /** The app a `device` method names, else the pinned one; neither is `INVALID_STATE`. */ +@@ -1361,10 +1363,10 @@ export class AgentDeviceSurface { + return input.send(() => client.interactions.hover(this.actionTarget(target))); + case 'fill': + // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- agent-device fill, not Array#fill +- return input.send(() => client.interactions.fill({ ...this.actionTarget(target), text: action.value, ...settle })); ++ return input.send(() => client.interactions.fill({ ...this.actionTarget(target), text: action.value, ...settle }), 0, fillAnswerMs(action.value)); + case 'clear': + // oxlint-disable-next-line unicorn/no-array-fill-with-reference-type -- agent-device fill, not Array#fill +- return input.send(() => client.interactions.fill({ ...this.actionTarget(target), text: '', ...settle })); ++ return input.send(() => client.interactions.fill({ ...this.actionTarget(target), text: '', ...settle }), 0, fillAnswerMs('')); + case 'check': + case 'uncheck': { + const wanted = action.kind === 'check'; @@ -1640,15 +1642,16 @@ export class AgentDeviceSurface { const app = this.pinnedApp; if (app === undefined) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a7ec759ad1..ab27dc4e61 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -363,7 +363,7 @@ pnpmfileChecksum: sha256-V4l4scZuq2tJGzv9CIPYF0cGBGNRBI8wBVBZg42BsCM= patchedDependencies: '@cursor/sdk@1.5.2': 38c103d5c83bd2276fa1b8788747df0b9aedb5ae0006aeb5bc351cd4cd32f95a - '@e2e-dev/mobile@0.12.9': c40d4ab0cc2917388badb005d86e3c62570d6450ffedb66d8ceb8a51de2ca5b0 + '@e2e-dev/mobile@0.12.9': 4d01eb3861b721fa35ed391bacea38de6765f9fd60951924d355100507a1ff78 '@e2e-dev/web@0.17.0': d4a718e516e19ad4db63cddd1e97439910bb260100dcde5de6213ecf75bc5b6b '@effect/platform-node-shared@4.1.7': c1e465e4b1faca5839831624bd0705c7dd346412f06279c656aeefb5c3b3080d '@effect/vitest@4.1.7': 3752ba7dcfe5449546ba77a5297613e1d0e31a87d1806a6d941a899e26770501 @@ -783,7 +783,7 @@ importers: version: 7.29.13(supports-color@8.1.1) '@e2e-dev/mobile': specifier: 0.12.9 - version: 0.12.9(patch_hash=c40d4ab0cc2917388badb005d86e3c62570d6450ffedb66d8ceb8a51de2ca5b0)(@e2e-dev/core@0.25.0)(e2e@0.25.0) + version: 0.12.9(patch_hash=4d01eb3861b721fa35ed391bacea38de6765f9fd60951924d355100507a1ff78)(@e2e-dev/core@0.25.0)(e2e@0.25.0) '@effect/vitest': specifier: 4.1.7 version: 4.1.7(patch_hash=3752ba7dcfe5449546ba77a5297613e1d0e31a87d1806a6d941a899e26770501)(@opentelemetry/api@1.10.0)(@types/node@26.6.11)(@vitest/browser-playwright@5.1.1)(@vitest/ui@5.1.1)(effect@4.1.7(patch_hash=eca58993801b2681500afba78da973110d0d6311df77564258edc4bf8a46544c))(jiti@2.7.0)(jsdom@31.0.1(@napi-rs/canvas@1.2.0)(@noble/hashes@2.4.0))(playwright@1.65.1)(terser@5.51.4)(typescript@7.0.2)(yaml@2.9.1) @@ -2582,7 +2582,7 @@ importers: dependencies: '@e2e-dev/mobile': specifier: 0.12.9 - version: 0.12.9(patch_hash=c40d4ab0cc2917388badb005d86e3c62570d6450ffedb66d8ceb8a51de2ca5b0)(@e2e-dev/core@0.25.0)(e2e@0.25.0) + version: 0.12.9(patch_hash=4d01eb3861b721fa35ed391bacea38de6765f9fd60951924d355100507a1ff78)(@e2e-dev/core@0.25.0)(e2e@0.25.0) '@e2e-dev/web': specifier: 0.17.0 version: 0.17.0(patch_hash=d4a718e516e19ad4db63cddd1e97439910bb260100dcde5de6213ecf75bc5b6b)(@e2e-dev/core@0.25.0)(e2e@0.25.0) @@ -12879,7 +12879,7 @@ snapshots: pixelmatch: 8.0.0 zod: 4.6.7 - '@e2e-dev/mobile@0.12.9(patch_hash=c40d4ab0cc2917388badb005d86e3c62570d6450ffedb66d8ceb8a51de2ca5b0)(@e2e-dev/core@0.25.0)(e2e@0.25.0)': + '@e2e-dev/mobile@0.12.9(patch_hash=4d01eb3861b721fa35ed391bacea38de6765f9fd60951924d355100507a1ff78)(@e2e-dev/core@0.25.0)(e2e@0.25.0)': dependencies: '@e2e-dev/core': 0.25.0 '@napi-rs/image': 1.16.0