From aee8bc705dbc97611a5e11deacb60c3dd2ffb548 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:19:19 -0500 Subject: [PATCH 1/4] perf(server): cut sqlite and streaming hot-path overhead High-rate streaming deltas, session sweeps, and projection writes were triggering redundant SQLite reads, full-row JSON rewrites, and repeated full read-model hydrations on the main thread. - Return early in ProviderService.listSessions when no adapters are active and fetch bindings only for active session thread IDs. - Route content.delta runtime ingestion through a narrow active-thread lookup (session and live side-turns) instead of four-query shell hydration with diff-stat rollups. - Update only updated_at in ProjectionPipeline for assistant messages and activities, guard subagent roster reads behind activityMayAffectSubagents, skip streaming session lookups and no-op turn upserts, and drop redundant correlated subqueries from message upserts. - Guard Claude partial tool JSON decoding with outer-brace checks, enforce the 500 ms file-change estimate throttle before scanning, and scan partial JSON strings in linear-time slices. - Scope shell snapshot diff-stat rollups to active or archived threads and replace non-engine getCommandReadModel calls in ProjectSetupSource, LinkMoves, and single-thread ThreadMoves paths. - Drop six unused or prefix-redundant SQLite indexes in migration 126 and tune NodeSqliteClient with a 1024-entry statement cache, borrower-based statement execution, prepared transaction controls, and savepoint release. - Wake AssistantEvents discovery only on events that produce assistant actions, and nudge discovery on stale settlements. --- .../src/assistants/AssistantEvents.test.ts | 62 ++++- .../src/assistants/AssistantEventsLive.ts | 9 +- .../Layers/CheckpointDiffQuery.test.ts | 18 ++ apps/server/src/links/LinkMoves.test.ts | 2 +- apps/server/src/links/LinkMoves.ts | 10 +- apps/server/src/moves/ThreadMoves.ts | 132 ++++++----- .../Layers/OrchestrationEngine.test.ts | 3 + .../Layers/ProjectionPipeline.ts | 114 +++++---- .../Layers/ProjectionSnapshotQuery.test.ts | 96 ++++++++ .../Layers/ProjectionSnapshotQuery.ts | 144 +++++++++++- .../Layers/ProviderRuntimeIngestion.ts | 218 +++++++++++------- .../PullRequestAutomationWatcher.test.ts | 3 + .../Layers/ThreadAutoArchiveSweeper.test.ts | 3 + .../ThreadDiffStatBaselineReactor.test.ts | 3 + .../Services/ProjectionSnapshotQuery.ts | 49 ++++ .../Layers/ProjectionThreadMessages.ts | 18 +- .../persistence/Layers/ProjectionThreads.ts | 21 ++ .../server/src/persistence/Migrations.test.ts | 51 ++++ apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/126_DropRedundantIndexes.ts | 28 +++ .../src/persistence/NodeSqliteClient.test.ts | 25 ++ .../src/persistence/NodeSqliteClient.ts | 138 ++++------- .../persistence/Services/ProjectionThreads.ts | 15 ++ .../Layers/ProjectSetupScriptRunner.test.ts | 3 + .../src/projectSetup/ProjectSetupSource.ts | 10 +- .../src/projectSetup/ProjectSetups.test.ts | 27 ++- .../src/provider/Layers/ClaudeAdapter.ts | 16 +- .../provider/Layers/ProviderService.test.ts | 52 +++++ .../src/provider/Layers/ProviderService.ts | 25 +- .../Layers/ProviderSessionReaper.test.ts | 3 + .../Layers/claudePartialToolInput.test.ts | 29 +++ .../provider/Layers/claudePartialToolInput.ts | 78 ++++--- .../ThreadContextSeedBuilder.test.ts | 6 + apps/server/src/server.test.ts | 6 + apps/server/src/serverRuntimeStartup.test.ts | 12 + .../shared/src/subagentProjection.test.ts | 26 ++- packages/shared/src/subagentProjection.ts | 16 ++ 37 files changed, 1095 insertions(+), 378 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/126_DropRedundantIndexes.ts diff --git a/apps/server/src/assistants/AssistantEvents.test.ts b/apps/server/src/assistants/AssistantEvents.test.ts index a34e327be..94d152c20 100644 --- a/apps/server/src/assistants/AssistantEvents.test.ts +++ b/apps/server/src/assistants/AssistantEvents.test.ts @@ -77,6 +77,7 @@ const makeHarness = Effect.gen(function* () { thread: makeThread(), assistants: 1, readDelayMs: 0, + readEventsCalls: 0, /** What the project lookup says; "fails": it can't be read. */ project: { title: "app", kind: "project" } as | { readonly title: string; readonly kind: string } @@ -95,10 +96,12 @@ const makeHarness = Effect.gen(function* () { countLive: () => Effect.sync(() => state.assistants), }), Layer.mock(OrchestrationEngineService)({ - readEvents: (after) => - Stream.fromEffect(Effect.sleep(Duration.millis(state.readDelayMs))).pipe( + readEvents: (after) => { + state.readEventsCalls += 1; + return Stream.fromEffect(Effect.sleep(Duration.millis(state.readDelayMs))).pipe( Stream.flatMap(() => Stream.fromIterable(events.filter((e) => e.sequence > after))), - ), + ); + }, streamDomainEvents: Stream.fromPubSub(published), }), Layer.mock(ProjectionSnapshotQuery)({ @@ -468,8 +471,7 @@ it.layer(NodeServices.layer)("AssistantEvents", (it) => { // The last assistant goes; the user answers the card while the record is off. harness.state.assistants = 0; - yield* PubSub.publish(harness.published, harness.events.at(-1) ?? ({} as never)); - yield* settle(1_000); + yield* settle(31_000); yield* PubSub.publish(harness.schedules, snapshot([])); yield* settle(1_000); assert.strictEqual((yield* recorded(record))[0]?.resolvedAt, null); @@ -725,4 +727,54 @@ it.layer(NodeServices.layer)("AssistantEvents", (it) => { }), ), ); + + it.effect("ignores non-actionable domain events until a stale settlement nudges discovery", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeHarness; + yield* TestClock.adjust("1 hour"); + const { record } = yield* harness.boot; + yield* settle(); + + const callsBeforeStreaming = harness.state.readEventsCalls; + yield* appended(harness, "thread.message-sent", { + threadId: THREAD, + messageId: "assistant-stream-1", + role: "assistant", + text: "hello", + turnId: "turn-1", + streaming: true, + createdAt: "2026-10-23T12:00:00.000Z", + updatedAt: "2026-10-23T12:00:00.000Z", + }); + yield* settle(); + assert.strictEqual(harness.state.readEventsCalls, callsBeforeStreaming); + + // A turn finishes and begins its hold; then a non-actionable message + // lands afterward so the record cursor lags behind the thread's latest + // sequence. Settlement hits `stale`, wakes discovery, and still settles + // promptly instead of waiting 30s for the idle timer. + harness.state.thread = makeThread({ + latestTurn: { turnId: "turn-1", state: "completed" } as never, + }); + yield* appended(harness, "thread.turn-completed", turnCompleted("turn-1")); + yield* settle(); + yield* appended(harness, "thread.message-sent", { + threadId: THREAD, + messageId: "assistant-stream-1", + role: "assistant", + text: " final", + turnId: "turn-1", + streaming: false, + createdAt: "2026-10-23T12:00:00.000Z", + updatedAt: "2026-10-23T12:00:01.000Z", + }); + + yield* settle(FINISHED_HOLD_MS + 1_000); + const events = yield* recorded(record); + assert.strictEqual(events.length, 1); + assert.strictEqual(events[0]?.name, "thread.finished"); + }), + ), + ); }); diff --git a/apps/server/src/assistants/AssistantEventsLive.ts b/apps/server/src/assistants/AssistantEventsLive.ts index 72abf30bf..9b28a89da 100644 --- a/apps/server/src/assistants/AssistantEventsLive.ts +++ b/apps/server/src/assistants/AssistantEventsLive.ts @@ -233,6 +233,9 @@ const make = Effect.gen(function* () { // the record read what happened, behind the rows due before it. if (outcome === "stale") { yield* repo.defer(row.subjectKey, iso(now + STALE_RETRY_MS)); + // Non-actionable domain events do not wake discovery; nudge it now + // so the cursor advances past them instead of waiting for the idle timer. + yield* Queue.offer(discoveryBell, undefined); } return outcome === "recorded"; } @@ -307,7 +310,11 @@ const make = Effect.gen(function* () { const start: AssistantEventsShape["start"] = () => Effect.gen(function* () { const ring = () => Queue.offer(discoveryBell, undefined); - yield* Effect.forkScoped(Stream.runForEach(engine.streamDomainEvents, ring)); + yield* Effect.forkScoped( + Stream.runForEach(engine.streamDomainEvents, (event) => + assistantEventActionsForEvent(event).length > 0 ? ring() : Effect.void, + ), + ); if (Option.isSome(assistants)) { // A connection made or removed turns the record on or off. yield* Effect.forkScoped(Stream.runForEach(assistants.value.changes, ring)); diff --git a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts index d4fe64455..5be186936 100644 --- a/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts +++ b/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.test.ts @@ -138,6 +138,9 @@ describe("CheckpointDiffQueryLive", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), @@ -241,6 +244,9 @@ describe("CheckpointDiffQueryLive", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), @@ -376,6 +382,9 @@ describe("CheckpointDiffQueryLive", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), @@ -461,6 +470,9 @@ describe("CheckpointDiffQueryLive", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), @@ -542,6 +554,9 @@ describe("CheckpointDiffQueryLive", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), @@ -606,6 +621,9 @@ describe("CheckpointDiffQueryLive", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts index 1b3a03e6c..c4838f623 100644 --- a/apps/server/src/links/LinkMoves.test.ts +++ b/apps/server/src/links/LinkMoves.test.ts @@ -267,7 +267,7 @@ function testLayer( ), }), Layer.mock(ProjectionSnapshotQuery)({ - getCommandReadModel: () => Effect.succeed({ threads: [], projects: [] } as never), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getProjectCatalog: () => Effect.succeed({ projects: diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index 5170dff70..663e619fa 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -1065,14 +1065,8 @@ const make = Effect.gen(function* () { * touch it. Null when that couldn't be read. */ const pathInUse = (path: string) => - snapshots.getCommandReadModel().pipe( - Effect.map((model): boolean | null => - model.threads.some( - (thread) => - thread.deletedAt === null && - (thread.worktreePath === path || thread.effectiveCwd === path), - ), - ), + snapshots.isThreadWorkspacePathInUse(path).pipe( + Effect.map((inUse): boolean | null => inUse), Effect.orElseSucceed((): boolean | null => null), ); diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts index b757b93fb..0e5bfc7a5 100644 --- a/apps/server/src/moves/ThreadMoves.ts +++ b/apps/server/src/moves/ThreadMoves.ts @@ -1590,7 +1590,7 @@ const make = Effect.gen(function* () { * differ), and the move is dropped there instead. */ const exportFor = ( - thread: OrchestrationThread, + threadId: ThreadId, agent: ModelSelection, transferId: ThreadMoveId, offered: boolean, @@ -1611,22 +1611,24 @@ const make = Effect.gen(function* () { reason: "This computer lost the packed thread. Start the move again.", }); } - const model = yield* readModel.pipe( - Effect.mapError(() => new ThreadMoveFailure({ reason: "This thread couldn't be read." })), - ); - const project = model.projects.find((entry) => entry.id === thread.projectId); - if (project === undefined) { - return yield* new ThreadMoveFailure({ reason: "This thread's project is gone." }); - } const detail = yield* snapshots - .getThreadDetailById(thread.id, { includeArchived: true }) + .getThreadDetailById(threadId, { includeArchived: true }) .pipe( Effect.mapError(() => new ThreadMoveFailure({ reason: "This thread couldn't be read." })), ); if (Option.isNone(detail)) { return yield* new ThreadMoveFailure({ reason: "This thread couldn't be read." }); } - const nativeSession = yield* sessionToCarry(thread.id, targetEnvironmentId, agent); + const catalog = yield* snapshots + .getProjectCatalog() + .pipe( + Effect.mapError(() => new ThreadMoveFailure({ reason: "This thread couldn't be read." })), + ); + const project = catalog.projects.find((entry) => entry.id === detail.value.projectId); + if (project === undefined) { + return yield* new ThreadMoveFailure({ reason: "This thread's project is gone." }); + } + const nativeSession = yield* sessionToCarry(threadId, targetEnvironmentId, agent); // What it had going, for a computer that takes it (docs/design/fleet.md, // Part 3e); one that doesn't never gets it, and couldn't have been // offered a thread that needs it. @@ -1635,7 +1637,7 @@ const make = Effect.gen(function* () { const state = takes?.threadState === true ? moveThreadStateOf( - threadMoveCarry({ projects: model.projects }, detail.value), + threadMoveCarry({ projects: catalog.projects }, detail.value), withRoom ? sessionSlotParticipantId(detail.value.session) : null, ) : undefined; @@ -1648,26 +1650,45 @@ const make = Effect.gen(function* () { const outsideWork = takes?.outsideWork === true ? (detail.value.outsideWork ?? []) : []; // Its family (Part 3f, (g)), only for a computer that takes families. const moveFamily = takes?.families === true ? detail.value.move?.family : undefined; - const threads = model.threads.map((entry) => - entry.id === detail.value.id ? detail.value : entry, - ); - const family = - moveFamily === undefined - ? undefined - : familyManifestOf( - { projects: model.projects, threads }, - detail.value, - moveFamily, - targetEnvironmentId, - ); - const familyThreadIds = - moveFamily === undefined ? undefined : familyThreadIdsOf(threads, moveFamily); + let family: ReturnType | undefined = undefined; + let familyThreadIds: ReturnType | undefined = undefined; + if (moveFamily !== undefined) { + const model = yield* readModel.pipe( + Effect.mapError(() => new ThreadMoveFailure({ reason: "This thread couldn't be read." })), + ); + const threads = model.threads.map((entry) => + entry.id === detail.value.id ? detail.value : entry, + ); + family = familyManifestOf( + { projects: model.projects, threads }, + detail.value, + moveFamily, + targetEnvironmentId, + ); + familyThreadIds = familyThreadIdsOf(threads, moveFamily); + } // Across the link its work came over (Part 3f, (h)), only for a // computer that takes it back that way. - const linkLineage = - takes?.linkLineage === true && moveFamily === undefined - ? linkLineageOf(threads, detail.value, targetEnvironmentId) - : undefined; + let linkLineage: ReturnType = undefined; + if (takes?.linkLineage === true && moveFamily === undefined) { + const parentDetail = + (detail.value.remoteOrigin ?? null) === null && + detail.value.parentThreadId !== null && + detail.value.attachedToParent + ? yield* snapshots + .getThreadDetailById(detail.value.parentThreadId, { includeArchived: true }) + .pipe( + Effect.mapError( + () => new ThreadMoveFailure({ reason: "This thread couldn't be read." }), + ), + ) + : Option.none(); + linkLineage = linkLineageOf( + [detail.value, ...Option.toArray(parentDetail)], + detail.value, + targetEnvironmentId, + ); + } // The threads it started there, for a computer that takes them back // as its children (Part 3f, (g)). const startedThere = @@ -1683,12 +1704,12 @@ const make = Effect.gen(function* () { const source = { environmentId: descriptor.environmentId, environmentLabel: environment.currentLabel(), - threadId: thread.id, + threadId, }; if (project.kind === "general-chat") { return yield* writeScratchExport({ dir, - folder: generalChatThreadScratchCwd(project.workspaceRoot, thread.id, NodePath), + folder: generalChatThreadScratchCwd(project.workspaceRoot, threadId, NodePath), attachmentsDir: config.attachmentsDir, thread: detail.value, source, @@ -1940,8 +1961,10 @@ const make = Effect.gen(function* () { }); return; } - const thread = (yield* readModel).threads.find((entry) => entry.id === threadId); - if (thread === undefined) return; + const threadRow = yield* threadRows + .getById({ threadId }) + .pipe(Effect.mapError(() => moveError("This computer's threads couldn't be read."))); + if (Option.isNone(threadRow)) return; // Nothing of the thread may still run while it's packed: its agent's // processes must be proven gone (docs/design/fleet.md, Part 3b). Not // proven, this attempt stops and the worker tries again; the thread @@ -1953,7 +1976,7 @@ const make = Effect.gen(function* () { }); } const manifest = yield* exportFor( - thread, + threadId, move.agent, transferId, false, @@ -2035,10 +2058,12 @@ const make = Effect.gen(function* () { break; } case "receiving": { - const thread = (yield* readModel).threads.find((entry) => entry.id === threadId); - if (thread === undefined) return; + const threadRow = yield* threadRows + .getById({ threadId }) + .pipe(Effect.mapError(() => moveError("This computer's threads couldn't be read."))); + if (Option.isNone(threadRow)) return; const manifest = yield* exportFor( - thread, + threadId, move.agent, transferId, true, @@ -2100,27 +2125,28 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const events = yield* engine.subscribeDomainEvents; // Every move the previous process left unfinished. - const model = yield* readModel.pipe(Effect.option); - if (Option.isSome(model)) { - for (const thread of model.value.threads) { - const move = thread.move ?? null; - if (thread.deletedAt === null && move !== null && move.movedAway === undefined) { - yield* runMove(thread.id, move.transferId).pipe(Effect.forkScoped); + const movingThreads = yield* snapshots.listThreadsWithMove().pipe(Effect.option); + if (Option.isSome(movingThreads)) { + for (const entry of movingThreads.value) { + if (entry.deletedAt === null && entry.move.movedAway === undefined) { + yield* runMove(entry.threadId, entry.move.transferId).pipe(Effect.forkScoped); } } // A packed copy left by a move that landed while no worker was there // to tidy it (the thread came back first, then this computer stopped). - const packed = new Set( - yield* Effect.tryPromise(() => - NodeFs.readdir(NodePath.join(config.stateDir, "moves")), - ).pipe(Effect.orElseSucceed((): ReadonlyArray => [])), - ); - for (const thread of model.value.threads) { - const move = thread.move ?? null; - if (move !== null && move.movedAway !== undefined && packed.has(move.transferId)) { + const movedAway = movingThreads.value.filter((entry) => entry.move.movedAway !== undefined); + if (movedAway.length > 0) { + const packed = new Set( yield* Effect.tryPromise(() => - NodeFs.rm(moveDir(move.transferId), { recursive: true, force: true }), - ).pipe(Effect.ignore); + NodeFs.readdir(NodePath.join(config.stateDir, "moves")), + ).pipe(Effect.orElseSucceed((): ReadonlyArray => [])), + ); + for (const entry of movedAway) { + if (packed.has(entry.move.transferId)) { + yield* Effect.tryPromise(() => + NodeFs.rm(moveDir(entry.move.transferId), { recursive: true, force: true }), + ).pipe(Effect.ignore); + } } } } diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts index a03d31462..f80cf7b47 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.test.ts @@ -236,6 +236,9 @@ describe("OrchestrationEngine", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), ), diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index ed2309d0e..ba93d4c83 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -107,6 +107,7 @@ import { toSafeThreadAttachmentSegment, } from "../../attachmentStore.ts"; import { + activityMayAffectSubagents, keepKnownSubagentProviders, projectSubagentActivity, } from "@threadlines/shared/subagentProjection"; @@ -1437,6 +1438,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti case "thread.proposed-plan-upserted": case "thread.approval-response-requested": case "thread.user-input-response-requested": { + // An agent's reply never changes stopsWithParent, outsideWork, or the + // shell summary counts (user message, plans, prompts, approvals), and + // arrives many times a second while streaming. + if (event.type === "thread.message-sent" && event.payload.role === "assistant") { + yield* projectionThreadRepository.touchUpdatedAt({ + threadId: event.payload.threadId, + updatedAt: event.occurredAt, + }); + return; + } const existingRow = yield* projectionThreadRepository.getById({ threadId: event.payload.threadId, }); @@ -1467,27 +1478,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti } : {}), }); - // An agent's reply changes nothing the summary counts (the user's - // last message, plans, prompts, approvals), and while it streams it - // arrives many times a second. - if (event.type === "thread.message-sent" && event.payload.role === "assistant") { - return; - } yield* refreshThreadShellSummary(event.payload.threadId); return; } case "thread.activity-appended": { - const existingRow = yield* projectionThreadRepository.getById({ + const touched = yield* projectionThreadRepository.touchUpdatedAt({ threadId: event.payload.threadId, + updatedAt: event.occurredAt, }); - if (Option.isNone(existingRow)) { + if (!touched) { return; } - yield* projectionThreadRepository.upsert({ - ...existingRow.value, - updatedAt: event.occurredAt, - }); if (activityMayAffectThreadShellSummary(event.payload.activity)) { yield* refreshThreadShellSummary(event.payload.threadId); } @@ -2174,18 +2176,20 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti : {}), createdAt: event.payload.activity.createdAt, }); - const existingSubagents = yield* projectionThreadSubagentRepository.listByThreadId({ - threadId: event.payload.threadId, - }); - const nextSubagents = projectSubagentActivity(existingSubagents, { - ...event.payload.activity, - eventSequence: event.sequence, - }); - if (nextSubagents !== existingSubagents) { - yield* projectionThreadSubagentRepository.replaceByThreadId( - event.payload.threadId, - nextSubagents, - ); + if (activityMayAffectSubagents(event.payload.activity)) { + const existingSubagents = yield* projectionThreadSubagentRepository.listByThreadId({ + threadId: event.payload.threadId, + }); + const nextSubagents = projectSubagentActivity(existingSubagents, { + ...event.payload.activity, + eventSequence: event.sequence, + }); + if (nextSubagents !== existingSubagents) { + yield* projectionThreadSubagentRepository.replaceByThreadId( + event.payload.threadId, + nextSubagents, + ); + } } return; } @@ -2502,37 +2506,53 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti if (event.payload.turnId === null || event.payload.role !== "assistant") { return; } - const existingSession = yield* projectionThreadSessionRepository.getByThreadId({ - threadId: event.payload.threadId, - }); - const completesTurn = assistantMessageEventCompletesTurn({ - streaming: event.payload.streaming, - explicitCompletesTurn: event.payload.completesTurn, - activeTurnId: Option.isSome(existingSession) - ? existingSession.value.activeTurnId - : null, - eventTurnId: event.payload.turnId, - }); + let completesTurn = false; + if (!event.payload.streaming) { + const existingSession = yield* projectionThreadSessionRepository.getByThreadId({ + threadId: event.payload.threadId, + }); + completesTurn = assistantMessageEventCompletesTurn({ + streaming: event.payload.streaming, + explicitCompletesTurn: event.payload.completesTurn, + activeTurnId: Option.isSome(existingSession) + ? existingSession.value.activeTurnId + : null, + eventTurnId: event.payload.turnId, + }); + } const existingTurn = yield* projectionTurnRepository.getByTurnId({ threadId: event.payload.threadId, turnId: event.payload.turnId, }); if (Option.isSome(existingTurn)) { + const nextState = !completesTurn + ? existingTurn.value.state + : existingTurn.value.state === "interrupted" + ? "interrupted" + : existingTurn.value.state === "error" + ? "error" + : "completed"; + const nextCompletedAt = !completesTurn + ? existingTurn.value.completedAt + : (existingTurn.value.completedAt ?? event.payload.updatedAt); + const nextStartedAt = existingTurn.value.startedAt ?? event.payload.createdAt; + const nextRequestedAt = existingTurn.value.requestedAt ?? event.payload.createdAt; + if ( + existingTurn.value.assistantMessageId === event.payload.messageId && + existingTurn.value.state === nextState && + existingTurn.value.completedAt === nextCompletedAt && + existingTurn.value.startedAt === nextStartedAt && + existingTurn.value.requestedAt === nextRequestedAt + ) { + return; + } yield* projectionTurnRepository.upsertByTurnId({ ...existingTurn.value, assistantMessageId: event.payload.messageId, - state: !completesTurn - ? existingTurn.value.state - : existingTurn.value.state === "interrupted" - ? "interrupted" - : existingTurn.value.state === "error" - ? "error" - : "completed", - completedAt: !completesTurn - ? existingTurn.value.completedAt - : (existingTurn.value.completedAt ?? event.payload.updatedAt), - startedAt: existingTurn.value.startedAt ?? event.payload.createdAt, - requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt, + state: nextState, + completedAt: nextCompletedAt, + startedAt: nextStartedAt, + requestedAt: nextRequestedAt, }); return; } diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts index 0908c7d78..3cc677bc7 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.test.ts @@ -1858,6 +1858,102 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => { }), ); + it.effect( + "reads narrow ingestion context, moving threads, and workspace path usage directly", + () => + Effect.gen(function* () { + const snapshotQuery = yield* ProjectionSnapshotQuery; + const sql = yield* SqlClient.SqlClient; + + yield* sql`DELETE FROM projection_threads`; + yield* sql`DELETE FROM projection_thread_sessions`; + + const sideTurnsJson = JSON.stringify([ + { + sideTurnId: "side-1", + participantId: "participant-1", + messageId: "msg-side-1", + status: "running", + requestId: "req-1", + kind: "ask", + startedAt: "2026-04-02T00:00:00.000Z", + }, + ]); + const moveJson = JSON.stringify({ + transferId: "move-1", + target: { environmentId: "env-remote", label: "Mini" }, + agent: { provider: "codex", model: "gpt-5-codex" }, + phase: "exporting", + cancelRequested: false, + startedAt: "2026-04-02T00:00:00.000Z", + }); + + yield* sql` + INSERT INTO projection_threads ( + thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode, + branch, worktree_path, effective_cwd, latest_turn_id, created_at, updated_at, + archived_at, deleted_at, side_turn, move_json + ) VALUES + ( + 'thread-active-ctx', 'project-1', 'Active', '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', 'default', 'main', '/tmp/wt-active', NULL, NULL, + '2026-04-02T00:00:00.000Z', '2026-04-02T00:00:00.000Z', NULL, NULL, ${sideTurnsJson}, ${moveJson} + ), + ( + 'thread-archived-ctx', 'project-1', 'Archived', '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', 'default', 'main', NULL, '/tmp/cwd-archived', NULL, + '2026-04-02T00:00:01.000Z', '2026-04-02T00:00:01.000Z', '2026-04-02T00:01:00.000Z', NULL, NULL, NULL + ), + ( + 'thread-deleted-ctx', 'project-1', 'Deleted', '{"provider":"codex","model":"gpt-5-codex"}', + 'full-access', 'default', 'main', '/tmp/wt-deleted', NULL, NULL, + '2026-04-02T00:00:02.000Z', '2026-04-02T00:00:02.000Z', NULL, '2026-04-02T00:02:00.000Z', NULL, NULL + ) + `; + yield* sql` + INSERT INTO projection_thread_sessions ( + thread_id, status, provider_name, provider_instance_id, provider_session_id, + provider_thread_id, runtime_mode, active_turn_id, last_error, updated_at + ) VALUES ( + 'thread-active-ctx', 'running', 'codex', 'codex-main', 'sess-1', + 'prov-thread-1', 'full-access', 'turn-1', NULL, '2026-04-02T00:00:00.000Z' + ) + `; + + const active = yield* snapshotQuery.getThreadIngestionContext( + ThreadId.make("thread-active-ctx"), + ); + assert.equal(active._tag, "Some"); + if (active._tag === "Some") { + assert.equal(active.value.id, "thread-active-ctx"); + assert.equal(active.value.session?.providerThreadId, "prov-thread-1"); + assert.equal(active.value.sideTurn?.sideTurnId, "side-1"); + assert.equal(active.value.sideTurns.length, 1); + } + assert.equal( + (yield* snapshotQuery.getThreadIngestionContext(ThreadId.make("thread-archived-ctx"))) + ._tag, + "None", + ); + assert.equal( + (yield* snapshotQuery.getThreadIngestionContext(ThreadId.make("thread-deleted-ctx"))) + ._tag, + "None", + ); + + const moving = yield* snapshotQuery.listThreadsWithMove(); + assert.deepEqual( + moving.map((entry) => [entry.threadId, entry.move.transferId]), + [["thread-active-ctx", "move-1"]], + ); + + assert.equal(yield* snapshotQuery.isThreadWorkspacePathInUse("/tmp/wt-active"), true); + assert.equal(yield* snapshotQuery.isThreadWorkspacePathInUse("/tmp/cwd-archived"), true); + assert.equal(yield* snapshotQuery.isThreadWorkspacePathInUse("/tmp/wt-deleted"), false); + assert.equal(yield* snapshotQuery.isThreadWorkspacePathInUse("/tmp/unused"), false); + }), + ); + it.effect("hydrates thread messages into the command read model", () => Effect.gen(function* () { const snapshotQuery = yield* ProjectionSnapshotQuery; diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 55283b146..d4a846e8b 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -141,6 +141,8 @@ import { type ProjectionFullThreadDiffContext, type ProjectionSnapshotCounts, type ProjectionThreadCheckpointContext, + type ProjectionThreadIngestionContext, + type ProjectionThreadMoveSummary, type ProjectionSnapshotQueryShape, } from "../Services/ProjectionSnapshotQuery.ts"; @@ -456,6 +458,21 @@ const ThreadRowLookupInput = Schema.Struct({ threadId: ThreadId, includeArchived: Schema.optional(Schema.Boolean), }); +const WorkspacePathLookupInput = Schema.Struct({ + path: Schema.String, +}); +const WorkspacePathInUseRowSchema = Schema.Struct({ + inUse: Schema.Number, +}); +const ProjectionThreadIngestionRowSchema = Schema.Struct({ + threadId: ThreadId, + sideTurns: Schema.optional(Schema.NullOr(ProjectionSideTurnsJson)), +}); +const ProjectionThreadMoveSummaryDbRowSchema = Schema.Struct({ + threadId: ThreadId, + deletedAt: Schema.NullOr(IsoDateTime), + move: Schema.fromJsonString(OrchestrationThreadMove), +}); const TurnActivityLookupInput = Schema.Struct({ threadId: ThreadId, turnId: TurnId, @@ -1659,10 +1676,20 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { GROUP BY thread_id `; - const listThreadDiffStatRows = SqlSchema.findAll({ + const listActiveThreadDiffStatRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadDiffStatDbRowSchema, + execute: () => + threadDiffStatQuery(sql`WHERE threads.deleted_at IS NULL AND threads.archived_at IS NULL`), + }); + + const listArchivedThreadDiffStatRows = SqlSchema.findAll({ Request: Schema.Void, Result: ProjectionThreadDiffStatDbRowSchema, - execute: () => threadDiffStatQuery(sql``), + execute: () => + threadDiffStatQuery( + sql`WHERE threads.deleted_at IS NULL AND threads.archived_at IS NOT NULL`, + ), }); const getThreadDiffStatRow = SqlSchema.findOneOption({ @@ -3400,7 +3427,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ), ), - listThreadDiffStatRows(undefined).pipe( + listActiveThreadDiffStatRows(undefined).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( "ProjectionSnapshotQuery.getShellSnapshot:listThreadDiffStats:query", @@ -3529,7 +3556,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ), ), - listThreadDiffStatRows(undefined).pipe( + listArchivedThreadDiffStatRows(undefined).pipe( Effect.mapError( toPersistenceSqlOrDecodeError( "ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadDiffStats:query", @@ -4035,6 +4062,50 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ), ); + const getActiveThreadIngestionRowById = SqlSchema.findOneOption({ + Request: ThreadIdLookupInput, + Result: ProjectionThreadIngestionRowSchema, + execute: ({ threadId }) => + sql` + SELECT + thread_id AS "threadId", + side_turn AS "sideTurns" + FROM projection_threads + WHERE thread_id = ${threadId} + AND deleted_at IS NULL + AND archived_at IS NULL + LIMIT 1 + `, + }); + + const listThreadMoveSummaryRows = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectionThreadMoveSummaryDbRowSchema, + execute: () => + sql` + SELECT + thread_id AS "threadId", + deleted_at AS "deletedAt", + move_json AS "move" + FROM projection_threads + WHERE move_json IS NOT NULL + ORDER BY created_at ASC, thread_id ASC + `, + }); + + const getThreadWorkspacePathInUseRow = SqlSchema.findOneOption({ + Request: WorkspacePathLookupInput, + Result: WorkspacePathInUseRowSchema, + execute: ({ path }) => + sql` + SELECT 1 AS "inUse" + FROM projection_threads + WHERE deleted_at IS NULL + AND (worktree_path = ${path} OR effective_cwd = ${path}) + LIMIT 1 + `, + }); + const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) => Effect.gen(function* () { const [threadRow, latestTurnRow, sessionRow, diffStatRow] = yield* Effect.all([ @@ -4085,6 +4156,68 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { ); }); + const getThreadIngestionContext: ProjectionSnapshotQueryShape["getThreadIngestionContext"] = ( + threadId, + ) => + Effect.gen(function* () { + const threadRow = yield* getActiveThreadIngestionRowById({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadIngestionContext:getThread:query", + "ProjectionSnapshotQuery.getThreadIngestionContext:getThread:decodeRow", + ), + ), + ); + if (Option.isNone(threadRow)) { + return Option.none(); + } + const sessionRow = yield* getThreadSessionRowByThread({ threadId }).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.getThreadIngestionContext:getSession:query", + "ProjectionSnapshotQuery.getThreadIngestionContext:getSession:decodeRow", + ), + ), + ); + const sideTurns = threadRow.value.sideTurns ?? []; + return Option.some({ + id: threadRow.value.threadId, + session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null, + sideTurn: sideTurns[0] ?? null, + sideTurns, + }); + }); + + const listThreadsWithMove: ProjectionSnapshotQueryShape["listThreadsWithMove"] = () => + listThreadMoveSummaryRows(undefined).pipe( + Effect.map((rows): ReadonlyArray => + rows.map((row) => ({ + threadId: row.threadId, + deletedAt: row.deletedAt, + move: row.move, + })), + ), + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.listThreadsWithMove:query", + "ProjectionSnapshotQuery.listThreadsWithMove:decodeRows", + ), + ), + ); + + const isThreadWorkspacePathInUse: ProjectionSnapshotQueryShape["isThreadWorkspacePathInUse"] = ( + path, + ) => + getThreadWorkspacePathInUseRow({ path }).pipe( + Effect.map(Option.isSome), + Effect.mapError( + toPersistenceSqlOrDecodeError( + "ProjectionSnapshotQuery.isThreadWorkspacePathInUse:query", + "ProjectionSnapshotQuery.isThreadWorkspacePathInUse:decodeRow", + ), + ), + ); + const getThreadMessage: ProjectionSnapshotQueryShape["getThreadMessage"] = (input) => getThreadMessageRow(input).pipe( Effect.map(Option.map(mapThreadMessageRow)), @@ -4341,6 +4474,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { listSecretRequests, listThreadShells, getThreadShellById, + getThreadIngestionContext, + listThreadsWithMove, + isThreadWorkspacePathInUse, getThreadDetailById, getTurnActivities, getThreadMessage, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 102ea2430..c1c41f5cf 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -1081,6 +1081,14 @@ const make = Effect.gen(function* () { .pipe(Effect.map(Option.getOrUndefined)); }); + const resolveThreadIngestionContext = Effect.fn("resolveThreadIngestionContext")(function* ( + threadId: ThreadId, + ) { + return yield* projectionSnapshotQuery + .getThreadIngestionContext(threadId) + .pipe(Effect.map(Option.getOrUndefined)); + }); + // Per-turn accumulation of provider-reported file-change stats for adapters // that emit per-tool-call evidence (Claude) instead of cumulative turn diffs // (Codex). Keyed by thread:turn, then by provider item id so a re-delivered @@ -3105,6 +3113,131 @@ const make = Effect.gen(function* () { ), ); + const processContentDeltaEvent = Effect.fnUntraced(function* ( + event: Extract, + ) { + const thread = yield* resolveThreadIngestionContext(event.threadId); + if (!thread) return; + if (event.sideTurnId !== undefined) { + yield* processSideTurnEvent({ ...event, sideTurnId: event.sideTurnId }, thread); + return; + } + if ((event.participantId ?? null) !== sessionSlotParticipantId(thread.session)) { + yield* Effect.logDebug("provider runtime ingestion ignored an idle room agent's event", { + eventId: event.eventId, + eventType: event.type, + threadId: thread.id, + participantId: event.participantId ?? null, + }); + return; + } + if ( + STRICT_PROVIDER_LIFECYCLE_GUARD && + !runtimeEventMatchesThreadSession(event, thread.session) + ) { + yield* Effect.logDebug("provider runtime ingestion ignored stale provider event", { + eventId: event.eventId, + eventType: event.type, + eventProvider: event.provider, + eventProviderInstanceId: event.providerInstanceId, + threadId: thread.id, + sessionProvider: thread.session?.providerName, + sessionProviderInstanceId: thread.session?.providerInstanceId, + }); + return; + } + + const attributionThread = + providerThreadIdFromEvent(event) !== undefined && !thread.session?.providerThreadId?.trim() + ? ((yield* resolveThreadDetail(thread.id)) ?? thread) + : thread; + const now = event.createdAt; + + if (event.payload.streamKind === "assistant_text" && event.payload.delta.length > 0) { + const assistantDelta = event.payload.delta; + const childProviderThreadId = childProviderThreadIdForEvent(event, attributionThread); + if (childProviderThreadId) { + const bufferKey = subagentResultTextKey({ event, childProviderThreadId }); + const settled = yield* Cache.getOption(settledSubagentResultActivityKeys, bufferKey); + if (Option.isNone(settled)) { + const body = yield* appendBufferedSubagentResultText(bufferKey, assistantDelta); + yield* queueSubagentResultActivity(bufferKey, { + event, + threadId: thread.id, + parentProviderThreadId: thread.session?.providerThreadId ?? undefined, + childProviderThreadId, + body, + createdAt: now, + }); + } + } else { + const turnId = toTurnId(event.turnId); + const assistantMessageId = + event.raw?.method === "thread/realtime/transcript/delta" + ? yield* Ref.modify(realtimeAssistantMessageIds, (current) => { + const existing = current.get(thread.id); + if (existing) { + return [existing, current] as const; + } + const created = MessageId.make(`assistant:realtime:${thread.id}:${event.eventId}`); + const next = new Map(current); + next.set(thread.id, created); + return [created, next] as const; + }) + : yield* getOrCreateAssistantMessageId({ + threadId: thread.id, + event, + ...(turnId ? { turnId } : {}), + }); + if (turnId) { + yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); + } + + const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), + ); + if (assistantDeliveryMode === "buffered") { + const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); + if (spillChunk.length > 0) { + yield* dispatchAssistantDelta({ + event, + threadId: thread.id, + messageId: assistantMessageId, + delta: spillChunk, + ...(turnId ? { turnId } : {}), + createdAt: now, + commandTag: "assistant-delta-buffer-spill", + }); + } + } else { + yield* queueStreamingAssistantDelta({ + event, + threadId: thread.id, + messageId: assistantMessageId, + delta: assistantDelta, + ...(turnId ? { turnId } : {}), + createdAt: now, + }); + } + } + } + + const activities = yield* projectRuntimeActivities(event, attributionThread, thread.id); + yield* Effect.forEach(activities, (activity) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: providerCommandId(event, "thread-activity-append"), + threadId: thread.id, + activity: + event.participantId != null && activity.participantId === undefined + ? { ...activity, participantId: event.participantId } + : activity, + createdAt: activity.createdAt, + }), + ).pipe(Effect.asVoid); + }); + const processRuntimeEvent = (event: ProviderRuntimeEvent) => Effect.gen(function* () { // Realtime audio/item traffic is intentionally in-memory only. Keep this @@ -3116,6 +3249,13 @@ const make = Effect.gen(function* () { ) { return; } + // High-frequency streaming deltas only need the active thread's session + // guards and live side-turns, avoiding full shell hydration and diff-stat + // rollups on every chunk. + if (event.type === "content.delta") { + yield* processContentDeltaEvent(event); + return; + } const thread = yield* resolveThreadShell(event.threadId); // A workflow run keeps running in the runtime that started it after its // agent hands the thread on, or the thread moves to another provider, @@ -3924,87 +4064,9 @@ const make = Effect.gen(function* () { } } - const assistantDelta = - event.type === "content.delta" && event.payload.streamKind === "assistant_text" - ? event.payload.delta - : undefined; const proposedPlanDelta = event.type === "turn.proposed.delta" ? event.payload.delta : undefined; - if (assistantDelta && assistantDelta.length > 0) { - const childProviderThreadId = childProviderThreadIdForEvent(event, attributionThread); - if (childProviderThreadId) { - const bufferKey = subagentResultTextKey({ event, childProviderThreadId }); - const settled = yield* Cache.getOption(settledSubagentResultActivityKeys, bufferKey); - if (Option.isNone(settled)) { - const body = yield* appendBufferedSubagentResultText(bufferKey, assistantDelta); - yield* queueSubagentResultActivity(bufferKey, { - event, - threadId: thread.id, - parentProviderThreadId: thread.session?.providerThreadId ?? undefined, - childProviderThreadId, - body, - createdAt: now, - }); - } - } else { - const turnId = toTurnId(event.turnId); - const assistantMessageId = - event.raw?.method === "thread/realtime/transcript/delta" - ? yield* Ref.modify(realtimeAssistantMessageIds, (current) => { - const existing = current.get(thread.id); - if (existing) { - return [existing, current] as const; - } - const created = MessageId.make( - `assistant:realtime:${thread.id}:${event.eventId}`, - ); - const next = new Map(current); - next.set(thread.id, created); - return [created, next] as const; - }) - : yield* getOrCreateAssistantMessageId({ - threadId: thread.id, - event, - ...(turnId ? { turnId } : {}), - }); - if (turnId) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), - ); - if (assistantDeliveryMode === "buffered") { - const spillChunk = yield* appendBufferedAssistantText( - assistantMessageId, - assistantDelta, - ); - if (spillChunk.length > 0) { - yield* dispatchAssistantDelta({ - event, - threadId: thread.id, - messageId: assistantMessageId, - delta: spillChunk, - ...(turnId ? { turnId } : {}), - createdAt: now, - commandTag: "assistant-delta-buffer-spill", - }); - } - } else { - yield* queueStreamingAssistantDelta({ - event, - threadId: thread.id, - messageId: assistantMessageId, - delta: assistantDelta, - ...(turnId ? { turnId } : {}), - createdAt: now, - }); - } - } - } - // A non-blocking question does not pause the agent, so its streaming // text must not be cut into a settled message here. const pauseForUserTurnId = diff --git a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts index 38d281cb1..463ff8f45 100644 --- a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts +++ b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.test.ts @@ -446,6 +446,9 @@ function makeSnapshotQuery(input: { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }; } diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index ee662b2c4..d648d2e7a 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -163,6 +163,9 @@ function makeSnapshotQuery( getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }; } diff --git a/apps/server/src/orchestration/Layers/ThreadDiffStatBaselineReactor.test.ts b/apps/server/src/orchestration/Layers/ThreadDiffStatBaselineReactor.test.ts index 247520611..d1250c2fa 100644 --- a/apps/server/src/orchestration/Layers/ThreadDiffStatBaselineReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadDiffStatBaselineReactor.test.ts @@ -90,6 +90,9 @@ function makeSnapshotQuery( getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }; } diff --git a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts index 15820896a..dec802636 100644 --- a/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Services/ProjectionSnapshotQuery.ts @@ -8,6 +8,7 @@ */ import type { CheckpointRef, + IsoDateTime, MessageId, OrchestrationMessage, OrchestrationCheckpointSummary, @@ -20,6 +21,7 @@ import type { OrchestrationSideTurn, OrchestrationThread, OrchestrationThreadActivity, + OrchestrationThreadMove, OrchestrationThreadShell, OutsideAgentConnectionId, ProjectId, @@ -93,6 +95,28 @@ export interface ProjectionThreadTurnOverlap { readonly effectiveCwd: string | null; } +/** + * Minimal active-thread state needed to guard and route high-frequency + * `content.delta` runtime events without hydrating full thread shells or + * computing diff-stat rollups. + */ +export interface ProjectionThreadIngestionContext { + readonly id: ThreadId; + readonly session: OrchestrationSession | null; + readonly sideTurn: OrchestrationSideTurn | null; + readonly sideTurns: ReadonlyArray; +} + +/** + * Narrow move record for startup recovery and cleanup, avoiding a full + * read-model hydration when scanning for in-flight or completed moves. + */ +export interface ProjectionThreadMoveSummary { + readonly threadId: ThreadId; + readonly deletedAt: IsoDateTime | null; + readonly move: OrchestrationThreadMove; +} + /** * ProjectionSnapshotQueryShape - Service API for read-model snapshots. */ @@ -314,6 +338,31 @@ export interface ProjectionSnapshotQueryShape { threadId: ThreadId, ) => Effect.Effect, ProjectionRepositoryError>; + /** + * Read the minimal active-thread state needed for high-frequency runtime + * delta ingestion (session slot/instance guards and live side-turns). + */ + readonly getThreadIngestionContext: ( + threadId: ThreadId, + ) => Effect.Effect, ProjectionRepositoryError>; + + /** + * List threads that currently carry a move record (in-flight or moved-away), + * including deleted rows so startup can clean up stale export directories. + */ + readonly listThreadsWithMove: () => Effect.Effect< + ReadonlyArray, + ProjectionRepositoryError + >; + + /** + * Whether any non-deleted thread currently uses `path` as its worktree or + * effective working directory. + */ + readonly isThreadWorkspacePathInUse: ( + path: string, + ) => Effect.Effect; + /** * Read a single active thread detail snapshot by id; with * `includeArchived`, an archived one too (a move packs a thread archived diff --git a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts index e67c1070d..3a212a330 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadMessages.ts @@ -164,22 +164,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () { ${row.turnId}, ${row.role}, ${row.text}, - COALESCE( - ${nextAttachmentsJson}, - ( - SELECT attachments_json - FROM projection_thread_messages - WHERE message_id = ${row.messageId} - ) - ), - COALESCE( - ${nextSkillsJson}, - ( - SELECT skills_json - FROM projection_thread_messages - WHERE message_id = ${row.messageId} - ) - ), + ${nextAttachmentsJson}, + ${nextSkillsJson}, ${row.participantId ?? null}, ${row.sideTurnId ?? null}, ${row.fromAgent !== undefined ? JSON.stringify(row.fromAgent) : null}, diff --git a/apps/server/src/persistence/Layers/ProjectionThreads.ts b/apps/server/src/persistence/Layers/ProjectionThreads.ts index e2b3760ff..1200f29c8 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreads.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreads.ts @@ -2,6 +2,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as SqlSchema from "effect/sql/SqlSchema"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Struct from "effect/Struct"; @@ -16,6 +17,7 @@ import { ProjectionThread, ProjectionThreadRepository, type ProjectionThreadRepositoryShape, + TouchProjectionThreadUpdatedAtInput, sideTurnsColumnValue, } from "../Services/ProjectionThreads.ts"; import { @@ -497,6 +499,18 @@ const makeProjectionThreadRepository = Effect.gen(function* () { `, }); + const touchProjectionThreadUpdatedAtRow = SqlSchema.findOneOption({ + Request: TouchProjectionThreadUpdatedAtInput, + Result: Schema.Struct({ threadId: ThreadId }), + execute: ({ threadId, updatedAt }) => + sql` + UPDATE projection_threads + SET updated_at = ${updatedAt} + WHERE thread_id = ${threadId} + RETURNING thread_id AS "threadId" + `, + }); + const deleteProjectionThreadRow = SqlSchema.void({ Request: DeleteProjectionThreadInput, execute: ({ threadId }) => @@ -511,6 +525,12 @@ const makeProjectionThreadRepository = Effect.gen(function* () { Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.upsert:query")), ); + const touchUpdatedAt: ProjectionThreadRepositoryShape["touchUpdatedAt"] = (input) => + touchProjectionThreadUpdatedAtRow(input).pipe( + Effect.map(Option.isSome), + Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.touchUpdatedAt:query")), + ); + const getById: ProjectionThreadRepositoryShape["getById"] = (input) => getProjectionThreadRow(input).pipe( Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")), @@ -552,6 +572,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () { return { upsert, + touchUpdatedAt, getById, listByProjectId, listIdsByRemoteLink, diff --git a/apps/server/src/persistence/Migrations.test.ts b/apps/server/src/persistence/Migrations.test.ts index a5a385511..1b194fac0 100644 --- a/apps/server/src/persistence/Migrations.test.ts +++ b/apps/server/src/persistence/Migrations.test.ts @@ -37,4 +37,55 @@ it.layer(NodeSqliteClient.layerMemory())("runMigrations", (it) => { assert.deepStrictEqual(reads, [false]); }), ); + + it.effect("drops redundant indexes in migration 126 while keeping active ordering indexes", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* runMigrations(); + + const indexes = yield* sql<{ readonly name: string }>` + SELECT name FROM sqlite_master WHERE type = 'index' + `; + const names = new Set(indexes.map((row) => row.name)); + + for (const dropped of [ + "idx_orch_events_command_id", + "idx_orch_events_correlation_id", + "idx_projection_thread_activities_thread_created", + "idx_projection_thread_activities_thread_sequence", + "idx_projection_thread_activities_thread_sequence_created_id", + "idx_projection_thread_messages_thread_created", + ]) { + assert.isFalse(names.has(dropped), `expected ${dropped} to be dropped`); + } + + for (const kept of [ + "idx_projection_thread_messages_thread_created_id", + "idx_projection_thread_messages_event_order", + "idx_projection_thread_activities_event_order", + "idx_projection_thread_activities_prompt_kinds", + "idx_projection_thread_activities_plan_updates", + "idx_projection_thread_activities_turn", + ]) { + assert.isTrue(names.has(kept), `expected ${kept} to remain`); + } + + const plan = yield* sql<{ readonly detail: string }>` + EXPLAIN QUERY PLAN + SELECT created_at AS "createdAt" + FROM projection_thread_messages + WHERE thread_id = 'thread-1' + AND role = 'user' + AND from_agent IS NULL + AND from_thread IS NULL + AND from_outside IS NULL + ORDER BY created_at DESC + LIMIT 1 + `; + assert.isTrue( + plan.some((row) => row.detail.includes("idx_projection_thread_messages_thread_created_id")), + `expected query plan to use idx_projection_thread_messages_thread_created_id, got: ${plan.map((r) => r.detail).join("; ")}`, + ); + }), + ); }); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 9c0f6cb3f..7c496b729 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -145,6 +145,7 @@ import Migration0122 from "./Migrations/122_ProjectBriefs.ts"; import Migration0123 from "./Migrations/123_ProjectNotes.ts"; import Migration0124 from "./Migrations/124_ChildAccessAndStopColumns.ts"; import Migration0125 from "./Migrations/125_ThemeShowcaseUpdateBaseSha.ts"; +import Migration0126 from "./Migrations/126_DropRedundantIndexes.ts"; /** * Migration loader with all migrations defined inline. @@ -282,6 +283,7 @@ export const migrationEntries = [ [123, "ProjectNotes", Migration0123], [124, "ChildAccessAndStopColumns", Migration0124], [125, "ThemeShowcaseUpdateBaseSha", Migration0125], + [126, "DropRedundantIndexes", Migration0126], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/126_DropRedundantIndexes.ts b/apps/server/src/persistence/Migrations/126_DropRedundantIndexes.ts new file mode 100644 index 000000000..b9f73c989 --- /dev/null +++ b/apps/server/src/persistence/Migrations/126_DropRedundantIndexes.ts @@ -0,0 +1,28 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * Drop six unused or redundant SQLite indexes to cut write amplification on + * event append, message streaming, and activity projection: + * + * - `idx_orch_events_command_id` and `idx_orch_events_correlation_id`: no + * query filters `orchestration_events` by `command_id` or `correlation_id` + * (command idempotency reads `orchestration_command_receipts` by primary key). + * - `idx_projection_thread_activities_thread_created`, + * `idx_projection_thread_activities_thread_sequence`, and + * `idx_projection_thread_activities_thread_sequence_created_id`: superseded + * by `idx_projection_thread_activities_event_order` (migration 050), the + * partial kind indexes (migration 070), and the turn index (migration 099). + * - `idx_projection_thread_messages_thread_created`: strict left prefix of + * `idx_projection_thread_messages_thread_created_id` (migration 029). + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql`DROP INDEX IF EXISTS idx_orch_events_command_id`; + yield* sql`DROP INDEX IF EXISTS idx_orch_events_correlation_id`; + yield* sql`DROP INDEX IF EXISTS idx_projection_thread_activities_thread_created`; + yield* sql`DROP INDEX IF EXISTS idx_projection_thread_activities_thread_sequence`; + yield* sql`DROP INDEX IF EXISTS idx_projection_thread_activities_thread_sequence_created_id`; + yield* sql`DROP INDEX IF EXISTS idx_projection_thread_messages_thread_created`; +}); diff --git a/apps/server/src/persistence/NodeSqliteClient.test.ts b/apps/server/src/persistence/NodeSqliteClient.test.ts index f21ae8f34..fe8cfadee 100644 --- a/apps/server/src/persistence/NodeSqliteClient.test.ts +++ b/apps/server/src/persistence/NodeSqliteClient.test.ts @@ -89,6 +89,31 @@ layer("NodeSqliteClient", (it) => { assert.deepStrictEqual(rows, [{ kind: "plain" }]); }), ); + + it.effect("commits and rolls back nested savepoints cleanly", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE nested(name TEXT NOT NULL)`; + + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`INSERT INTO nested(name) VALUES ('outer')`; + yield* sql + .withTransaction( + Effect.gen(function* () { + yield* sql`INSERT INTO nested(name) VALUES ('rolled-back')`; + return yield* Effect.fail("inner-fail"); + }), + ) + .pipe(Effect.ignore); + yield* sql.withTransaction(sql`INSERT INTO nested(name) VALUES ('inner-ok')`); + }), + ); + + const rows = yield* sql<{ readonly name: string }>`SELECT name FROM nested ORDER BY rowid`; + assert.deepStrictEqual(rows, [{ name: "outer" }, { name: "inner-ok" }]); + }), + ); }); it.live("an interrupted query never keeps the connection", () => diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts index 43d7e682b..0d29b0fc8 100644 --- a/apps/server/src/persistence/NodeSqliteClient.ts +++ b/apps/server/src/persistence/NodeSqliteClient.ts @@ -10,6 +10,7 @@ import * as Cache from "effect/Cache"; import * as Config from "effect/Config"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import { identity } from "effect/Function"; import * as Layer from "effect/Layer"; import * as Scope from "effect/Scope"; @@ -19,7 +20,7 @@ import * as Stream from "effect/Stream"; import * as Reactivity from "effect/reactivity/Reactivity"; import * as Client from "effect/sql/SqlClient"; import type { Connection } from "effect/sql/SqlConnection"; -import { ConnectionError, SqlError, classifySqliteError } from "effect/sql/SqlError"; +import { SqlError, classifySqliteError } from "effect/sql/SqlError"; import * as Statement from "effect/sql/Statement"; import { timeDatabaseCall } from "../observability/databaseCallTime.ts"; @@ -105,20 +106,22 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* ( return value; }; - const prepareCache = yield* Cache.make({ - capacity: options.prepareCacheSize ?? 200, - timeToLive: options.prepareCacheTTL ?? Duration.minutes(10), - lookup: (sql: string) => - Effect.try({ - try: () => timeDatabaseCall(() => db.prepare(sql)), - catch: (cause) => - new SqlError({ - reason: classifySqliteError(cause, { - message: "Failed to prepare statement", - operation: "prepare", - }), + const prepare = (sql: string) => + Effect.try({ + try: () => timeDatabaseCall(() => db.prepare(sql)), + catch: (cause) => + new SqlError({ + reason: classifySqliteError(cause, { + message: "Failed to prepare statement", + operation: "prepare", }), - }), + }), + }); + + const prepareCacheTTL = options.prepareCacheTTL ?? Duration.minutes(10); + const prepareCache = yield* Cache.makeWith(prepare, { + capacity: options.prepareCacheSize ?? 1024, + timeToLive: (exit) => (Exit.isSuccess(exit) ? prepareCacheTTL : Duration.zero), }); const runStatement = (statement: StatementSync, params: ReadonlyArray, raw: boolean) => @@ -179,7 +182,12 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* ( }), ); - const connection = identity({ + interface SqliteConnection extends Connection { + readonly isTransaction: () => boolean; + } + + const connection = identity({ + isTransaction: () => db.isTransaction, execute(sql, params, rowTransform) { return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params); }, @@ -190,16 +198,13 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* ( return runValues(sql, params); }, executeValuesUnprepared(sql, params) { - return runValuesStatement( - timeDatabaseCall(() => db.prepare(sql)), - params ?? [], + return Effect.flatMap(prepare(sql), (statement) => + runValuesStatement(statement, params ?? []), ); }, executeUnprepared(sql, params, rowTransform) { - const effect = runStatement( - timeDatabaseCall(() => db.prepare(sql)), - params ?? [], - false, + const effect = Effect.flatMap(prepare(sql), (statement) => + runStatement(statement, params ?? [], false), ); return rowTransform ? Effect.map(effect, rowTransform) : effect; }, @@ -207,93 +212,28 @@ const makeWithDatabase = Effect.fn("makeWithDatabase")(function* ( return Stream.die("executeStream not implemented"); }, }); - return { connection, isTransaction: () => db.isTransaction }; + return connection; }); const semaphore = yield* Semaphore.make(1); - const { connection, isTransaction } = yield* makeConnection; - - // SQLite can keep a transaction open after COMMIT fails (a deferred foreign - // key violation, for one). `onCommitFailure` rolls it back before anyone - // else gets the connection. If that ROLLBACK fails too, the connection stays - // marked: every later statement and transaction retries the ROLLBACK first - // and fails until it works, so nothing lands in the dead transaction. - let needsRollback = false; - const rollbackOpenTransaction = Effect.suspend(() => - isTransaction() - ? Effect.asVoid(connection.executeUnprepared("ROLLBACK", [], undefined)) - : Effect.void, - ); - const onCommitFailure = () => - rollbackOpenTransaction.pipe( - Effect.tapCause(() => - Effect.sync(() => { - needsRollback = true; - }), - ), - ); - const ensureUsable = Effect.suspend(() => - needsRollback - ? rollbackOpenTransaction.pipe( - Effect.andThen( - Effect.sync(() => { - needsRollback = false; - }), - ), - Effect.mapError( - (cause) => - new SqlError({ - reason: new ConnectionError({ - message: "SQLite connection cannot be reused after failed COMMIT cleanup", - operation: "rollback", - cause, - }), - }), - ), - ) - : Effect.void, - ); - - // Plain statements and transactions share the one connection, so each holds - // it for its whole run: a plain statement while it executes, a transaction - // until COMMIT or ROLLBACK. A statement that let go of the connection before - // running could land inside another fiber's open transaction, where a - // rollback silently undid an acknowledged write. Upstream fixed the same race - // in effect 4.0.3 (Effect-TS/effect#8927). - // - // `withPermits` waits interruptibly and registers the release in the same - // step that takes the permit. The statement is built inside it because the - // unprepared methods call `db.prepare` as soon as they are called. Statements - // inside a transaction run on the bare connection the transaction holds. - const holdConnection = (statement: () => Effect.Effect) => - semaphore.withPermits(1)(Effect.andThen(ensureUsable, Effect.suspend(statement))); - const plainConnection = identity({ - execute: (sql, params, rowTransform) => - holdConnection(() => connection.execute(sql, params, rowTransform)), - executeRaw: (sql, params) => holdConnection(() => connection.executeRaw(sql, params)), - executeValues: (sql, params) => holdConnection(() => connection.executeValues(sql, params)), - executeValuesUnprepared: (sql, params) => - holdConnection(() => connection.executeValuesUnprepared(sql, params)), - executeUnprepared: (sql, params, rowTransform) => - holdConnection(() => connection.executeUnprepared(sql, params, rowTransform)), - // Not implemented. A real stream would hold the connection until it ends. - executeStream: (sql, params, rowTransform) => - connection.executeStream(sql, params, rowTransform), - }); - // Taken without interruption, so the permit is never counted without its - // release. `withTransaction` masks interruption here anyway; the one cost is - // that a waiting `sql.reserve` (unused here) cannot be cancelled. - const transactionAcquirer = Effect.acquireRelease(semaphore.take(1), () => - semaphore.release(1), - ).pipe(Effect.andThen(ensureUsable), Effect.as(connection)); + const connection = yield* makeConnection; + const { acquirer, borrower, isTransaction, onCommitFailure, transactionAcquirer } = + Client.makeSqliteAcquirers({ + connection: Effect.succeed(connection), + semaphore, + isTransaction: (conn) => conn.isTransaction(), + }); return yield* Client.make({ driver: "sqlite-node", - acquirer: Effect.succeed(plainConnection), + acquirer, + borrower, compiler, transactionAcquirer, onCommitFailure, isTransaction, + prepareTransactionControls: true, + releaseSavepoint: (name) => `RELEASE SAVEPOINT ${name}`, spanAttributes: [ ...(options.spanAttributes ? Object.entries(options.spanAttributes) : []), [ATTR_DB_SYSTEM_NAME, "sqlite"], diff --git a/apps/server/src/persistence/Services/ProjectionThreads.ts b/apps/server/src/persistence/Services/ProjectionThreads.ts index 88bcc0c97..878b93b14 100644 --- a/apps/server/src/persistence/Services/ProjectionThreads.ts +++ b/apps/server/src/persistence/Services/ProjectionThreads.ts @@ -257,6 +257,12 @@ export const GetProjectionThreadInput = Schema.Struct({ }); export type GetProjectionThreadInput = typeof GetProjectionThreadInput.Type; +export const TouchProjectionThreadUpdatedAtInput = Schema.Struct({ + threadId: ThreadId, + updatedAt: IsoDateTime, +}); +export type TouchProjectionThreadUpdatedAtInput = typeof TouchProjectionThreadUpdatedAtInput.Type; + export const DeleteProjectionThreadInput = Schema.Struct({ threadId: ThreadId, }); @@ -289,6 +295,15 @@ export interface ProjectionThreadRepositoryShape { */ readonly upsert: (thread: ProjectionThread) => Effect.Effect; + /** + * Update only `updated_at` for an existing projected thread row. + * + * Returns `true` when a row was updated, `false` when no row matched. + */ + readonly touchUpdatedAt: ( + input: TouchProjectionThreadUpdatedAtInput, + ) => Effect.Effect; + /** * Read a projected thread row by id. */ diff --git a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts index d0660936b..1effceb20 100644 --- a/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts +++ b/apps/server/src/project/Layers/ProjectSetupScriptRunner.test.ts @@ -52,6 +52,9 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) => getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.die("unused"), }); diff --git a/apps/server/src/projectSetup/ProjectSetupSource.ts b/apps/server/src/projectSetup/ProjectSetupSource.ts index 53ae7f807..a57994c8b 100644 --- a/apps/server/src/projectSetup/ProjectSetupSource.ts +++ b/apps/server/src/projectSetup/ProjectSetupSource.ts @@ -90,13 +90,11 @@ export const makeProjectSetupSource = Effect.gen(function* () { /** The project, its repository root and its place there. */ const where = (projectId: ProjectId) => Effect.gen(function* () { - const model = yield* snapshots - .getCommandReadModel() + const found = yield* snapshots + .getProjectShellById(projectId) .pipe(Effect.mapError(() => failure("This computer's projects couldn't be read."))); - const project = model.projects.find( - (entry) => entry.id === projectId && entry.deletedAt === null, - ); - if (project === undefined) return yield* failure("That project isn't on this computer."); + if (Option.isNone(found)) return yield* failure("That project isn't on this computer."); + const project = found.value; if (project.kind === "general-chat") { return yield* failure("General chats don't belong to a project to copy."); } diff --git a/apps/server/src/projectSetup/ProjectSetups.test.ts b/apps/server/src/projectSetup/ProjectSetups.test.ts index ca5c7a94c..3089f9f10 100644 --- a/apps/server/src/projectSetup/ProjectSetups.test.ts +++ b/apps/server/src/projectSetup/ProjectSetups.test.ts @@ -17,6 +17,7 @@ import { normalizeGitRemoteUrl } from "@threadlines/shared/git"; import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; import * as Layer from "effect/Layer"; import * as Stream from "effect/Stream"; @@ -112,20 +113,18 @@ function testLayer( }), }), Layer.mock(ProjectionSnapshotQuery)({ - getCommandReadModel: () => - Effect.succeed({ - threads: [], - projects: [ - { - id: PROJECT_A, - kind: "workspace", - title: "App", - workspaceRoot: repos.a, - scripts: SCRIPTS, - deletedAt: null, - }, - ], - } as never), + getProjectShellById: (projectId) => + Effect.succeed( + projectId === PROJECT_A + ? Option.some({ + id: PROJECT_A, + kind: "workspace", + title: "App", + workspaceRoot: repos.a, + scripts: SCRIPTS, + } as never) + : Option.none(), + ), getProjectCatalog: () => Effect.succeed({ snapshotSequence: 0, diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 294299256..d4786b7c1 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -3890,7 +3890,11 @@ function exitPlanCaptureKey(input: { } function tryParseJsonRecord(value: string): Record | undefined { - const result = decodeUnknownJsonStringExit(value); + const trimmed = value.trim(); + if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) { + return undefined; + } + const result = decodeUnknownJsonStringExit(trimmed); if (!Exit.isSuccess(result)) { return undefined; } @@ -5198,11 +5202,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( tool: ToolInFlight, message: SDKMessage, ) { + const previousEmit = tool.partialStatsEmit; + const nowMs = DateTime.toEpochMillis(yield* DateTime.now); + if (previousEmit && nowMs - previousEmit.atMs < PARTIAL_FILE_CHANGE_EMIT_INTERVAL_MS) { + return; + } const estimate = estimatePartialFileChangeStat(tool.toolName, tool.partialInputJson); if (!estimate) { return; } - const previousEmit = tool.partialStatsEmit; if ( previousEmit && previousEmit.additions === estimate.stat.additions && @@ -5210,10 +5218,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( ) { return; } - const nowMs = DateTime.toEpochMillis(yield* DateTime.now); - if (previousEmit && nowMs - previousEmit.atMs < PARTIAL_FILE_CHANGE_EMIT_INTERVAL_MS) { - return; - } const detail = summarizeToolRequest(tool.toolName, estimate.input, { cwd: context.session.cwd }) || diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index e7d2c457c..2bfbe19f5 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -2572,6 +2572,58 @@ routing.layer("ProviderServiceLive routing", (it) => { }), ); + it.effect( + "listSessions only reads bindings for active sessions and skips directory when idle", + () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const directory = yield* ProviderSessionDirectory; + + const staleThreadId = asThreadId("thread-list-sessions-inactive-historical"); + const activeThreadId = asThreadId("thread-list-sessions-active"); + yield* directory.upsert({ + threadId: staleThreadId, + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + runtimeMode: "full-access", + }); + + yield* routing.codex.stopAll(); + yield* routing.claude.stopAll(); + + const listThreadIdsSpy = vi.spyOn(directory, "listThreadIds"); + const getBindingSpy = vi.spyOn(directory, "getBinding"); + try { + const emptySessions = yield* provider.listSessions(); + assert.deepEqual(emptySessions, []); + assert.equal(listThreadIdsSpy.mock.calls.length, 0); + assert.equal(getBindingSpy.mock.calls.length, 0); + + yield* provider.startSession(activeThreadId, { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + threadId: activeThreadId, + cwd: "/tmp/project-list-sessions-active", + runtimeMode: "full-access", + }); + + listThreadIdsSpy.mockClear(); + getBindingSpy.mockClear(); + + const activeSessions = yield* provider.listSessions(); + assert.deepEqual( + activeSessions.map((session) => session.threadId), + [activeThreadId], + ); + assert.equal(listThreadIdsSpy.mock.calls.length, 0); + assert.deepEqual(getBindingSpy.mock.calls, [[activeThreadId]]); + } finally { + listThreadIdsSpy.mockRestore(); + getBindingSpy.mockRestore(); + } + }), + ); + it.effect("recovers stale sessions for sendTurn using persisted cwd", () => Effect.gen(function* () { const provider = yield* ProviderService; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 38b972462..82740c5dc 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -2929,18 +2929,19 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ), ); const activeSessions = sessionsByProvider.flatMap((sessions) => sessions); - const persistedBindings = yield* directory.listThreadIds().pipe( - Effect.flatMap((threadIds) => - Effect.forEach( - threadIds, - (threadId) => - directory - .getBinding(threadId) - .pipe(Effect.orElseSucceed(() => Option.none())), - { concurrency: "unbounded" }, - ), - ), - Effect.orElseSucceed(() => [] as Array>), + if (activeSessions.length === 0) { + return []; + } + const activeThreadIds = Array.from( + new Set(activeSessions.map((session) => session.threadId)), + ); + const persistedBindings = yield* Effect.forEach( + activeThreadIds, + (threadId) => + directory + .getBinding(threadId) + .pipe(Effect.orElseSucceed(() => Option.none())), + { concurrency: "unbounded" }, ); const bindingsByThreadId = new Map(); for (const bindingOption of persistedBindings) { diff --git a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts index cf5891845..587baed87 100644 --- a/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts +++ b/apps/server/src/provider/Layers/ProviderSessionReaper.test.ts @@ -335,6 +335,9 @@ describe("ProviderSessionReaper", () => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.die("unused"), }), ), diff --git a/apps/server/src/provider/Layers/claudePartialToolInput.test.ts b/apps/server/src/provider/Layers/claudePartialToolInput.test.ts index bfacb3892..1e3636be2 100644 --- a/apps/server/src/provider/Layers/claudePartialToolInput.test.ts +++ b/apps/server/src/provider/Layers/claudePartialToolInput.test.ts @@ -61,4 +61,33 @@ describe("estimatePartialFileChangeStat", () => { expect(estimate?.stat.additions).toBe(1); expect(estimate?.stat.deletions).toBe(0); }); + + it("handles dangling escapes and many escaped newlines cleanly", () => { + const lines = Array.from({ length: 50 }, (_, index) => `const x${index} = "v${index}";`); + const escaped = lines.map((line) => line.replaceAll('"', '\\"')).join("\\n"); + const buffer = `{"file_path":"/tmp/many.ts","content":"${escaped}\\`; + const estimate = estimatePartialFileChangeStat("Write", buffer); + expect(estimate?.stat).toEqual({ + path: "/tmp/many.ts", + kind: "update", + additions: 50, + deletions: 0, + }); + }); + + it("handles large escape-free MultiEdit inputs in linear time", () => { + const count = 4_000; + const edits = Array.from( + { length: count }, + (_, index) => `{"old_string":"old_${index}","new_string":"new_${index}"}`, + ).join(","); + const buffer = `{"file_path":"/tmp/big.ts","edits":[${edits}`; + const estimate = estimatePartialFileChangeStat("MultiEdit", buffer); + expect(estimate?.stat).toEqual({ + path: "/tmp/big.ts", + kind: "update", + additions: count, + deletions: count, + }); + }); }); diff --git a/apps/server/src/provider/Layers/claudePartialToolInput.ts b/apps/server/src/provider/Layers/claudePartialToolInput.ts index 2fc18ae7c..2448ee93c 100644 --- a/apps/server/src/provider/Layers/claudePartialToolInput.ts +++ b/apps/server/src/provider/Layers/claudePartialToolInput.ts @@ -72,55 +72,79 @@ function collectJsonStringValues( const valuesByKey = new Map(); let currentKey: string | undefined; let index = 0; + // Track the next backslash across the whole buffer so escape-free strings + // (e.g. large MultiEdit payloads) never rescan the remaining suffix per token. + let nextSlash = buffer.indexOf("\\", 0); while (index < buffer.length) { - if (buffer[index] !== '"') { - index += 1; - continue; + const openQuote = buffer.indexOf('"', index); + if (openQuote === -1) { + break; } - index += 1; + index = openQuote + 1; let text = ""; + let chunkStart = index; let terminated = false; + let nextQuote = buffer.indexOf('"', index); while (index < buffer.length) { - const char = buffer[index]!; - if (char === '"') { + if (nextQuote !== -1 && nextQuote < index) { + nextQuote = buffer.indexOf('"', index); + } + if (nextSlash !== -1 && nextSlash < index) { + nextSlash = buffer.indexOf("\\", index); + } + if (nextQuote === -1 && nextSlash === -1) { + if (chunkStart < buffer.length) { + text += buffer.slice(chunkStart); + } + index = buffer.length; + break; + } + if (nextQuote !== -1 && (nextSlash === -1 || nextQuote < nextSlash)) { + if (nextQuote > chunkStart) { + text += buffer.slice(chunkStart, nextQuote); + } terminated = true; - index += 1; + index = nextQuote + 1; break; } - if (char === "\\") { - const escape = buffer[index + 1]; - if (escape === undefined) { - // Dangling escape at the buffer end: the pair completes next delta. + if (nextSlash > chunkStart) { + text += buffer.slice(chunkStart, nextSlash); + } + const escape = buffer[nextSlash + 1]; + if (escape === undefined) { + // Dangling escape at the buffer end: the pair completes next delta. + index = buffer.length; + break; + } + if (escape === "u") { + const hex = buffer.slice(nextSlash + 2, nextSlash + 6); + if (!/^[0-9a-fA-F]{4}$/u.test(hex)) { index = buffer.length; break; } - if (escape === "u") { - const hex = buffer.slice(index + 2, index + 6); - if (!/^[0-9a-fA-F]{4}$/u.test(hex)) { - index = buffer.length; - break; - } - text += String.fromCharCode(Number.parseInt(hex, 16)); - index += 6; - continue; - } - text += JSON_ESCAPE_MAP[escape] ?? escape; - index += 2; + text += String.fromCharCode(Number.parseInt(hex, 16)); + index = nextSlash + 6; + chunkStart = index; continue; } - text += char; - index += 1; + text += JSON_ESCAPE_MAP[escape] ?? escape; + index = nextSlash + 2; + chunkStart = index; } let isKey = false; if (terminated) { let lookahead = index; - while (lookahead < buffer.length && /\s/u.test(buffer[lookahead]!)) { + while (lookahead < buffer.length) { + const code = buffer.charCodeAt(lookahead); + if (code !== 32 && code !== 9 && code !== 10 && code !== 13) { + break; + } lookahead += 1; } - isKey = buffer[lookahead] === ":"; + isKey = buffer.charCodeAt(lookahead) === 58; } if (isKey) { diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts index 598191a10..debc646ce 100644 --- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts +++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts @@ -64,6 +64,9 @@ function fakeSnapshotQuery(thread: OrchestrationThread | null): ProjectionSnapsh getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(thread === null ? Option.none() : Option.some(thread)), }; @@ -96,6 +99,9 @@ function failingSnapshotQuery(): ProjectionSnapshotQueryShape { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.fail( new PersistenceSqlError({ diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 361b150f6..5b4fc4811 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -1101,6 +1101,9 @@ const buildAppUnderTest = (options?: { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }), getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()), @@ -4659,6 +4662,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.sync(() => { threadDetailReads += 1; diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 6290b5770..7529bbd6d 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -123,6 +123,9 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), Effect.provideService(AnalyticsService, { @@ -176,6 +179,9 @@ it.effect("recordStartupHeartbeat includes feature adoption counts and flags", ( getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.succeed(Option.none()), }), Effect.provideService(AnalyticsService, { @@ -283,6 +289,9 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.die("unused"), }), Effect.provideService(OrchestrationEngineService, { @@ -341,6 +350,9 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when getTurnActivities: () => Effect.succeed([]), getThreadMessage: () => Effect.succeed(Option.none()), hasAssistantMessageForTurn: () => Effect.succeed(false), + getThreadIngestionContext: () => Effect.succeed(Option.none()), + listThreadsWithMove: () => Effect.succeed([]), + isThreadWorkspacePathInUse: () => Effect.succeed(false), getThreadDetailById: () => Effect.die("unused"), }), Effect.provideService(OrchestrationEngineService, { diff --git a/packages/shared/src/subagentProjection.test.ts b/packages/shared/src/subagentProjection.test.ts index ff91b9a5f..01cd8544c 100644 --- a/packages/shared/src/subagentProjection.test.ts +++ b/packages/shared/src/subagentProjection.test.ts @@ -6,7 +6,11 @@ import { type OrchestrationThreadActivity, } from "@threadlines/contracts"; -import { keepKnownSubagentProviders, projectSubagentActivity } from "./subagentProjection.ts"; +import { + activityMayAffectSubagents, + keepKnownSubagentProviders, + projectSubagentActivity, +} from "./subagentProjection.ts"; const TURN_ID = TurnId.make("11111111-1111-4111-8111-111111111111"); const RESUME_TURN_ID = TurnId.make("22222222-2222-4222-8222-222222222222"); @@ -948,3 +952,23 @@ it("keeps result and live event positions through metadata updates", () => { isBackgrounded: true, }); }); + +it("matches every activity kind or payload that can change the subagent roster", () => { + expect(activityMayAffectSubagents({ kind: "task.started", payload: {} })).toBe(true); + expect(activityMayAffectSubagents({ kind: "task.progress", payload: {} })).toBe(true); + expect(activityMayAffectSubagents({ kind: "task.completed", payload: {} })).toBe(true); + expect(activityMayAffectSubagents({ kind: "subagent.metadata", payload: {} })).toBe(true); + expect( + activityMayAffectSubagents({ + kind: "tool.updated", + payload: { itemType: "collab_agent_tool_call" }, + }), + ).toBe(true); + expect( + activityMayAffectSubagents({ + kind: "tool.updated", + payload: { itemType: "command_execution" }, + }), + ).toBe(false); + expect(activityMayAffectSubagents({ kind: "reasoning.delta", payload: null })).toBe(false); +}); diff --git a/packages/shared/src/subagentProjection.ts b/packages/shared/src/subagentProjection.ts index 7679248d9..bf4795a09 100644 --- a/packages/shared/src/subagentProjection.ts +++ b/packages/shared/src/subagentProjection.ts @@ -514,6 +514,22 @@ function linkTaskTranscript( return next; } +/** Whether an activity can change a thread's subagent roster. */ +export function activityMayAffectSubagents( + activity: Pick, +): boolean { + if ( + activity.kind === "task.started" || + activity.kind === "task.progress" || + activity.kind === "task.completed" || + activity.kind === "subagent.metadata" + ) { + return true; + } + const payload = record(activity.payload); + return text(payload?.itemType) === "collab_agent_tool_call"; +} + /** Fold one timeline activity into the uncapped durable child-agent roster. */ export function projectSubagentActivity( current: ReadonlyArray, From e6d177125b2bbb8ac00d7e3c32c8e763aa2aee8d Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:16:03 -0500 Subject: [PATCH 2/4] perf(web,desktop): cut rendering, state sync, startup, and cdp overhead Streaming turns and composer typing triggered redundant markdown parses, full-thread UI syncs, duplicated inbox derivations, and broad store re-renders in the web client, while the desktop app serialized shell probing ahead of startup, rasterized all 38 macOS tray icons upfront, and kept preview browser CDP buffers and accessibility active. Stabilize markdown link-kind state, cache per-block file-path scans, narrow backdrop observers on active chat threads, deduplicate thread shells structurally on modelSelection, switch thread upserts to single-thread UI sync, share one inbox derivation with narrower component selectors, overlap desktop shell probing with startup, rasterize macOS tray frames lazily on first use, and disable unused preview CDP response buffering and eager accessibility tracking. --- apps/desktop/src/app/DesktopApp.ts | 133 ++++---- apps/desktop/src/preview/PreviewAutomation.ts | 133 ++++++-- .../desktop/src/window/DesktopStatusGlyphs.ts | 32 +- .../src/window/DesktopStatusIndicator.test.ts | 11 +- .../src/window/DesktopStatusIndicator.ts | 109 +++++-- apps/web/src/components/BranchToolbar.tsx | 7 +- apps/web/src/components/ChatMarkdown.tsx | 122 +++++-- apps/web/src/components/DiffPanel.tsx | 7 +- .../components/GitActionsControl.browser.tsx | 1 + apps/web/src/components/GitActionsControl.tsx | 4 +- apps/web/src/components/Sidebar.logic.ts | 130 ++++---- .../source-control/SourceControlPanel.tsx | 26 +- .../runtime/service.savedEnvironments.test.ts | 2 + apps/web/src/environments/runtime/service.ts | 25 +- apps/web/src/hooks/useInboxThreads.ts | 98 ++++-- .../web/src/hooks/useMarkdownFileLinkKinds.ts | 75 ++++- apps/web/src/hooks/useTurnDiffSummaries.ts | 2 +- apps/web/src/lib/chatMarkdownDocument.test.ts | 48 +++ apps/web/src/lib/chatMarkdownDocument.ts | 203 ++++++++++-- apps/web/src/lib/providerReview.ts | 13 +- apps/web/src/lib/threadInboxSync.ts | 10 +- apps/web/src/routes/__root.tsx | 96 +++--- .../routes/_chat.$environmentId.$threadId.tsx | 16 +- apps/web/src/store.test.ts | 77 +++++ apps/web/src/store.ts | 93 +++++- apps/web/src/storeSelectors.ts | 297 +++++++++++++++++- apps/web/src/theme/ThemeBackdropLayer.tsx | 81 +++-- apps/web/src/threadDerivation.ts | 14 +- apps/web/src/uiStateStore.test.ts | 87 +++++ apps/web/src/uiStateStore.ts | 69 +++- 30 files changed, 1627 insertions(+), 394 deletions(-) diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.ts index 6d3d0ceb3..7c30d861a 100644 --- a/apps/desktop/src/app/DesktopApp.ts +++ b/apps/desktop/src/app/DesktopApp.ts @@ -3,6 +3,7 @@ import * as Data from "effect/Data"; import * as Duration from "effect/Duration"; import { randomUUIDv4 } from "@threadlines/shared/uuid"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; @@ -110,68 +111,78 @@ const fatalStartupCause = (stage: string, cause: Cause.Cause) => * the menus, tray, file protocol, updater and IPC handlers can be built while * it boots. The window waits for those (see allowMainWindowOpen), not for this. */ -const startBackend = Effect.gen(function* () { - const backendManager = yield* DesktopBackendManager.DesktopBackendManager; - const state = yield* DesktopState.DesktopState; - const environment = yield* DesktopEnvironment.DesktopEnvironment; - const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; - const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; - yield* logBootstrapInfo("bootstrap start"); +const startBackend = (shellEnvironmentFiber: Fiber.Fiber) => + Effect.gen(function* () { + const backendManager = yield* DesktopBackendManager.DesktopBackendManager; + const shutdown = yield* DesktopLifecycle.DesktopShutdown; + const state = yield* DesktopState.DesktopState; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; + const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; + yield* logBootstrapInfo("bootstrap start"); - if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) { - return yield* new DesktopDevelopmentBackendPortRequiredError(); - } + if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) { + return yield* new DesktopDevelopmentBackendPortRequiredError(); + } - const settings = yield* desktopSettings.get; - const probeHosts = desktopBackendPortProbeHosts(settings.serverExposureMode); - const backendPortSelection = yield* resolveDesktopBackendPort({ - configuredPort: environment.configuredBackendPort, - probeHosts, - }).pipe( - Effect.timeoutOrElse({ - duration: BACKEND_PORT_DISCOVERY_TIMEOUT, - orElse: () => new DesktopBackendPortDiscoveryTimeoutError(), - }), - ); - const backendPort = backendPortSelection.port; - yield* logBootstrapInfo( - backendPortSelection.selectedByScan - ? "selected backend port via sequential scan" - : "using configured backend port", - { - port: backendPort, - ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}), - }, - ); + const settings = yield* desktopSettings.get; + const probeHosts = desktopBackendPortProbeHosts(settings.serverExposureMode); + const backendPortSelection = yield* resolveDesktopBackendPort({ + configuredPort: environment.configuredBackendPort, + probeHosts, + }).pipe( + Effect.timeoutOrElse({ + duration: BACKEND_PORT_DISCOVERY_TIMEOUT, + orElse: () => new DesktopBackendPortDiscoveryTimeoutError(), + }), + ); + const backendPort = backendPortSelection.port; + yield* logBootstrapInfo( + backendPortSelection.selectedByScan + ? "selected backend port via sequential scan" + : "using configured backend port", + { + port: backendPort, + ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}), + }, + ); - if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) { - yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", { - mode: settings.serverExposureMode, + if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) { + yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", { + mode: settings.serverExposureMode, + }); + } + const serverExposureState = yield* serverExposure.configureFromSettings({ + port: backendPort, + selectedByScan: backendPortSelection.selectedByScan, }); - } - const serverExposureState = yield* serverExposure.configureFromSettings({ - port: backendPort, - selectedByScan: backendPortSelection.selectedByScan, - }); - const backendConfig = yield* serverExposure.backendConfig; - yield* logBootstrapInfo("bootstrap resolved backend endpoint", { - baseUrl: backendConfig.httpBaseUrl.href, - }); - if (serverExposureState.endpointUrl) { - yield* logBootstrapInfo("bootstrap enabled network access", { - endpointUrl: serverExposureState.endpointUrl, + const backendConfig = yield* serverExposure.backendConfig; + yield* logBootstrapInfo("bootstrap resolved backend endpoint", { + baseUrl: backendConfig.httpBaseUrl.href, }); - } else if (settings.serverExposureMode === "network-accessible") { - yield* logBootstrapWarning( - "bootstrap fell back to local-only because no advertised network host was available", + if (serverExposureState.endpointUrl) { + yield* logBootstrapInfo("bootstrap enabled network access", { + endpointUrl: serverExposureState.endpointUrl, + }); + } else if (settings.serverExposureMode === "network-accessible") { + yield* logBootstrapWarning( + "bootstrap fell back to local-only because no advertised network host was available", + ); + } + + // Wait for the login-shell environment probe before spawning the backend + // (and before updates.configure below) so both see the recovered PATH. + // Race against shutdown so quitting while a slow shell probes exits promptly. + yield* Effect.raceFirst( + Fiber.join(shellEnvironmentFiber), + shutdown.awaitRequest.pipe(Effect.andThen(Fiber.interrupt(shellEnvironmentFiber))), ); - } - if (!(yield* Ref.get(state.quitting))) { - yield* backendManager.start; - yield* logBootstrapInfo("bootstrap backend start requested"); - } -}).pipe(Effect.withSpan("desktop.bootstrap")); + if (!(yield* Ref.get(state.quitting))) { + yield* backendManager.start; + yield* logBootstrapInfo("bootstrap backend start requested"); + } + }).pipe(Effect.withSpan("desktop.bootstrap")); const startup = Effect.gen(function* () { const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity; @@ -181,6 +192,7 @@ const startup = Effect.gen(function* () { const lifecycle = yield* DesktopLifecycle.DesktopLifecycle; const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings; + const state = yield* DesktopState.DesktopState; const updates = yield* DesktopUpdates.DesktopUpdates; const environment = yield* DesktopEnvironment.DesktopEnvironment; const statusIndicator = yield* DesktopStatusIndicator.DesktopStatusIndicator; @@ -188,7 +200,9 @@ const startup = Effect.gen(function* () { const desktopWindow = yield* DesktopWindow.DesktopWindow; const threadLinks = yield* DesktopThreadLinks.DesktopThreadLinks; - yield* shellEnvironment.installIntoProcess; + // Probe the login shell in parallel with Electron initialization and backend + // port discovery; joined in startBackend before spawning the server process. + const shellEnvironmentFiber = yield* Effect.forkChild(shellEnvironment.installIntoProcess); yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir }); yield* desktopSettings.load; @@ -214,7 +228,12 @@ const startup = Effect.gen(function* () { logStartupWarning("browser passkeys could not be enabled", { cause: String(cause) }), ), ); - yield* startBackend.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause))); + yield* startBackend(shellEnvironmentFiber).pipe( + Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)), + ); + if (yield* Ref.get(state.quitting)) { + return; + } yield* applicationMenu.configure; yield* statusIndicator.configure; yield* background.configure; diff --git a/apps/desktop/src/preview/PreviewAutomation.ts b/apps/desktop/src/preview/PreviewAutomation.ts index 6733df649..67add673f 100644 --- a/apps/desktop/src/preview/PreviewAutomation.ts +++ b/apps/desktop/src/preview/PreviewAutomation.ts @@ -128,6 +128,7 @@ const MAX_CONSOLE_ENTRIES = 200; const DRAG_MOVE_STEPS = 10; const MAX_NETWORK_FAILURES = 100; +const MAX_TRACKED_REQUEST_URLS = 1000; /** See `sendCommand`: comfortably inside the broker's twenty second deadline. */ const CDP_COMMAND_TIMEOUT = "15 seconds"; const PAGE_DID_NOT_ANSWER = "the page did not answer in time"; @@ -256,6 +257,8 @@ interface AttachedTab { expectedAgentInputs: Array<{ kind: "mouseDown" | "mouseWheel"; expiresAt: number }>; /** Until when the user's keys are kept out of the page; see `agentKeys`. */ holdUserKeysUntil: number; + /** Reference count of active element-description calls holding `Accessibility.enable` open. */ + accessibilityUsers: number; /** Frame id -> its own CDP session, for frames in other processes; see `routePoint`. */ frameSessions: Map; /** @@ -1699,34 +1702,71 @@ export const make = Effect.gen(function* PreviewAutomationMake() { * all. Must run before the overlay is torn down, since the teardown is what * drops the handles. */ + const withAccessibilityEnabled = ( + contents: WebContents, + effect: Effect.Effect, + ): Effect.Effect => + Effect.acquireUseRelease( + Effect.gen(function* () { + const tab = attached.get(contents.id); + if (tab === undefined) { + return null; + } + tab.accessibilityUsers += 1; + // Idempotent in CDP: running on every acquire avoids racing a second + // caller ahead of an in-flight enable, while refcounting delays disable. + yield* sendCommand(contents, "Accessibility.enable").pipe(Effect.ignore); + return tab; + }), + () => effect, + (tab) => + Effect.gen(function* () { + if (tab === null) { + return; + } + tab.accessibilityUsers = Math.max(0, tab.accessibilityUsers - 1); + if (tab.accessibilityUsers === 0 && attached.get(contents.id) === tab) { + yield* sendCommand(contents, "Accessibility.disable").pipe(Effect.ignore); + } + }), + ); + const describeStashed = Effect.fn("PreviewAutomation.describeStashed")(function* ( contents: WebContents, stash: string, count: number, ) { - const described: DesktopPreviewPickedElement[] = []; - for (let index = 0; index < count; index += 1) { - const handle = (yield* sendCommand(contents, "Runtime.evaluate", { - expression: `window[${JSON.stringify(stash)}][${index}]`, - })) as { result?: { objectId?: string } }; - const objectId = handle.result?.objectId; - if (objectId === undefined) { - continue; - } - const node = (yield* sendCommand(contents, "DOM.describeNode", { objectId })) as { - node?: { backendNodeId?: number }; - }; - yield* sendCommand(contents, "Runtime.releaseObject", { objectId }).pipe(Effect.ignore); - const backendNodeId = node.node?.backendNodeId; - if (backendNodeId === undefined) { - continue; - } - const element = yield* describePickedNode(sendCommand)(contents, backendNodeId); - if (element !== null) { - described.push(element); - } + if (count <= 0) { + return []; } - return described; + return yield* withAccessibilityEnabled( + contents, + Effect.gen(function* () { + const described: DesktopPreviewPickedElement[] = []; + for (let index = 0; index < count; index += 1) { + const handle = (yield* sendCommand(contents, "Runtime.evaluate", { + expression: `window[${JSON.stringify(stash)}][${index}]`, + })) as { result?: { objectId?: string } }; + const objectId = handle.result?.objectId; + if (objectId === undefined) { + continue; + } + const node = (yield* sendCommand(contents, "DOM.describeNode", { objectId })) as { + node?: { backendNodeId?: number }; + }; + yield* sendCommand(contents, "Runtime.releaseObject", { objectId }).pipe(Effect.ignore); + const backendNodeId = node.node?.backendNodeId; + if (backendNodeId === undefined) { + continue; + } + const element = yield* describePickedNode(sendCommand)(contents, backendNodeId); + if (element !== null) { + described.push(element); + } + } + return described; + }), + ); }); const buildStatus = (webContentsId: number, contents: WebContents): DesktopPreviewStatus => { @@ -1779,6 +1819,7 @@ export const make = Effect.gen(function* PreviewAutomationMake() { controlEpoch: 0, expectedAgentInputs: [], holdUserKeysUntil: 0, + accessibilityUsers: 0, frameSessions: new Map(), sessionOwners: new Map(), framesByOrdinal: new Map(), @@ -1892,7 +1933,21 @@ export const make = Effect.gen(function* PreviewAutomationMake() { const requestId = String(params.requestId ?? ""); const request = params.request as { url?: string } | undefined; if (requestId !== "" && request?.url !== undefined) { + tab.requestUrls.delete(requestId); tab.requestUrls.set(requestId, request.url); + if (tab.requestUrls.size > MAX_TRACKED_REQUEST_URLS) { + const oldestKey = tab.requestUrls.keys().next().value; + if (oldestKey !== undefined) { + tab.requestUrls.delete(oldestKey); + } + } + } + return; + } + if (method === "Network.loadingFinished") { + const requestId = String(params.requestId ?? ""); + if (requestId !== "") { + tab.requestUrls.delete(requestId); } return; } @@ -1953,11 +2008,7 @@ export const make = Effect.gen(function* PreviewAutomationMake() { }; contents.debugger.on("message", onMessage); - const onDestroyed = () => { - frameNumbering.delete(webContentsId); - attached.delete(webContentsId); - lifecycles.delete(webContentsId); - }; + trackDestruction(webContentsId, contents); // Electron tells us when the attachment goes -- DevTools opening, the guest // crashing, someone calling detach. Dropping the record here is what lets // the next command notice and rebuild rather than fail. @@ -1965,13 +2016,11 @@ export const make = Effect.gen(function* PreviewAutomationMake() { attached.get(webContentsId)?.dispose(); attached.delete(webContentsId); }; - contents.once("destroyed", onDestroyed); contents.debugger.on("detach", onDetach); tab.dispose = () => { siteIdentity.stop(); contents.debugger.off("message", onMessage); contents.debugger.off("detach", onDetach); - contents.off("destroyed", onDestroyed); contents.off("before-input-event", onBeforeInput); contents.off("before-mouse-event", onBeforeMouse); contents.off("console-message", onConsole); @@ -1985,9 +2034,14 @@ export const make = Effect.gen(function* PreviewAutomationMake() { Effect.ignore, ); - for (const method of ["Page.enable", "Network.enable", "Log.enable", "Accessibility.enable"]) { - yield* sendCommand(contents, method); - } + yield* sendCommand(contents, "Page.enable"); + // We only record request URLs and failures and never call + // `Network.getResponseBody`, so tell Chromium not to buffer response bodies. + yield* sendCommand(contents, "Network.enable", { + maxTotalBufferSize: 0, + maxResourceBufferSize: 0, + }); + yield* sendCommand(contents, "Log.enable"); // The guest believes it is focused even while the user's caret is // elsewhere in the embedding window. Agent input pulls focus onto the // and the web client hands it straight back (browserFocusGuard); @@ -2045,6 +2099,21 @@ export const make = Effect.gen(function* PreviewAutomationMake() { /** Names each frame-owner lookup's object group apart. */ let frameOwnerLookups = 0; + const trackedDestruction = new WeakSet(); + // Registered once per guest (outside `tab.dispose`) so detaching the debugger + // (e.g. opening DevTools) never drops cleanup for `frameNumbering` and `lifecycles`. + const trackDestruction = (webContentsId: number, contents: WebContents) => { + if (trackedDestruction.has(contents)) return; + trackedDestruction.add(contents); + contents.once("destroyed", () => { + pendingPicks.get(webContentsId)?.supersede(); + drawWaiters.get(webContentsId)?.(); + frameNumbering.delete(webContentsId); + attached.delete(webContentsId); + lifecycles.delete(webContentsId); + }); + }; + const frameNumbering = new Map< number, { readonly ordinals: Map; next: number } diff --git a/apps/desktop/src/window/DesktopStatusGlyphs.ts b/apps/desktop/src/window/DesktopStatusGlyphs.ts index 48ea9b251..facac9bee 100644 --- a/apps/desktop/src/window/DesktopStatusGlyphs.ts +++ b/apps/desktop/src/window/DesktopStatusGlyphs.ts @@ -708,17 +708,35 @@ export function makeMacMenuStateGlyphs(): MacMenuStateGlyphs { return cachedMenuStateGlyphs; } +let cachedIdleGlyph: TrayGlyph | null = null; +let cachedWorkingGlyphs: readonly TrayGlyph[] | null = null; +let cachedCompletedGlyphs: readonly TrayGlyph[] | null = null; let cachedGlyphSet: MacTrayGlyphSet | null = null; +export function makeMacIdleTrayGlyph(): TrayGlyph { + cachedIdleGlyph ??= buildGlyph(idleShapes(), TRAY_RENDER_OPTIONS); + return cachedIdleGlyph; +} + +export function makeMacWorkingTrayGlyphs(): readonly TrayGlyph[] { + cachedWorkingGlyphs ??= Array.from({ length: TRAY_WORKING_FRAME_COUNT }, (_, frameIndex) => + buildGlyph(workingShapes(frameIndex), TRAY_RENDER_OPTIONS), + ); + return cachedWorkingGlyphs; +} + +export function makeMacCompletedTrayGlyphs(): readonly TrayGlyph[] { + cachedCompletedGlyphs ??= COMPLETED_POP_FRAMES.map((frame) => + buildGlyph(completedShapes(frame), TRAY_RENDER_OPTIONS), + ); + return cachedCompletedGlyphs; +} + export function makeMacTrayGlyphSet(): MacTrayGlyphSet { cachedGlyphSet ??= { - idle: buildGlyph(idleShapes(), TRAY_RENDER_OPTIONS), - workingFrames: Array.from({ length: TRAY_WORKING_FRAME_COUNT }, (_, frameIndex) => - buildGlyph(workingShapes(frameIndex), TRAY_RENDER_OPTIONS), - ), - completedFrames: COMPLETED_POP_FRAMES.map((frame) => - buildGlyph(completedShapes(frame), TRAY_RENDER_OPTIONS), - ), + idle: makeMacIdleTrayGlyph(), + workingFrames: makeMacWorkingTrayGlyphs(), + completedFrames: makeMacCompletedTrayGlyphs(), }; return cachedGlyphSet; } diff --git a/apps/desktop/src/window/DesktopStatusIndicator.test.ts b/apps/desktop/src/window/DesktopStatusIndicator.test.ts index b4f150e68..55ac2fbde 100644 --- a/apps/desktop/src/window/DesktopStatusIndicator.test.ts +++ b/apps/desktop/src/window/DesktopStatusIndicator.test.ts @@ -243,11 +243,17 @@ describe("DesktopStatusIndicator", () => { yield* Effect.gen(function* () { const indicator = yield* DesktopStatusIndicator.DesktopStatusIndicator; yield* indicator.configure; + // Startup only rasterizes the idle icon; animation frames and menu icons wait for first use. + assert.lengthOf(trayCalls.createTemplateImages, 1); yield* indicator.setStatus({ status: "working", description: "One chat is working", runningThreadCount: 1, }); + assert.lengthOf( + trayCalls.createTemplateImages, + 1 + DesktopStatusGlyphs.makeMacWorkingTrayGlyphs().length, + ); vi.advanceTimersByTime(DesktopStatusGlyphs.TRAY_WORKING_FRAME_INTERVAL_MS * 4.5); yield* indicator.setStatus({ status: "completed", @@ -268,9 +274,8 @@ describe("DesktopStatusIndicator", () => { }).pipe(Effect.provide(makeTestLayer({ appCalls, trayCalls, window }))); const glyphs = DesktopStatusGlyphs.makeMacTrayGlyphSet(); - // idle + animation frames + the two menu thread-state icons. - const expectedGlyphCount = - 1 + glyphs.workingFrames.length + glyphs.completedFrames.length + 2; + // idle + working + completed frames; menu thread-state icons stay lazy until threads are shown. + const expectedGlyphCount = 1 + glyphs.workingFrames.length + glyphs.completedFrames.length; assert.lengthOf(trayCalls.createTemplateImages, expectedGlyphCount); assert.isTrue( trayCalls.createTemplateImages.every( diff --git a/apps/desktop/src/window/DesktopStatusIndicator.ts b/apps/desktop/src/window/DesktopStatusIndicator.ts index 6502150bf..4fd857579 100644 --- a/apps/desktop/src/window/DesktopStatusIndicator.ts +++ b/apps/desktop/src/window/DesktopStatusIndicator.ts @@ -44,12 +44,16 @@ export class DesktopStatusIndicator extends Context.Service< type DesktopStatusIndicatorRuntimeServices = DesktopWindow.DesktopWindow | ElectronApp.ElectronApp; +interface MacTrayMenuIcons { + readonly running: Electron.NativeImage; + readonly completed: Electron.NativeImage; +} + interface MacTrayImages { readonly idle: Electron.NativeImage; - readonly workingFrames: readonly Electron.NativeImage[]; - readonly completedFrames: readonly Electron.NativeImage[]; - readonly menuRunning: Electron.NativeImage; - readonly menuCompleted: Electron.NativeImage; + workingFrames: readonly Electron.NativeImage[] | null; + completedFrames: readonly Electron.NativeImage[] | null; + menuIcons: MacTrayMenuIcons | null; } const { logWarning: logStatusWarning, logError: logStatusError } = @@ -245,33 +249,56 @@ const make = Effect.gen(function* () { }); const createMacTrayImages = Effect.gen(function* () { - const glyphs = DesktopStatusGlyphs.makeMacTrayGlyphSet(); - const menuGlyphs = DesktopStatusGlyphs.makeMacMenuStateGlyphs(); - const idle = yield* createTrayImageFrames([glyphs.idle]); - const workingFrames = yield* createTrayImageFrames(glyphs.workingFrames); - const completedFrames = yield* createTrayImageFrames(glyphs.completedFrames); - const menuIcons = yield* createTrayImageFrames([menuGlyphs.running, menuGlyphs.completed]); - if ( - Option.isNone(idle) || - Option.isNone(workingFrames) || - Option.isNone(completedFrames) || - Option.isNone(menuIcons) || - idle.value[0] === undefined || - menuIcons.value[0] === undefined || - menuIcons.value[1] === undefined - ) { + const idle = yield* createTrayImageFrames([DesktopStatusGlyphs.makeMacIdleTrayGlyph()]); + if (Option.isNone(idle) || idle.value[0] === undefined) { return Option.none(); } - return Option.some({ + return Option.some({ idle: idle.value[0], - workingFrames: workingFrames.value, - completedFrames: completedFrames.value, - menuRunning: menuIcons.value[0], - menuCompleted: menuIcons.value[1], + workingFrames: null, + completedFrames: null, + menuIcons: null, }); }); + const ensureMacWorkingFrames = Effect.gen(function* () { + const images = macTrayImages; + if (images === null || images.workingFrames !== null) { + return; + } + const frames = yield* createTrayImageFrames(DesktopStatusGlyphs.makeMacWorkingTrayGlyphs()); + if (Option.isSome(frames)) { + images.workingFrames = frames.value; + } + }); + + const ensureMacCompletedFrames = Effect.gen(function* () { + const images = macTrayImages; + if (images === null || images.completedFrames !== null) { + return; + } + const frames = yield* createTrayImageFrames(DesktopStatusGlyphs.makeMacCompletedTrayGlyphs()); + if (Option.isSome(frames)) { + images.completedFrames = frames.value; + } + }); + + const ensureMacMenuIcons = Effect.gen(function* () { + const images = macTrayImages; + if (images === null || images.menuIcons !== null) { + return; + } + const menuGlyphs = DesktopStatusGlyphs.makeMacMenuStateGlyphs(); + const icons = yield* createTrayImageFrames([menuGlyphs.running, menuGlyphs.completed]); + if (Option.isSome(icons) && icons.value[0] !== undefined && icons.value[1] !== undefined) { + images.menuIcons = { + running: icons.value[0], + completed: icons.value[1], + }; + } + }); + const setMacTrayImage = (image: Electron.NativeImage) => { const currentTray = tray; if (currentTray === null) { @@ -339,16 +366,29 @@ const make = Effect.gen(function* () { return; } const previousStatus = macTrayRenderedStatus; - macTrayRenderedStatus = currentStatus.status; switch (currentStatus.status) { case "working": + if (images.workingFrames === null) { + macTrayRenderedStatus = null; + clearMacTrayAnimation(); + setMacTrayImage(images.idle); + return; + } + macTrayRenderedStatus = currentStatus.status; playMacTrayFrames(images.workingFrames, { loop: true, frameMs: DesktopStatusGlyphs.TRAY_WORKING_FRAME_INTERVAL_MS, }); return; case "completed": + if (images.completedFrames === null) { + macTrayRenderedStatus = null; + clearMacTrayAnimation(); + setMacTrayImage(images.idle); + return; + } + macTrayRenderedStatus = currentStatus.status; // The check pops as work finishes. Unread work already waiting (at // launch, or after marking a thread unread) shows it at rest. playMacTrayFrames( @@ -357,6 +397,7 @@ const make = Effect.gen(function* () { ); return; case "idle": + macTrayRenderedStatus = currentStatus.status; clearMacTrayAnimation(); setMacTrayImage(images.idle); return; @@ -372,11 +413,14 @@ const make = Effect.gen(function* () { return []; } + const menuIcons = images.menuIcons; const items: Electron.MenuItemConstructorOptions[] = threads .slice(0, MACOS_TRAY_MENU_THREAD_LIMIT) .map((thread) => ({ label: truncateThreadMenuLabel(thread.title), - icon: thread.state === "completed" ? images.menuCompleted : images.menuRunning, + ...(menuIcons !== null + ? { icon: thread.state === "completed" ? menuIcons.completed : menuIcons.running } + : {}), toolTip: `${thread.title.trim()} — ${describeThreadMenuState(thread)}`, click: () => runTrayEffect( @@ -464,6 +508,19 @@ const make = Effect.gen(function* () { return; } + if (environment.platform === "darwin" && macTrayImages !== null) { + if ((currentStatus.threads?.length ?? 0) > 0) { + yield* ensureMacMenuIcons; + } + if (currentStatus.status !== macTrayRenderedStatus) { + if (currentStatus.status === "working") { + yield* ensureMacWorkingFrames; + } else if (currentStatus.status === "completed") { + yield* ensureMacCompletedFrames; + } + } + } + const menu = yield* electronTray.buildMenu(buildTrayMenuTemplate(currentStatus)); yield* Effect.sync(() => { if (tray === null) { diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index 6c59a7bcd..8b57e4a72 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -19,7 +19,7 @@ import { lendingThreadId } from "../worktreeOrigin"; import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; import { useIsMobile } from "../hooks/useMediaQuery"; import { useStore } from "../store"; -import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; +import { createProjectSelectorByRef, createThreadCheckoutSelectorByRef } from "../storeSelectors"; import { worktreePathLabel } from "../worktreePickup"; import { type EnvMode, @@ -282,7 +282,10 @@ export const BranchToolbar = memo(function BranchToolbar({ () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); - const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]); + const serverThreadSelector = useMemo( + () => createThreadCheckoutSelectorByRef(threadRef), + [threadRef], + ); const serverThread = useStore(serverThreadSelector); const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 6386676d6..cbd5fac15 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -108,13 +108,15 @@ import { CHAT_MARKDOWN_REMARK_PLUGINS, chatMarkdownUrlTransform, GITHUB_HTML_REHYPE_PLUGINS, + indexWrittenFilePathsByBasename, + isFileNameMention, normalizeMarkdownLinkHrefKey, pullRequestLinkLabel, - collectWrittenFilePaths, - isFileNameMention, + repairStreamingMarkdownTail, resolveMarkdownDocumentFileLinks, + scanMarkdownBlockFileLinks, + selectWrittenFilePathsKeyForBareNames, splitMarkdownBlocks, - repairStreamingMarkdownTail, } from "../lib/chatMarkdownDocument"; import { normalizeChatMath } from "../lib/chatMarkdownMath"; import { fencedBlockIsClosed } from "../lib/markdownFences"; @@ -167,21 +169,20 @@ interface ChatMarkdownProps { className?: string | undefined; } -/** One block of a message, with what the whole message tells every block. */ -interface ChatMarkdownBlockProps extends ChatMarkdownProps { +/** One rendered markdown document with the written file paths relevant to it. */ +interface ChatMarkdownDocumentProps extends ChatMarkdownProps { /** Files the whole message names by full path, see {@link collectWrittenFilePaths}. */ writtenFilePaths: readonly string[]; } -/** - * {@link collectWrittenFilePaths} for a whole message, as an array that keeps - * its identity while the paths stay the same: a streaming message rescans on - * every delta, but its settled blocks re-render only when a new path appears. - */ -function useWrittenFilePaths(text: string, cwd: string | undefined): readonly string[] { - // A path never holds a line break: every source of one stops at the line. - const key = useMemo(() => collectWrittenFilePaths(text, cwd).join("\n"), [cwd, text]); - return useMemo(() => (key === "" ? NO_WRITTEN_FILE_PATHS : key.split("\n")), [key]); +/** One block of a message, keyed on a newline-joined written-path string for stable memoization. */ +interface ChatMarkdownBlockProps extends ChatMarkdownProps { + writtenFilePathsKey: string; +} + +interface ChatMarkdownBodyProps extends Omit { + blocks: readonly string[]; + blockWrittenFilePathsKeys: readonly string[]; } const NO_WRITTEN_FILE_PATHS: readonly string[] = []; @@ -1626,7 +1627,7 @@ function ChatMarkdownDocument({ searchHighlightQuery, html, writtenFilePaths, -}: ChatMarkdownBlockProps) { +}: ChatMarkdownDocumentProps) { const { resolvedTheme } = useTheme(); // Null unless both halves of the identity are here: a transcript rendered // outside a thread (a plan preview, a subagent excerpt without context) has @@ -1737,7 +1738,7 @@ const MarkdownBlock = memo(function MarkdownBlock({ skills = EMPTY_MARKDOWN_SKILLS, searchHighlightQuery, html, - writtenFilePaths, + writtenFilePathsKey, }: ChatMarkdownBlockProps) { // Lets React drop intermediate parses when deltas outpace rendering // (older CPUs) instead of parsing every 50ms server flush. A settled block's @@ -1749,6 +1750,11 @@ const MarkdownBlock = memo(function MarkdownBlock({ const withMath = normalizeChatMath(deferredText, { streaming: isStreaming }); return isStreaming ? repairStreamingMarkdownTail(withMath) : withMath; }, [deferredText, isStreaming]); + // A path never holds a line break: every source of one stops at the line. + const writtenFilePaths = useMemo( + () => (writtenFilePathsKey === "" ? NO_WRITTEN_FILE_PATHS : writtenFilePathsKey.split("\n")), + [writtenFilePathsKey], + ); return ( ` around paragraphs), so an HTML-bearing document parses whole. - const blocks = html === "github" ? [text] : splitMarkdownBlocks(text); const tailIndex = blocks.length - 1; /* oxlint-disable react/no-array-index-key -- streaming only appends blocks; index is the stable identity */ return ( @@ -1798,7 +1801,7 @@ function ChatMarkdownBody({ skills={skills} searchHighlightQuery={searchHighlightQuery} html={html} - writtenFilePaths={writtenFilePaths} + writtenFilePathsKey={blockWrittenFilePathsKeys[index] ?? ""} /> ))} @@ -1825,10 +1828,67 @@ function ChatMarkdown({ warmCodeHighlighter(codeThemeName); }, [codeThemeName]); const canRenderVisualizations = environmentId !== undefined && threadId !== undefined; - const segments = canRenderVisualizations - ? parseCodexInlineVisualizations(text, { isStreaming }) - : [{ type: "markdown" as const, key: "markdown:0", text }]; - const writtenFilePaths = useWrittenFilePaths(text, cwd); + const parsedSegments = useMemo(() => { + const rawSegments = canRenderVisualizations + ? parseCodexInlineVisualizations(text, { isStreaming }) + : [{ type: "markdown" as const, key: "markdown:0", text }]; + + const allWrittenPaths = new Set(); + const scannedSegments = rawSegments.map((segment, segmentIndex) => { + if (segment.type === "visualization") { + return segment; + } + // Raw HTML can span what the splitter takes for several blocks (a + // `
` around paragraphs), so an HTML-bearing document parses whole. + const blocks = html === "github" ? [segment.text] : splitMarkdownBlocks(segment.text); + const segmentIsStreaming = isStreaming && segmentIndex === rawSegments.length - 1; + const tailIndex = blocks.length - 1; + const scans = blocks.map((block, blockIndex) => { + const scan = scanMarkdownBlockFileLinks(block, cwd, { + cache: !(segmentIsStreaming && blockIndex === tailIndex), + }); + for (const writtenPath of scan.writtenPaths) { + allWrittenPaths.add(writtenPath); + } + return scan; + }); + return { + type: "markdown" as const, + key: segment.key, + blocks, + scans, + isStreaming: segmentIsStreaming, + }; + }); + + const allWrittenFilePathsKey = + allWrittenPaths.size === 0 ? "" : [...allWrittenPaths].toSorted().join("\n"); + const writtenPathsByBasename = + allWrittenPaths.size === 0 ? null : indexWrittenFilePathsByBasename(allWrittenPaths); + + return scannedSegments.map((segment) => { + if (segment.type === "visualization") { + return segment; + } + const tailIndex = segment.blocks.length - 1; + const blockWrittenFilePathsKeys = segment.scans.map((scan, blockIndex) => { + if (writtenPathsByBasename === null) return ""; + // Tail repair can close an inline-code span that wasn't complete yet; + // the streaming tail already re-renders on every delta, so pass all paths. + if (segment.isStreaming && blockIndex === tailIndex) { + return allWrittenFilePathsKey; + } + return selectWrittenFilePathsKeyForBareNames(scan.bareFileNames, writtenPathsByBasename); + }); + return { + type: "markdown" as const, + key: segment.key, + blocks: segment.blocks, + blockWrittenFilePathsKeys, + isStreaming: segment.isStreaming, + }; + }); + }, [canRenderVisualizations, cwd, html, isStreaming, text]); return (
- {segments.map((segment, index) => { + {parsedSegments.map((segment) => { if (segment.type === "visualization") { return environmentId && threadId ? ( ); })} diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index 90fef3491..61e640832 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -40,7 +40,10 @@ import { buildFileDiffRenderKey, getRenderablePatch } from "../lib/diffRendering import { useCodeThemeName } from "../theme/codeTheme"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; import { useStore } from "../store"; -import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; +import { + createProjectSelectorByRef, + createThreadDiffContextSelectorByRef, +} from "../storeSelectors"; import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes"; import { useSettings, useUpdateSettings } from "../hooks/useSettings"; import { formatShortTimestamp } from "../timestampFormat"; @@ -272,7 +275,7 @@ export default function DiffPanel({ mode = "inline", onClose, embedded = false } const diffOpen = diffSearch.diff === "1"; const activeThreadId = routeThreadRef?.threadId ?? null; const activeThread = useStore( - useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]), + useMemo(() => createThreadDiffContextSelectorByRef(routeThreadRef), [routeThreadRef]), ); const draftThread = useComposerDraftStore((store) => routeThreadRef ? store.getDraftThreadByRef(routeThreadRef) : null, diff --git a/apps/web/src/components/GitActionsControl.browser.tsx b/apps/web/src/components/GitActionsControl.browser.tsx index 54cdc57d5..98baae78d 100644 --- a/apps/web/src/components/GitActionsControl.browser.tsx +++ b/apps/web/src/components/GitActionsControl.browser.tsx @@ -239,6 +239,7 @@ vi.mock("~/store", () => ({ selectBootstrapCompleteForActiveEnvironment: () => true, selectProjectByRef: () => null, selectThreadByRef: () => null, + selectThreadShellByRef: () => null, selectThreadExistsByRef: () => false, selectSidebarThreadSummaryByRef: () => null, selectThreadIdsByProjectRef: () => [], diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 5af97d1eb..201994adb 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -83,7 +83,7 @@ import { useThreadCheckoutSelection } from "~/hooks/useThreadCheckoutSelection"; import { readLocalApi } from "~/localApi"; import { getSourceControlPresentation } from "~/sourceControlPresentation"; import { useStore } from "~/store"; -import { createThreadSelectorByRef } from "~/storeSelectors"; +import { createThreadCheckoutSelectorByRef } from "~/storeSelectors"; import { applyGitActionProgressEvent, createGitActionProgress, @@ -1121,7 +1121,7 @@ export default function GitActionsControl({ [activeThreadRef], ); const activeServerThreadSelector = useMemo( - () => createThreadSelectorByRef(activeThreadRef), + () => createThreadCheckoutSelectorByRef(activeThreadRef), [activeThreadRef], ); const activeServerThread = useStore(activeServerThreadSelector); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 3dc8b73bc..1779cc3bc 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -298,14 +298,68 @@ export function isContextMenuPointerDown(input: { return input.isMac && input.button === 0 && input.ctrlKey; } -function awaitingInputPill(): ThreadStatusPill { - return { - label: "Awaiting Input", - colorClass: "text-amber-600 dark:text-amber-300/90", - dotClass: THREAD_STATUS_DOT_CLASSES.amber, - pulse: false, - }; -} +const PENDING_APPROVAL_PILL: ThreadStatusPill = Object.freeze({ + label: "Pending Approval", + colorClass: "text-amber-600 dark:text-amber-300/90", + dotClass: THREAD_STATUS_DOT_CLASSES.amber, + pulse: false, +}); + +const AWAITING_INPUT_PILL: ThreadStatusPill = Object.freeze({ + label: "Awaiting Input", + colorClass: "text-amber-600 dark:text-amber-300/90", + dotClass: THREAD_STATUS_DOT_CLASSES.amber, + pulse: false, +}); + +const WORKING_PILL: ThreadStatusPill = Object.freeze({ + label: "Working", + colorClass: "text-primary-readable", + dotClass: THREAD_STATUS_DOT_CLASSES.blue, + pulse: true, +}); + +const STARTING_PILL: ThreadStatusPill = Object.freeze({ + label: "Starting", + colorClass: "text-primary-readable", + dotClass: THREAD_STATUS_DOT_CLASSES.blue, + pulse: true, +}); + +const ANSWERING_PILL: ThreadStatusPill = Object.freeze({ + label: "Answering", + colorClass: "text-primary-readable", + dotClass: THREAD_STATUS_DOT_CLASSES.blue, + pulse: true, +}); + +const FAILED_PILL: ThreadStatusPill = Object.freeze({ + label: "Failed", + colorClass: "text-red-600 dark:text-red-400/90", + dotClass: THREAD_STATUS_DOT_CLASSES.red, + pulse: false, +}); + +const PLAN_READY_PILL: ThreadStatusPill = Object.freeze({ + label: "Plan Ready", + colorClass: "text-violet-600 dark:text-violet-300/90", + dotClass: THREAD_STATUS_DOT_CLASSES.violet, + pulse: false, +}); + +const WAITING_PILL: ThreadStatusPill = Object.freeze({ + label: "Waiting", + colorClass: WAITING_STATUS_TONE, + dotClass: THREAD_STATUS_DOT_CLASSES.cyan, + pulse: true, +}); + +const COMPLETED_PILL: ThreadStatusPill = Object.freeze({ + label: "Completed", + colorClass: "text-emerald-600 dark:text-emerald-300/90", + dotClass: THREAD_STATUS_DOT_CLASSES.emerald, + pulse: false, +}); export function resolveThreadStatusPill(input: { thread: ThreadStatusInput; @@ -322,54 +376,34 @@ export function resolveThreadStatusPill(input: { thread.pendingSettingsChange === true || thread.pendingSecretRequest === true ) { - return { - label: "Pending Approval", - colorClass: "text-amber-600 dark:text-amber-300/90", - dotClass: THREAD_STATUS_DOT_CLASSES.amber, - pulse: false, - }; + return PENDING_APPROVAL_PILL; } // A question that pauses the agent needs the user right away. One it asked // in passing (it keeps working) needs them once the work below stops. if (thread.hasBlockingUserInput ?? thread.hasPendingUserInput) { - return awaitingInputPill(); + return AWAITING_INPUT_PILL; } const inFlightStatus = getThreadInFlightStatus(thread); if (inFlightStatus === "working") { - return { - label: "Working", - colorClass: "text-primary-readable", - dotClass: THREAD_STATUS_DOT_CLASSES.blue, - pulse: true, - }; + return WORKING_PILL; } if (inFlightStatus === "starting") { - return { - label: "Starting", - colorClass: "text-primary-readable", - dotClass: THREAD_STATUS_DOT_CLASSES.blue, - pulse: true, - }; + return STARTING_PILL; } // In a room, an agent answering on the side while the others are idle. if (hasLiveSideTurn(thread)) { - return { - label: "Answering", - colorClass: "text-primary-readable", - dotClass: THREAD_STATUS_DOT_CLASSES.blue, - pulse: true, - }; + return ANSWERING_PILL; } // The work stopped with a question still open: it waits on the user's // answer (or their next message, which closes it) like a blocking one. if (thread.hasPendingUserInput) { - return awaitingInputPill(); + return AWAITING_INPUT_PILL; } // A usage limit stopped it and it continues once the limit resets: the row @@ -388,12 +422,7 @@ export function resolveThreadStatusPill(input: { if (thread.session?.status === "error") { // Failed threads previously showed nothing -- indistinguishable from // healthy idle ones, which is the worst place for a failure to hide. - return { - label: "Failed", - colorClass: "text-red-600 dark:text-red-400/90", - dotClass: THREAD_STATUS_DOT_CLASSES.red, - pulse: false, - }; + return FAILED_PILL; } const hasPlanReadyPrompt = @@ -402,23 +431,13 @@ export function resolveThreadStatusPill(input: { isLatestTurnSettled(thread.latestTurn, thread.session) && thread.hasActionableProposedPlan; if (hasPlanReadyPrompt) { - return { - label: "Plan Ready", - colorClass: "text-violet-600 dark:text-violet-300/90", - dotClass: THREAD_STATUS_DOT_CLASSES.violet, - pulse: false, - }; + return PLAN_READY_PILL; } // Settled turn with provider tasks still running: the provider will start // the thread back up on its own when they finish. if (isWaitingOnBackgroundTasks(thread.latestTurn, thread.session)) { - return { - label: "Waiting", - colorClass: WAITING_STATUS_TONE, - dotClass: THREAD_STATUS_DOT_CLASSES.cyan, - pulse: true, - }; + return WAITING_PILL; } // Its own turn is over and the threads its agent started still owe it @@ -435,12 +454,7 @@ export function resolveThreadStatusPill(input: { } if (hasUnseenCompletion(thread)) { - return { - label: "Completed", - colorClass: "text-emerald-600 dark:text-emerald-300/90", - dotClass: THREAD_STATUS_DOT_CLASSES.emerald, - pulse: false, - }; + return COMPLETED_PILL; } // Settled, and an agent set itself to come back: the row says when, not diff --git a/apps/web/src/components/source-control/SourceControlPanel.tsx b/apps/web/src/components/source-control/SourceControlPanel.tsx index 206dc4ed8..e7a8a16c0 100644 --- a/apps/web/src/components/source-control/SourceControlPanel.tsx +++ b/apps/web/src/components/source-control/SourceControlPanel.tsx @@ -24,6 +24,7 @@ import { useQueryClient, } from "@tanstack/react-query"; import { useNavigate } from "@tanstack/react-router"; +import { useShallow } from "zustand/react/shallow"; import { ChevronDownIcon, ChevronRightIcon, @@ -117,7 +118,11 @@ import { getAppModelOptionsForInstance } from "~/modelSelection"; import { useServerProviders } from "~/rpc/serverState"; import { getSourceControlPresentation } from "~/sourceControlPresentation"; import { useStore } from "~/store"; -import { createProjectSelectorByRef, createThreadSelectorByRef } from "~/storeSelectors"; +import { + createProjectSelectorByRef, + createThreadCheckoutSelectorByRef, + createThreadProviderReviewSelectorByRef, +} from "~/storeSelectors"; import { buildThreadRouteParams } from "~/threadRoutes"; import { resolvePathLinkTarget } from "~/terminal-links"; import { getVcsRefBadge, type WorktreeCleanupRow } from "~/worktreeCleanup"; @@ -1433,7 +1438,7 @@ function SourceControlBranchMenu({ }) { const queryClient = useQueryClient(); const activeThread = useStore( - useMemo(() => createThreadSelectorByRef(activeThreadRef), [activeThreadRef]), + useMemo(() => createThreadCheckoutSelectorByRef(activeThreadRef), [activeThreadRef]), ); const activeThreadSession = activeThread?.session ?? null; const selectServerThreadCheckout = useThreadCheckoutSelection({ @@ -2063,13 +2068,24 @@ export function SourceControlPanel({ setPendingDropStash(null); }, [cwd, environmentId]); const reviewThread = useStore( - useMemo(() => createThreadSelectorByRef(activeThreadRef), [activeThreadRef]), + useMemo(() => createThreadProviderReviewSelectorByRef(activeThreadRef), [activeThreadRef]), ); const reviewDraftSession = useComposerDraftStore((store) => activeThreadRef ? store.getDraftSessionByRef(activeThreadRef) : null, ); - const reviewComposerDraft = useComposerDraftStore((store) => - activeThreadRef ? store.getComposerDraft(activeThreadRef) : null, + const reviewComposerDraft = useComposerDraftStore( + useShallow((store) => { + const draft = activeThreadRef ? store.getComposerDraft(activeThreadRef) : null; + if (!draft) { + return null; + } + return { + activeProvider: draft.activeProvider, + modelSelectionByProvider: draft.modelSelectionByProvider, + runtimeMode: draft.runtimeMode, + interactionMode: draft.interactionMode, + }; + }), ); const reviewProjectRef = useMemo(() => { const threadContext = reviewThread ?? reviewDraftSession; diff --git a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts index 42de4bc15..b69a99fb7 100644 --- a/apps/web/src/environments/runtime/service.savedEnvironments.test.ts +++ b/apps/web/src/environments/runtime/service.savedEnvironments.test.ts @@ -156,6 +156,7 @@ vi.mock("~/store", () => ({ selectProjectsAcrossEnvironments: vi.fn(() => []), selectSidebarThreadSummaryByRef: vi.fn(() => null), selectThreadByRef: vi.fn(() => null), + selectThreadShellByRef: vi.fn(() => null), selectThreadShellsAcrossEnvironments: vi.fn(() => []), selectThreadsAcrossEnvironments: vi.fn(() => []), })); @@ -174,6 +175,7 @@ vi.mock("~/uiStateStore", () => ({ useUiStateStore: { getState: () => ({ clearThreadUi: vi.fn(), + syncThread: vi.fn(), syncPromotedDraftThreadRefs: vi.fn(), }), }, diff --git a/apps/web/src/environments/runtime/service.ts b/apps/web/src/environments/runtime/service.ts index 29d19b999..0e33d9dad 100644 --- a/apps/web/src/environments/runtime/service.ts +++ b/apps/web/src/environments/runtime/service.ts @@ -6,6 +6,7 @@ import { type OrchestrationEvent, type OrchestrationShellSnapshot, type OrchestrationShellStreamEvent, + type OrchestrationThreadShell, type ScopedThreadRef, type ServerConfig, type TerminalStreamEvent, @@ -94,8 +95,8 @@ import { selectProjectsAcrossEnvironments, selectSidebarThreadSummaryByRef, selectThreadByRef, + selectThreadShellByRef, selectThreadShellsAcrossEnvironments, - selectThreadsAcrossEnvironments, } from "~/store"; import { useTerminalStateStore } from "~/terminalStateStore"; import { useUiStateStore } from "~/uiStateStore"; @@ -1197,6 +1198,18 @@ function syncProjectUiFromStore() { ); } +function syncSingleThreadUiFromShell( + thread: OrchestrationThreadShell, + environmentId: EnvironmentId, +) { + useUiStateStore.getState().syncThread({ + key: scopedThreadKey(scopeThreadRef(environmentId, thread.id)), + seedVisitedAt: thread.updatedAt ?? thread.createdAt, + serverLastSeenAt: thread.lastSeenAt, + serverDoneOverrideAt: thread.doneOverride?.at ?? null, + }); +} + function syncThreadUiFromStore() { const appState = useStore.getState(); // The shells carry everything read here; whole threads would rebuild every @@ -1228,7 +1241,7 @@ function reconcileSnapshotDerivedState() { syncProjectUiFromStore(); syncThreadUiFromStore(); - const threads = selectThreadsAcrossEnvironments(useStore.getState()); + const threads = selectThreadShellsAcrossEnvironments(useStore.getState()); const activeThreadKeys = collectActiveTerminalThreadIds({ snapshotThreads: threads.map((thread) => ({ key: scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), @@ -1424,7 +1437,9 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En ? event.threadId : null; const threadRef = threadId ? scopeThreadRef(environmentId, threadId) : null; - const previousThread = threadRef ? selectThreadByRef(useStore.getState(), threadRef) : undefined; + const previousThread = threadRef + ? selectThreadShellByRef(useStore.getState(), threadRef) + : undefined; writeThreadStore(environmentId, threadId, () => useStore.getState().applyShellEvent(event, environmentId), @@ -1437,13 +1452,13 @@ function applyShellEvent(event: OrchestrationShellStreamEvent, environmentId: En syncProjectUiFromStore(); return; case "thread-upserted": - syncThreadUiFromStore(); + syncSingleThreadUiFromShell(event.thread, environmentId); settleComposerPullRequestDismissals({ environmentId, threadId: event.thread.id, sequence: event.sequence, }); - if (!previousThread && threadRef) { + if (threadRef) { markPromotedDraftThreadByRef(threadRef); } threadDetails.warmNonIdle(environmentId, [event.thread]); diff --git a/apps/web/src/hooks/useInboxThreads.ts b/apps/web/src/hooks/useInboxThreads.ts index 0cd291283..6abb2cab0 100644 --- a/apps/web/src/hooks/useInboxThreads.ts +++ b/apps/web/src/hooks/useInboxThreads.ts @@ -6,7 +6,14 @@ import { scopeThreadRef, } from "@threadlines/client-runtime"; import type { ScopedProjectRef } from "@threadlines/contracts"; -import { useCallback, useMemo } from "react"; +import { + createContext, + createElement, + type ReactNode, + useCallback, + useContext, + useMemo, +} from "react"; import { useShallow } from "zustand/react/shallow"; import { @@ -107,16 +114,14 @@ export interface InboxThreads { readonly generalChatEntries: InboxGeneralChatEntry[]; } +const InboxThreadsContext = createContext(null); + /** - * The inbox: every open thread with the status its row shows and whether it - * sits under Active or Wrapped, plus the general chats beside it. - * - * The sidebar draws it, and the desktop app counts its unread finished work on - * the Dock and taskbar. Both read it from here so the badge can never name a - * thread the sidebar has filed away. Each caller runs its own copy; the pull - * request listings are shared queries, so a second caller costs no requests. + * Derives the shared inbox once at the app shell so the sidebar, alert sounds, + * taskbar status sync, family tabs, title menu, command palette, and boards + * read the same snapshot instead of repeating the O(threads) derivation. */ -export function useInboxThreads(): InboxThreads { +function useDerivedInboxThreads(): InboxThreads { const projects = useStore(useShallow(selectProjectsAcrossEnvironments)); const sidebarThreads = useStore(useShallow(selectSidebarThreadsAcrossEnvironments)); // One listing for the whole sidebar: the Pull Requests row's count and every @@ -395,21 +400,62 @@ export function useInboxThreads(): InboxThreads { [generalChatThreads, seenThreadOverlays, threadSeedVisitedAtById], ); - return { - projects, - sidebarThreads, - sidebarProjects, - sidebarProjectByKey, - resolveProjectKeyForRef, - resolveThreadProjectKey, - generalChatProjectKeys, - inboxThreads, - openPullRequests, - pullRequestByThreadKey, - linkedPullRequestsByThreadKey, - nowIso, - leadThreadKeys, - entries, - generalChatEntries, - }; + return useMemo( + () => ({ + projects, + sidebarThreads, + sidebarProjects, + sidebarProjectByKey, + resolveProjectKeyForRef, + resolveThreadProjectKey, + generalChatProjectKeys, + inboxThreads, + openPullRequests, + pullRequestByThreadKey, + linkedPullRequestsByThreadKey, + nowIso, + leadThreadKeys, + entries, + generalChatEntries, + }), + [ + entries, + generalChatEntries, + generalChatProjectKeys, + inboxThreads, + leadThreadKeys, + linkedPullRequestsByThreadKey, + nowIso, + openPullRequests, + projects, + pullRequestByThreadKey, + resolveProjectKeyForRef, + resolveThreadProjectKey, + sidebarProjectByKey, + sidebarProjects, + sidebarThreads, + ], + ); +} + +/** Provides one shared {@link InboxThreads} derivation to all inbox consumers. */ +export function InboxThreadsProvider({ children }: { readonly children: ReactNode }) { + const value = useDerivedInboxThreads(); + return createElement(InboxThreadsContext.Provider, { value }, children); +} + +/** + * The inbox: every open thread with the status its row shows and whether it + * sits under Active or Wrapped, plus the general chats beside it. + * + * The sidebar draws it, and the desktop app counts its unread finished work on + * the Dock and taskbar. Both read the shared value from {@link InboxThreadsProvider} + * so the badge can never name a thread the sidebar has filed away. + */ +export function useInboxThreads(): InboxThreads { + const value = useContext(InboxThreadsContext); + if (value === null) { + throw new Error("useInboxThreads must be used within an InboxThreadsProvider."); + } + return value; } diff --git a/apps/web/src/hooks/useMarkdownFileLinkKinds.ts b/apps/web/src/hooks/useMarkdownFileLinkKinds.ts index 7f5090783..9e421d649 100644 --- a/apps/web/src/hooks/useMarkdownFileLinkKinds.ts +++ b/apps/web/src/hooks/useMarkdownFileLinkKinds.ts @@ -35,6 +35,30 @@ function directoryListingCacheKey(environmentId: EnvironmentId, parentPath: stri return `${environmentId}\u0000${normalizeFilesystemPathForComparison(parentPath)}`; } +const EMPTY_KIND_MAP: ReadonlyMap = new Map(); + +function kindMapsEqual( + left: ReadonlyMap, + right: ReadonlyMap, +): boolean { + if (left === right) return true; + if (left.size !== right.size) return false; + for (const [key, value] of left) { + if (right.get(key) !== value) return false; + } + return true; +} + +function peekCachedDirectoryListing( + environmentId: EnvironmentId, + parentPath: string, +): ReadonlySet | null { + const key = directoryListingCacheKey(environmentId, parentPath); + const cached = directoryListingCache.get(key); + if (!cached || cached.expiresAt <= Date.now()) return null; + return cached.directoryPaths; +} + function readCachedDirectoryListing( environmentId: EnvironmentId, parentPath: string, @@ -49,6 +73,38 @@ function readCachedDirectoryListing( return cached.directoryPaths; } +function computeInitialKindByPath( + fileLinkMetaByHref: ReadonlyMap, + environmentId: EnvironmentId | undefined, +): ReadonlyMap { + if (fileLinkMetaByHref.size === 0) return EMPTY_KIND_MAP; + let initial: Map | null = null; + for (const meta of fileLinkMetaByHref.values()) { + if (meta.line !== undefined || !environmentId) { + initial ??= new Map(); + initial.set(meta.filePath, "file"); + continue; + } + const parentPath = browseParentPath(meta.filePath); + if (!parentPath) { + initial ??= new Map(); + initial.set(meta.filePath, "file"); + continue; + } + const cachedListing = peekCachedDirectoryListing(environmentId, parentPath); + if (cachedListing) { + initial ??= new Map(); + initial.set( + meta.filePath, + cachedListing.has(normalizeFilesystemPathForComparison(meta.filePath)) + ? "directory" + : "file", + ); + } + } + return initial ?? EMPTY_KIND_MAP; +} + function resolveDirectoryListing( environmentId: EnvironmentId, parentPath: string, @@ -92,11 +148,16 @@ export function useMarkdownFileLinkKinds( environmentId: EnvironmentId | undefined, cwd: string | undefined, ): ReadonlyMap { - const [kindByPath, setKindByPath] = useState>( - () => new Map(), + const [kindByPath, setKindByPath] = useState>(() => + computeInitialKindByPath(fileLinkMetaByHref, environmentId), ); useEffect(() => { + if (fileLinkMetaByHref.size === 0) { + setKindByPath((previous) => (previous.size === 0 ? previous : EMPTY_KIND_MAP)); + return; + } + let cancelled = false; const nextKindByPath = new Map(); const unresolvedPathsByParent = new Map(); @@ -129,7 +190,10 @@ export function useMarkdownFileLinkKinds( unresolvedPathsByParent.set(parentPath, unresolvedPaths); } - setKindByPath(nextKindByPath); + const immediateKindByPath = nextKindByPath.size === 0 ? EMPTY_KIND_MAP : nextKindByPath; + setKindByPath((previous) => + kindMapsEqual(previous, immediateKindByPath) ? previous : immediateKindByPath, + ); if (!environmentId || unresolvedPathsByParent.size === 0) { return () => { cancelled = true; @@ -155,7 +219,10 @@ export function useMarkdownFileLinkKinds( ); } } - setKindByPath(resolvedKindByPath); + const finalKindByPath = resolvedKindByPath.size === 0 ? EMPTY_KIND_MAP : resolvedKindByPath; + setKindByPath((previous) => + kindMapsEqual(previous, finalKindByPath) ? previous : finalKindByPath, + ); }); return () => { diff --git a/apps/web/src/hooks/useTurnDiffSummaries.ts b/apps/web/src/hooks/useTurnDiffSummaries.ts index 2bebb6684..2b6a715e9 100644 --- a/apps/web/src/hooks/useTurnDiffSummaries.ts +++ b/apps/web/src/hooks/useTurnDiffSummaries.ts @@ -8,7 +8,7 @@ const inferRememberedCheckpointTurnCounts = keyedMemo((summaries: Thread["turnDi inferCheckpointTurnCountByTurnId(summaries), ); -export function useTurnDiffSummaries(activeThread: Thread | undefined) { +export function useTurnDiffSummaries(activeThread: Pick | undefined) { const turnDiffSummaries = useMemo(() => { if (!activeThread) { return []; diff --git a/apps/web/src/lib/chatMarkdownDocument.test.ts b/apps/web/src/lib/chatMarkdownDocument.test.ts index a96c6e667..99be2a175 100644 --- a/apps/web/src/lib/chatMarkdownDocument.test.ts +++ b/apps/web/src/lib/chatMarkdownDocument.test.ts @@ -2,7 +2,11 @@ import { describe, expect, it } from "vite-plus/test"; import { collectWrittenFilePaths, + indexWrittenFilePathsByBasename, repairStreamingMarkdownTail, + resolveMarkdownDocumentFileLinks, + scanMarkdownBlockFileLinks, + selectWrittenFilePathsKeyForBareNames, splitMarkdownBlocks, } from "./chatMarkdownDocument"; import { fencedBlockIsClosed } from "./markdownFences"; @@ -123,6 +127,50 @@ describe("collectWrittenFilePaths", () => { "C:\\Users\\me\\notes\\plan.md", ]); }); + + it("matches only bare file names relevant to a block while keeping ambiguous paths intact", () => { + const first = scanMarkdownBlockFileLinks( + "Updated [a](/Users/me/repo/a/index.ts) and `/Users/me/repo/src/math.ts`.", + "/Users/me/repo", + ); + const second = scanMarkdownBlockFileLinks( + "See `math.ts:12` and `index.ts` and `other.ts`.", + "/Users/me/repo", + ); + const third = scanMarkdownBlockFileLinks( + "Also [b](/Users/me/repo/b/index.ts).", + "/Users/me/repo", + ); + + const byBasename = indexWrittenFilePathsByBasename([ + ...first.writtenPaths, + ...second.writtenPaths, + ...third.writtenPaths, + ]); + expect(second.bareFileNames).toEqual(["index.ts", "math.ts", "other.ts"]); + expect(selectWrittenFilePathsKeyForBareNames(first.bareFileNames, byBasename)).toBe(""); + expect(selectWrittenFilePathsKeyForBareNames(second.bareFileNames, byBasename)).toBe( + ["/Users/me/repo/a/index.ts", "/Users/me/repo/b/index.ts", "/Users/me/repo/src/math.ts"].join( + "\n", + ), + ); + + const noLinksA = resolveMarkdownDocumentFileLinks("Plain prose only.", "/Users/me/repo", { + inlineCodeChips: true, + writtenFilePaths: [], + }); + const noLinksB = resolveMarkdownDocumentFileLinks("Still plain prose.", "/Users/me/repo", { + inlineCodeChips: true, + writtenFilePaths: [], + }); + expect(noLinksA.fileLinkMetaByKey).toBe(noLinksB.fileLinkMetaByKey); + expect(noLinksA.fileLinkParentSuffixByPath).toBe(noLinksB.fileLinkParentSuffixByPath); + }); + + it("keeps scanning bare file names after an unmatched $$ display-math opener", () => { + const scan = scanMarkdownBlockFileLinks("$$\nSee `report.ts:12`.", "/Users/me/repo"); + expect(scan.bareFileNames).toEqual(["report.ts"]); + }); }); describe("repairStreamingMarkdownTail", () => { diff --git a/apps/web/src/lib/chatMarkdownDocument.ts b/apps/web/src/lib/chatMarkdownDocument.ts index 89469f316..b6af76216 100644 --- a/apps/web/src/lib/chatMarkdownDocument.ts +++ b/apps/web/src/lib/chatMarkdownDocument.ts @@ -25,7 +25,7 @@ import { resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref, } from "../markdown-links"; -import { createFenceTracker } from "./markdownFences"; +import { createFenceTracker, laterMathClosers } from "./markdownFences"; export { splitMarkdownBlocks } from "@threadlines/shared/markdownBlocks"; @@ -182,17 +182,20 @@ export function buildInlineCodeFileLinkMeta( text: string, cwd: string | undefined, ): ReadonlyMap { - const metaBySpan = new Map(); + let metaBySpan: Map | null = null; for (const span of extractInlineCodeSpans(text)) { - if (metaBySpan.has(span)) continue; + if (metaBySpan?.has(span)) continue; // A dev-server address reads as a file reference too (`127.0.0.1:8080`); it // is handled as an address by the renderer and must not become a chip. if (localhostUrlFromText(span)) continue; if (!parseChatFileReference(span) && !isAbsoluteInlineFilePath(span)) continue; const meta = resolveMarkdownFileLinkMeta(span, cwd); - if (meta) metaBySpan.set(span, meta); + if (meta) { + metaBySpan ??= new Map(); + metaBySpan.set(span, meta); + } } - return metaBySpan; + return metaBySpan ?? EMPTY_FILE_LINK_META_MAP; } const TAIL_CONTAINER_PREFIX_REGEX = /^[ \t>]*(?:(?:[-*+]|\d{1,9}[.)])(?= ))?[ \t]*/; @@ -352,37 +355,161 @@ export function chatMarkdownUrlTransform(href: string, cwd: string | undefined): } const EMPTY_FILE_LINK_META_MAP: ReadonlyMap = new Map(); +const EMPTY_SUFFIX_MAP: ReadonlyMap = new Map(); const EMPTY_SPAN_SET: ReadonlySet = new Set(); const EMPTY_PATHS: readonly string[] = []; -/** - * Every file a message names by a written-out path: a link with a folder in - * it, an inline code span that is an absolute path, an image path typed in - * prose. Fenced blocks are skipped, and so is a path inside a longer code span: - * a path in a command is not a citation. Read over the whole message, since - * chat draws each block on its own and a name often sits blocks below the path - * that placed it. Sorted, so equal answers compare equal. - */ -export function collectWrittenFilePaths(text: string, cwd: string | undefined): readonly string[] { - const paths = new Set(); - const add = (written: string) => { +/** Per-block file-path summary used to avoid rescanning settled blocks while streaming. */ +export interface MarkdownBlockFileLinkScan { + readonly writtenPaths: readonly string[]; + /** Bare file names referenced in inline code (`home.png`, `math.ts:12`), without line/column. */ + readonly bareFileNames: readonly string[]; +} + +const EMPTY_BLOCK_FILE_LINK_SCAN: MarkdownBlockFileLinkScan = { + writtenPaths: EMPTY_PATHS, + bareFileNames: EMPTY_PATHS, +}; + +const MAX_BLOCK_FILE_LINK_SCAN_CACHE_ENTRIES = 512; +const blockFileLinkScanCache = new Map(); + +function scanMarkdownBlockFileLinksUncached( + text: string, + cwd: string | undefined, +): MarkdownBlockFileLinkScan { + let writtenPaths: Set | null = null; + let bareFileNames: Set | null = null; + const addWritten = (written: string) => { const meta = resolveMarkdownFileLinkMeta(written, cwd); - if (meta) paths.add(meta.filePath); + if (meta) { + writtenPaths ??= new Set(); + writtenPaths.add(meta.filePath); + } }; - const fence = createFenceTracker(); - for (const line of text.split("\n")) { + const lines = text.split("\n"); + const fence = createFenceTracker({ closesLater: laterMathClosers(lines) }); + for (const line of lines) { if (fence.feed(line) !== "text") continue; for (const href of extractMarkdownLinkHrefs(line)) { - if (href.includes("/") || href.includes("\\")) add(normalizeMarkdownLinkHrefKey(href)); + if (href.includes("/") || href.includes("\\")) addWritten(normalizeMarkdownLinkHrefKey(href)); } for (const match of line.matchAll(INLINE_CODE_RUN_PATTERN)) { const span = match[2]?.trim(); - if (span && isAbsoluteInlineFilePath(span)) add(span); + if (!span) continue; + if (isAbsoluteInlineFilePath(span)) { + addWritten(span); + continue; + } + if (localhostUrlFromText(span)) continue; + const reference = parseChatFileReference(span); + if (reference && !reference.path.includes("/")) { + bareFileNames ??= new Set(); + bareFileNames.add(reference.path); + } } const prose = line.replace(INLINE_CODE_RUN_PATTERN, (run) => " ".repeat(run.length)); - for (const match of findBareImagePaths(prose)) add(match.text); + for (const match of findBareImagePaths(prose)) addWritten(match.text); + } + if (!writtenPaths && !bareFileNames) { + return EMPTY_BLOCK_FILE_LINK_SCAN; } - return paths.size === 0 ? EMPTY_PATHS : [...paths].toSorted(); + return { + writtenPaths: writtenPaths ? [...writtenPaths].toSorted() : EMPTY_PATHS, + bareFileNames: bareFileNames ? [...bareFileNames].toSorted() : EMPTY_PATHS, + }; +} + +/** + * Scans one markdown block for written file paths and bare inline-code file + * names. Settled blocks hit a bounded LRU cache so streaming deltas only scan + * the growing tail block. + */ +export function scanMarkdownBlockFileLinks( + text: string, + cwd: string | undefined, + options?: { readonly cache?: boolean }, +): MarkdownBlockFileLinkScan { + if (options?.cache === false) { + return scanMarkdownBlockFileLinksUncached(text, cwd); + } + const cacheKey = `${cwd ?? ""}\u0000${text}`; + const cached = blockFileLinkScanCache.get(cacheKey); + if (cached !== undefined) { + blockFileLinkScanCache.delete(cacheKey); + blockFileLinkScanCache.set(cacheKey, cached); + return cached; + } + const computed = scanMarkdownBlockFileLinksUncached(text, cwd); + if (blockFileLinkScanCache.size >= MAX_BLOCK_FILE_LINK_SCAN_CACHE_ENTRIES) { + const oldestKey = blockFileLinkScanCache.keys().next().value; + if (oldestKey !== undefined) { + blockFileLinkScanCache.delete(oldestKey); + } + } + blockFileLinkScanCache.set(cacheKey, computed); + return computed; +} + +/** Groups written file paths by trailing basename segment for O(1) bare-name lookup. */ +export function indexWrittenFilePathsByBasename( + writtenPaths: Iterable, +): ReadonlyMap { + const byBasename = new Map>(); + for (const filePath of writtenPaths) { + const slashed = filePath.replaceAll("\\", "/"); + const lastSlash = slashed.lastIndexOf("/"); + if (lastSlash < 0) continue; + const basename = slashed.slice(lastSlash + 1); + if (!basename) continue; + let group = byBasename.get(basename); + if (!group) { + group = new Set(); + byBasename.set(basename, group); + } + group.add(filePath); + } + const sorted = new Map(); + for (const [basename, group] of byBasename) { + sorted.set(basename, [...group].toSorted()); + } + return sorted; +} + +/** Returns only the written paths that could match one of `bareFileNames`, as a newline-joined key. */ +export function selectWrittenFilePathsKeyForBareNames( + bareFileNames: readonly string[], + writtenPathsByBasename: ReadonlyMap, +): string { + if (bareFileNames.length === 0 || writtenPathsByBasename.size === 0) { + return ""; + } + if (bareFileNames.length === 1) { + const matches = writtenPathsByBasename.get(bareFileNames[0]!); + return matches ? matches.join("\n") : ""; + } + let matched: Set | null = null; + for (const name of bareFileNames) { + const group = writtenPathsByBasename.get(name); + if (!group) continue; + matched ??= new Set(); + for (const filePath of group) { + matched.add(filePath); + } + } + return matched ? [...matched].toSorted().join("\n") : ""; +} + +/** + * Every file a message names by a written-out path: a link with a folder in + * it, an inline code span that is an absolute path, an image path typed in + * prose. Fenced blocks are skipped, and so is a path inside a longer code span: + * a path in a command is not a citation. Read over the whole message, since + * chat draws each block on its own and a name often sits blocks below the path + * that placed it. Sorted, so equal answers compare equal. + */ +export function collectWrittenFilePaths(text: string, cwd: string | undefined): readonly string[] { + return scanMarkdownBlockFileLinksUncached(text, cwd).writtenPaths; } /** @@ -481,15 +608,18 @@ export function resolveMarkdownDocumentFileLinks( readonly writtenFilePaths?: readonly string[] | undefined; }, ): MarkdownDocumentFileLinks { - const markdownFileLinkMetaByHref = new Map(); + let markdownFileLinkMetaByHrefMap: Map | null = null; for (const href of extractMarkdownLinkHrefs(text)) { const normalizedHref = normalizeMarkdownLinkHrefKey(href); - if (markdownFileLinkMetaByHref.has(normalizedHref)) continue; + if (markdownFileLinkMetaByHrefMap?.has(normalizedHref)) continue; const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd); if (meta) { - markdownFileLinkMetaByHref.set(normalizedHref, meta); + markdownFileLinkMetaByHrefMap ??= new Map(); + markdownFileLinkMetaByHrefMap.set(normalizedHref, meta); } } + const markdownFileLinkMetaByHref: ReadonlyMap = + markdownFileLinkMetaByHrefMap ?? EMPTY_FILE_LINK_META_MAP; const { metaBySpan: inlineCodeFileLinkMetaBySpan, placedSpans: inlineCodeSpansPlacedByDocument } = options.inlineCodeChips ? placeShortReferencesByWrittenPaths( @@ -500,15 +630,22 @@ export function resolveMarkdownDocumentFileLinks( : { metaBySpan: EMPTY_FILE_LINK_META_MAP, placedSpans: EMPTY_SPAN_SET }; let fileLinkMetaByKey: ReadonlyMap = markdownFileLinkMetaByHref; if (inlineCodeFileLinkMetaBySpan.size > 0) { - const merged = new Map(markdownFileLinkMetaByHref); - for (const [span, meta] of inlineCodeFileLinkMetaBySpan) { - if (!merged.has(span)) merged.set(span, meta); + if (markdownFileLinkMetaByHref.size === 0) { + fileLinkMetaByKey = inlineCodeFileLinkMetaBySpan; + } else { + const merged = new Map(markdownFileLinkMetaByHref); + for (const [span, meta] of inlineCodeFileLinkMetaBySpan) { + if (!merged.has(span)) merged.set(span, meta); + } + fileLinkMetaByKey = merged; } - fileLinkMetaByKey = merged; } - const fileLinkParentSuffixByPath = buildFileLinkParentSuffixByPath( - [...fileLinkMetaByKey.values()].map((meta) => meta.filePath), - ); + const fileLinkParentSuffixByPath: ReadonlyMap = + fileLinkMetaByKey.size < 2 + ? EMPTY_SUFFIX_MAP + : buildFileLinkParentSuffixByPath( + [...fileLinkMetaByKey.values()].map((meta) => meta.filePath), + ); return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaBySpan, diff --git a/apps/web/src/lib/providerReview.ts b/apps/web/src/lib/providerReview.ts index 70dccbc36..b4f1b5612 100644 --- a/apps/web/src/lib/providerReview.ts +++ b/apps/web/src/lib/providerReview.ts @@ -35,8 +35,19 @@ export interface ProviderReviewContext { readonly providerInstanceEntries: ReadonlyArray; } +export type ProviderReviewThread = Pick< + Thread, + | "projectId" + | "modelSelection" + | "runtimeMode" + | "interactionMode" + | "branch" + | "worktreePath" + | "session" +>; + export function resolveProviderReviewContext(input: { - readonly thread: Thread | null | undefined; + readonly thread: ProviderReviewThread | null | undefined; readonly draftSession: DraftSessionState | null | undefined; readonly composerDraft: | Pick< diff --git a/apps/web/src/lib/threadInboxSync.ts b/apps/web/src/lib/threadInboxSync.ts index 939f8688a..d147f9f33 100644 --- a/apps/web/src/lib/threadInboxSync.ts +++ b/apps/web/src/lib/threadInboxSync.ts @@ -149,7 +149,15 @@ export function setThreadDoneOverride( settled: false, }); void dispatchDoneOverride(threadRef, state, at).then( - () => useUiStateStore.getState().resolveDoneOverlay(threadKey, at, "confirmed"), + () => + useUiStateStore + .getState() + .resolveDoneOverlay( + threadKey, + at, + "confirmed", + readServerLifecycle(threadRef).doneOverride?.at ?? null, + ), () => useUiStateStore.getState().resolveDoneOverlay(threadKey, at, "failed"), ); } diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 26d606e8c..33f18efa8 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -90,7 +90,7 @@ import { import { isElectron } from "../env"; import { readLocalApi } from "../localApi"; import { refreshSourceControlDiscoveryAfterReconnect } from "../lib/sourceControlDiscoveryState"; -import { useInboxThreads } from "../hooks/useInboxThreads"; +import { InboxThreadsProvider, useInboxThreads } from "../hooks/useInboxThreads"; import { useSettings } from "../hooks/useSettings"; import { isUnreadFinishedWork } from "../components/Sidebar.logic"; import { toSortableTimestamp } from "../lib/threadSort"; @@ -278,52 +278,54 @@ function RootRouteView() { - - {isElectron ? : null} - {primaryEnvironmentAuthenticated ? : null} - {primaryEnvironmentAuthenticated ? ( - - - - ) : null} - {/* The Keep bar every theme trial shows, the import dialog, theme file drops. */} - - {isElectron ? : null} - {/* Plain Suspense: the browser panel needs it, so a failure shows. */} - {isElectron ? ( - - - - ) : null} - - - - - - - - - - - - - - - {primaryEnvironmentAuthenticated ? : null} - - {primaryEnvironmentAuthenticated ? : null} - {/* Not over first-run setup: the one chance would go to a screen about something else. */} - {shownRouteId !== "/setup" ? : null} - {primaryEnvironmentAuthenticated ? : null} - - {primaryEnvironmentAuthenticated ? : null} - {primaryEnvironmentAuthenticated ? : null} - - {primaryEnvironmentAuthenticated ? ( - {appShell} - ) : ( - appShell - )} + + + {isElectron ? : null} + {primaryEnvironmentAuthenticated ? : null} + {primaryEnvironmentAuthenticated ? ( + + + + ) : null} + {/* The Keep bar every theme trial shows, the import dialog, theme file drops. */} + + {isElectron ? : null} + {/* Plain Suspense: the browser panel needs it, so a failure shows. */} + {isElectron ? ( + + + + ) : null} + + + + + + + + + + + + + + + {primaryEnvironmentAuthenticated ? : null} + + {primaryEnvironmentAuthenticated ? : null} + {/* Not over first-run setup: the one chance would go to a screen about something else. */} + {shownRouteId !== "/setup" ? : null} + {primaryEnvironmentAuthenticated ? : null} + + {primaryEnvironmentAuthenticated ? : null} + {primaryEnvironmentAuthenticated ? : null} + + {primaryEnvironmentAuthenticated ? ( + {appShell} + ) : ( + appShell + )} + {authGateState.status === "hosted-static" ? : null} {authGateState.status === "hosted-static" ? : null} diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx index c617ac9e4..a9d36a4de 100644 --- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx +++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx @@ -13,7 +13,6 @@ import { HostedStaticLinkNotPairedState, HostedStaticLoadingState, } from "../components/ConnectionStatusStates"; -import { threadHasPromotableServerActivity } from "../components/ChatView.logic"; import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider"; import { DiffPanelLoadingState, @@ -118,7 +117,7 @@ import { selectThreadExistsByRef, useStore, } from "../store"; -import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; +import { createProjectSelectorByRef, createThreadRouteSelectorByRef } from "../storeSelectors"; import { setActiveFileViewerContext, useFileViewerStore } from "../fileViewerStore"; import { resolveThreadRouteRef, buildThreadRouteParams } from "../threadRoutes"; import { RightPanelSheet } from "../components/RightPanelSheet"; @@ -224,7 +223,9 @@ function ChatThreadRouteView() { const bootstrapComplete = useStore( (store) => selectEnvironmentState(store, threadRef?.environmentId ?? null).bootstrapComplete, ); - const serverThread = useStore(useMemo(() => createThreadSelectorByRef(threadRef), [threadRef])); + const serverThread = useStore( + useMemo(() => createThreadRouteSelectorByRef(threadRef), [threadRef]), + ); const threadExists = useStore((store) => selectThreadExistsByRef(store, threadRef)); const environmentHasServerThreads = useStore( (store) => selectEnvironmentState(store, threadRef?.environmentId ?? null).threadIds.length > 0, @@ -242,7 +243,7 @@ function ChatThreadRouteView() { return store.hasDraftThreadsInEnvironment(threadRef.environmentId); }); const routeThreadExists = threadExists || draftThreadExists; - const serverThreadHasPromotableActivity = threadHasPromotableServerActivity(serverThread); + const serverThreadHasPromotableActivity = serverThread?.hasPromotableActivity ?? false; const environmentHasAnyThreads = environmentHasServerThreads || environmentHasDraftThreads; const currentThreadKey = threadRef ? `${threadRef.environmentId}:${threadRef.threadId}` : null; const agentsPanelSource = useAgentsPanelSource(); @@ -380,15 +381,16 @@ function ChatThreadRouteView() { ); const devicesSupported = useDevicesSupported(threadRef?.environmentId ?? null); + const hasServerThread = serverThread !== undefined; const availableTabs = useMemo( () => availableRightPanelTabs({ isGeneralChat: isGeneralChatThread, // A thread the server has not accepted yet has no turn, so no agents. - isDraft: !serverThread, + isDraft: !hasServerThread, devicesSupported, }), - [devicesSupported, isGeneralChatThread, serverThread], + [devicesSupported, hasServerThread, isGeneralChatThread], ); // The thread's pull request, for the Pull request tab and the launcher row @@ -721,7 +723,7 @@ function ChatThreadRouteView() { // Media tab opens on, so the row and the tab agree. Read only while the // launcher is on screen; a turn landing changes the revision and so the key. // A message (a reply, your attachment) can share a picture between turns. - const mediaTurnsRevision = `${turnSummariesRevision(serverThread?.turnDiffSummaries ?? null)}:${serverThread?.messages.length ?? 0}`; + const mediaTurnsRevision = `${turnSummariesRevision(serverThread?.turnDiffSummaries ?? null)}:${serverThread?.messageCount ?? 0}`; const launcherMediaListing = useQuery( projectMediaQueryOptions({ environmentId: threadRef?.environmentId ?? null, diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index e4462aa01..b1685e808 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -3778,4 +3778,81 @@ describe("selectRunningSidebarThreadsAcrossEnvironments", () => { expect(ids(unknown.local)).toEqual([local.id, remote.id]); expect(unknown.remote).toEqual([]); }); + + it("keeps thread shell identity when an upserted shell carries a fresh structurally equal modelSelection", () => { + const thread = makeThread({ + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + options: [{ id: "reasoningEffort", value: "high" }], + }, + }); + const baseState = makeState(thread); + const makeUpsert = (sequence: number, updatedAt: string) => + ({ + kind: "thread-upserted", + sequence, + thread: { + id: thread.id, + projectId: thread.projectId, + title: thread.title, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5-codex", + options: [{ id: "reasoningEffort", value: "high" }], + }, + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + branch: thread.branch, + worktreePath: thread.worktreePath, + effectiveCwd: thread.effectiveCwd, + goal: null, + latestTurn: null, + createdAt: thread.createdAt, + updatedAt, + archivedAt: thread.archivedAt, + pinnedAt: thread.pinnedAt, + pullRequestAutoFix: false, + pullRequestAutoMerge: null, + linkedPullRequests: [], + participants: [], + doneOverride: null, + lastSeenAt: null, + session: null, + latestUserMessageAt: null, + hasPendingApprovals: false, + hasPendingUserInput: false, + hasActionableProposedPlan: false, + cumulativeDiffStat: null, + diffStatBaselineTurnCount: 0, + ...NO_CHILD_THREAD_SHELL_FIELDS, + }, + }) as const; + + const first = applyShellEvent( + baseState, + makeUpsert(2, "2026-02-27T00:00:01.000Z"), + localEnvironmentId, + ); + const firstShell = localEnvironmentStateOf(first).threadShellById[thread.id]; + expect(firstShell).toBeDefined(); + + // Exact same content with a fresh modelSelection object must keep the shell reference. + const second = applyShellEvent( + first, + makeUpsert(3, "2026-02-27T00:00:01.000Z"), + localEnvironmentId, + ); + expect(localEnvironmentStateOf(second).threadShellById[thread.id]).toBe(firstShell); + + // When updatedAt moves, the shell changes but modelSelection keeps its reference. + const third = applyShellEvent( + second, + makeUpsert(4, "2026-02-27T00:00:02.000Z"), + localEnvironmentId, + ); + const thirdShell = localEnvironmentStateOf(third).threadShellById[thread.id]; + expect(thirdShell).not.toBe(firstShell); + expect(thirdShell?.modelSelection).toBe(firstShell?.modelSelection); + }); }); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 9c308e013..b7e86d205 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -304,9 +304,13 @@ function normalizeModelSelection { + const other = b[index]; + return other !== undefined && option.id === other.id && option.value === other.value; + }); +} + /** - * A changed shell, keeping the participants it had while they are the same. - * The server pushes a whole shell again on every update a streaming turn - * makes, and what the chat builds from the participants (agent names and - * labels) should keep its identity across them. + * A changed shell, keeping references to nested structures (`participants`, + * `modelSelection`, `linkedPullRequests`, `dismissedPullRequests`) while their + * contents are unchanged. The server pushes a whole shell again on every update + * a streaming turn makes, and consumers keyed on those fields should keep + * reference identity across them. */ -function withKeptParticipants(previous: ThreadShell | undefined, next: ThreadShell): ThreadShell { - const kept = previous?.participants; - return kept !== undefined && - kept !== next.participants && - participantsEqual(kept, next.participants) - ? { ...next, participants: kept } - : next; +function withKeptShellReferences( + previous: ThreadShell | undefined, + next: ThreadShell, +): ThreadShell { + if (!previous) return next; + const keepParticipants = + previous.participants !== undefined && + previous.participants !== next.participants && + participantsEqual(previous.participants, next.participants); + const keepModelSelection = + previous.modelSelection !== next.modelSelection && + modelSelectionsEqual(previous.modelSelection, next.modelSelection); + const keepLinkedPullRequests = + previous.linkedPullRequests !== next.linkedPullRequests && + linkedPullRequestsEqual(previous.linkedPullRequests, next.linkedPullRequests); + const keepDismissedPullRequests = + previous.dismissedPullRequests !== next.dismissedPullRequests && + dismissedPullRequestsEqual(previous.dismissedPullRequests, next.dismissedPullRequests); + const keepWorktreeOrigin = + previous.worktreeOrigin !== next.worktreeOrigin && + worktreeOriginsEqual(previous.worktreeOrigin, next.worktreeOrigin); + if ( + !keepParticipants && + !keepModelSelection && + !keepLinkedPullRequests && + !keepDismissedPullRequests && + !keepWorktreeOrigin + ) { + return next; + } + return { + ...next, + ...(keepParticipants ? { participants: previous.participants } : {}), + ...(keepModelSelection ? { modelSelection: previous.modelSelection } : {}), + ...(keepLinkedPullRequests ? { linkedPullRequests: previous.linkedPullRequests } : {}), + ...(keepDismissedPullRequests ? { dismissedPullRequests: previous.dismissedPullRequests } : {}), + ...(keepWorktreeOrigin ? { worktreeOrigin: previous.worktreeOrigin } : {}), + }; } function threadShellsEqual(left: ThreadShell | undefined, right: ThreadShell): boolean { @@ -1566,7 +1620,7 @@ function threadShellsEqual(left: ThreadShell | undefined, right: ThreadShell): b left.codexThreadId === right.codexThreadId && left.projectId === right.projectId && left.title === right.title && - left.modelSelection === right.modelSelection && + modelSelectionsEqual(left.modelSelection, right.modelSelection) && left.runtimeMode === right.runtimeMode && left.interactionMode === right.interactionMode && left.error === right.error && @@ -1802,7 +1856,7 @@ function writeThreadState( ...nextState, threadShellById: { ...nextState.threadShellById, - [nextThread.id]: withKeptParticipants(previousShell, nextShell), + [nextThread.id]: withKeptShellReferences(previousShell, nextShell), }, }; } @@ -2035,7 +2089,7 @@ function writeThreadShellState( ...nextState, threadShellById: { ...nextState.threadShellById, - [nextThread.shell.id]: withKeptParticipants(previousShell, nextThread.shell), + [nextThread.shell.id]: withKeptShellReferences(previousShell, nextThread.shell), }, }; } @@ -4237,6 +4291,15 @@ export function selectProjectByRef( : undefined; } +export function selectThreadShellByRef( + state: AppState, + ref: ScopedThreadRef | null | undefined, +): ThreadShell | undefined { + return ref + ? selectEnvironmentState(state, ref.environmentId).threadShellById[ref.threadId] + : undefined; +} + export function selectThreadByRef( state: AppState, ref: ScopedThreadRef | null | undefined, diff --git a/apps/web/src/storeSelectors.ts b/apps/web/src/storeSelectors.ts index 492cc5771..bd2951503 100644 --- a/apps/web/src/storeSelectors.ts +++ b/apps/web/src/storeSelectors.ts @@ -1,7 +1,61 @@ import { type ScopedProjectRef, type ScopedThreadRef, type ThreadId } from "@threadlines/contracts"; import { selectEnvironmentState, type AppState, type EnvironmentState } from "./store"; import { type Project, type Thread } from "./types"; -import { getThreadFromEnvironmentState } from "./threadDerivation"; +import { + getThreadFromEnvironmentState, + selectThreadActivities, + selectThreadMessages, + selectThreadProposedPlans, + selectThreadTurnDiffSummaries, +} from "./threadDerivation"; + +export interface ThreadCheckoutSlice { + readonly id: Thread["id"]; + readonly environmentId: Thread["environmentId"]; + readonly projectId: Thread["projectId"]; + readonly branch: Thread["branch"]; + readonly worktreePath: Thread["worktreePath"]; + readonly effectiveCwd: Thread["effectiveCwd"]; + readonly worktreeOrigin: Thread["worktreeOrigin"]; + readonly session: Thread["session"]; +} + +export interface ThreadProviderReviewSlice { + readonly environmentId: Thread["environmentId"]; + readonly projectId: Thread["projectId"]; + readonly modelSelection: Thread["modelSelection"]; + readonly runtimeMode: Thread["runtimeMode"]; + readonly interactionMode: Thread["interactionMode"]; + readonly branch: Thread["branch"]; + readonly worktreePath: Thread["worktreePath"]; + readonly session: Thread["session"]; +} + +export interface ThreadDiffContextSlice { + readonly id: Thread["id"]; + readonly environmentId: Thread["environmentId"]; + readonly projectId: Thread["projectId"]; + readonly worktreePath: Thread["worktreePath"]; + readonly effectiveCwd: Thread["effectiveCwd"]; + readonly turnDiffSummaries: Thread["turnDiffSummaries"]; +} + +export interface ThreadRouteSlice { + readonly id: Thread["id"]; + readonly environmentId: Thread["environmentId"]; + readonly projectId: Thread["projectId"]; + readonly branch: Thread["branch"]; + readonly worktreePath: Thread["worktreePath"]; + readonly effectiveCwd: Thread["effectiveCwd"]; + readonly archivedAt: Thread["archivedAt"]; + readonly linkedPullRequests?: Exclude; + readonly dismissedPullRequests?: Exclude; + readonly pullRequestAutoFix?: Exclude; + readonly pullRequestAutoMerge?: Exclude; + readonly turnDiffSummaries: Thread["turnDiffSummaries"]; + readonly messageCount: number; + readonly hasPromotableActivity: boolean; +} export function createProjectSelectorByRef( ref: ScopedProjectRef | null | undefined, @@ -10,6 +64,247 @@ export function createProjectSelectorByRef( ref ? selectEnvironmentState(state, ref.environmentId).projectById[ref.projectId] : undefined; } +/** + * Selects only the checkout and session fields a branch/worktree control reads, + * ignoring streaming message, activity, diff, and `updatedAt` churn. + */ +export function createThreadCheckoutSelectorByRef( + ref: ScopedThreadRef | null | undefined, +): (state: AppState) => ThreadCheckoutSlice | undefined { + let previousEnvironmentState: EnvironmentState | undefined; + let previousValue: ThreadCheckoutSlice | undefined; + + return (state) => { + if (!ref) { + return undefined; + } + const environmentState = selectEnvironmentState(state, ref.environmentId); + if (previousEnvironmentState === environmentState) { + return previousValue; + } + previousEnvironmentState = environmentState; + + const shell = environmentState.threadShellById[ref.threadId]; + if (!shell) { + previousValue = undefined; + return undefined; + } + const session = environmentState.threadSessionById[ref.threadId] ?? null; + if ( + previousValue !== undefined && + previousValue.id === shell.id && + previousValue.environmentId === shell.environmentId && + previousValue.projectId === shell.projectId && + previousValue.branch === shell.branch && + previousValue.worktreePath === shell.worktreePath && + previousValue.effectiveCwd === shell.effectiveCwd && + previousValue.worktreeOrigin === shell.worktreeOrigin && + previousValue.session === session + ) { + return previousValue; + } + previousValue = { + id: shell.id, + environmentId: shell.environmentId, + projectId: shell.projectId, + branch: shell.branch, + worktreePath: shell.worktreePath, + effectiveCwd: shell.effectiveCwd, + worktreeOrigin: shell.worktreeOrigin, + session, + }; + return previousValue; + }; +} + +/** + * Selects only the fields needed to resolve provider review defaults in Source, + * avoiding re-renders during streaming turns and unrelated shell metadata churn. + */ +export function createThreadProviderReviewSelectorByRef( + ref: ScopedThreadRef | null | undefined, +): (state: AppState) => ThreadProviderReviewSlice | undefined { + let previousEnvironmentState: EnvironmentState | undefined; + let previousValue: ThreadProviderReviewSlice | undefined; + + return (state) => { + if (!ref) { + return undefined; + } + const environmentState = selectEnvironmentState(state, ref.environmentId); + if (previousEnvironmentState === environmentState) { + return previousValue; + } + previousEnvironmentState = environmentState; + + const shell = environmentState.threadShellById[ref.threadId]; + if (!shell) { + previousValue = undefined; + return undefined; + } + const session = environmentState.threadSessionById[ref.threadId] ?? null; + if ( + previousValue !== undefined && + previousValue.environmentId === shell.environmentId && + previousValue.projectId === shell.projectId && + previousValue.modelSelection === shell.modelSelection && + previousValue.runtimeMode === shell.runtimeMode && + previousValue.interactionMode === shell.interactionMode && + previousValue.branch === shell.branch && + previousValue.worktreePath === shell.worktreePath && + previousValue.session === session + ) { + return previousValue; + } + previousValue = { + environmentId: shell.environmentId, + projectId: shell.projectId, + modelSelection: shell.modelSelection, + runtimeMode: shell.runtimeMode, + interactionMode: shell.interactionMode, + branch: shell.branch, + worktreePath: shell.worktreePath, + session, + }; + return previousValue; + }; +} + +/** + * Selects only the checkout and checkpoint diff summaries the diff panel reads, + * avoiding re-renders on streaming messages, activities, or `updatedAt` ticks. + */ +export function createThreadDiffContextSelectorByRef( + ref: ScopedThreadRef | null | undefined, +): (state: AppState) => ThreadDiffContextSlice | undefined { + let previousEnvironmentState: EnvironmentState | undefined; + let previousValue: ThreadDiffContextSlice | undefined; + + return (state) => { + if (!ref) { + return undefined; + } + const environmentState = selectEnvironmentState(state, ref.environmentId); + if (previousEnvironmentState === environmentState) { + return previousValue; + } + previousEnvironmentState = environmentState; + + const shell = environmentState.threadShellById[ref.threadId]; + if (!shell) { + previousValue = undefined; + return undefined; + } + const turnDiffSummaries = selectThreadTurnDiffSummaries(environmentState, ref.threadId); + if ( + previousValue !== undefined && + previousValue.id === shell.id && + previousValue.environmentId === shell.environmentId && + previousValue.projectId === shell.projectId && + previousValue.worktreePath === shell.worktreePath && + previousValue.effectiveCwd === shell.effectiveCwd && + previousValue.turnDiffSummaries === turnDiffSummaries + ) { + return previousValue; + } + previousValue = { + id: shell.id, + environmentId: shell.environmentId, + projectId: shell.projectId, + worktreePath: shell.worktreePath, + effectiveCwd: shell.effectiveCwd, + turnDiffSummaries, + }; + return previousValue; + }; +} + +/** + * Selects the route-level slice for the chat thread view, keeping the route + * shell quiet while assistant tokens and activities stream in. + */ +export function createThreadRouteSelectorByRef( + ref: ScopedThreadRef | null | undefined, +): (state: AppState) => ThreadRouteSlice | undefined { + let previousEnvironmentState: EnvironmentState | undefined; + let previousValue: ThreadRouteSlice | undefined; + + return (state) => { + if (!ref) { + return undefined; + } + const environmentState = selectEnvironmentState(state, ref.environmentId); + if (previousEnvironmentState === environmentState) { + return previousValue; + } + previousEnvironmentState = environmentState; + + const shell = environmentState.threadShellById[ref.threadId]; + if (!shell) { + previousValue = undefined; + return undefined; + } + const session = environmentState.threadSessionById[ref.threadId] ?? null; + const turnState = environmentState.threadTurnStateById[ref.threadId]; + const turnDiffSummaries = selectThreadTurnDiffSummaries(environmentState, ref.threadId); + const messageCount = selectThreadMessages(environmentState, ref.threadId).length; + const hasPromotableActivity = + (turnState?.latestTurn ?? null) !== null || + selectThreadActivities(environmentState, ref.threadId).length > 0 || + selectThreadProposedPlans(environmentState, ref.threadId).length > 0 || + turnDiffSummaries.length > 0 || + Boolean(shell.error) || + session?.status === "error" || + session?.orchestrationStatus === "error" || + session?.orchestrationStatus === "interrupted"; + + if ( + previousValue !== undefined && + previousValue.id === shell.id && + previousValue.environmentId === shell.environmentId && + previousValue.projectId === shell.projectId && + previousValue.branch === shell.branch && + previousValue.worktreePath === shell.worktreePath && + previousValue.effectiveCwd === shell.effectiveCwd && + previousValue.archivedAt === shell.archivedAt && + previousValue.linkedPullRequests === shell.linkedPullRequests && + previousValue.dismissedPullRequests === shell.dismissedPullRequests && + previousValue.pullRequestAutoFix === shell.pullRequestAutoFix && + previousValue.pullRequestAutoMerge === shell.pullRequestAutoMerge && + previousValue.turnDiffSummaries === turnDiffSummaries && + previousValue.messageCount === messageCount && + previousValue.hasPromotableActivity === hasPromotableActivity + ) { + return previousValue; + } + previousValue = { + id: shell.id, + environmentId: shell.environmentId, + projectId: shell.projectId, + branch: shell.branch, + worktreePath: shell.worktreePath, + effectiveCwd: shell.effectiveCwd, + archivedAt: shell.archivedAt, + ...(shell.linkedPullRequests !== undefined + ? { linkedPullRequests: shell.linkedPullRequests } + : {}), + ...(shell.dismissedPullRequests !== undefined + ? { dismissedPullRequests: shell.dismissedPullRequests } + : {}), + ...(shell.pullRequestAutoFix !== undefined + ? { pullRequestAutoFix: shell.pullRequestAutoFix } + : {}), + ...(shell.pullRequestAutoMerge !== undefined + ? { pullRequestAutoMerge: shell.pullRequestAutoMerge } + : {}), + turnDiffSummaries, + messageCount, + hasPromotableActivity, + }; + return previousValue; + }; +} + function createScopedThreadSelector( resolveRef: (state: AppState) => ScopedThreadRef | null | undefined, ): (state: AppState) => Thread | undefined { diff --git a/apps/web/src/theme/ThemeBackdropLayer.tsx b/apps/web/src/theme/ThemeBackdropLayer.tsx index e8497a2cb..f65ec820d 100644 --- a/apps/web/src/theme/ThemeBackdropLayer.tsx +++ b/apps/web/src/theme/ThemeBackdropLayer.tsx @@ -169,12 +169,16 @@ const EMPTY_LAYOUT: MeasuredBackdropLayout = { zones: [], artShown: true }; /** The new-thread screen, in either layout: its zones are patches around its text. */ const DRAFT_SCREEN_SELECTOR = "[data-draft-hero], [data-draft-stacked]"; +/** Screens whose backdrop patches hug individual text blocks rather than fixed boxes. */ +const TEXT_PATCH_SCREEN_SELECTOR = "[data-draft-hero], [data-draft-stacked], [data-empty-home]"; + const MEASURED_SELECTORS = [ '[data-slot="app-titlebar"]', '[data-slot="navigation-rail"]', '[data-slot="app-panel"]', '[data-slot="sidebar-inner"]', "[data-chat-column]", + "[data-timeline-root]", "[data-chat-composer-form]", "[data-glass-surface]", "[data-draft-hero]", @@ -189,6 +193,17 @@ const MEASURED_SELECTORS = [ ".thread-terminal-drawer", ].join(", "); +function recordsAffectBackdropLayout(records: readonly MutationRecord[]): boolean { + for (const record of records) { + if (record.type !== "childList") return true; + const target = record.target; + if (!(target instanceof Element) || target.closest("[data-timeline-root]") === null) { + return true; + } + } + return false; +} + function useBackdropLayout( tokens: ThemeTokens, floors: ReturnType, @@ -202,8 +217,46 @@ function useBackdropLayout( let lastRun = -Infinity; // The last measure was of a new-thread screen, whose patches hug its text. let draftPatches = false; + let observerInitialized = false; + let watchingTextPatchScreen = false; const observed = new Set(); + const syncTextPatchObservers = (nextWatching: boolean) => { + if (observerInitialized && nextWatching === watchingTextPatchScreen) return; + const wasWatching = watchingTextPatchScreen; + watchingTextPatchScreen = nextWatching; + if (observerInitialized) { + mutationObserver.disconnect(); + } + observerInitialized = true; + mutationObserver.observe(document.body, { + childList: true, + subtree: true, + // Text that changes in place (a project renamed elsewhere) can outgrow + // its patch without resizing anything that is watched; only needed on + // screens whose zones hug individual text blocks. + characterData: nextWatching, + attributes: true, + attributeFilter: [ + "data-state", + "data-sidebar-state", + "data-draft-hero", + "data-draft-stacked", + "data-chat-composer-mobile-collapsed", + "hidden", + ], + }); + if (nextWatching && !wasWatching) { + // The new-thread screen scrolls as one, carrying its patch with it. + document.addEventListener("scroll", schedule, { capture: true, passive: true }); + // Text that rises into place (the home screen's) settles where its patch belongs. + document.addEventListener("animationend", schedule); + } else if (!nextWatching && wasWatching) { + document.removeEventListener("scroll", schedule, { capture: true }); + document.removeEventListener("animationend", schedule); + } + }; + const measure = () => { frame = 0; lastRun = performance.now(); @@ -214,6 +267,9 @@ function useBackdropLayout( floors, ); draftPatches = document.querySelector(DRAFT_SCREEN_SELECTOR) !== null; + syncTextPatchObservers( + draftPatches || document.querySelector(TEXT_PATCH_SCREEN_SELECTOR) !== null, + ); setLayout((previous) => previous.artShown === next.artShown && sameBackdropZones(previous.zones, next.zones) ? previous @@ -266,31 +322,16 @@ function useBackdropLayout( }; const resizeObserver = new ResizeObserver(schedule); - const mutationObserver = new MutationObserver(schedule); - mutationObserver.observe(document.body, { - childList: true, - subtree: true, - // Text that changes in place (a project renamed elsewhere) can outgrow - // its patch without resizing anything that is watched. - characterData: true, - attributes: true, - attributeFilter: [ - "data-state", - "data-sidebar-state", - "data-draft-hero", - "data-draft-stacked", - "data-chat-composer-mobile-collapsed", - "hidden", - ], + const mutationObserver = new MutationObserver((records) => { + if (!watchingTextPatchScreen && !recordsAffectBackdropLayout(records)) { + return; + } + schedule(); }); window.addEventListener("resize", schedule); // A phone's keyboard shrinks and pans the visible page without resizing the window. window.visualViewport?.addEventListener("resize", schedule); window.visualViewport?.addEventListener("scroll", schedule); - // The new-thread screen scrolls as one, carrying its patch with it. - document.addEventListener("scroll", schedule, { capture: true, passive: true }); - // Text that rises into place (the home screen's) settles where its patch belongs. - document.addEventListener("animationend", schedule); measure(); return () => { if (frame !== 0) cancelAnimationFrame(frame); diff --git a/apps/web/src/threadDerivation.ts b/apps/web/src/threadDerivation.ts index 04a59f0b1..93c3a0cb1 100644 --- a/apps/web/src/threadDerivation.ts +++ b/apps/web/src/threadDerivation.ts @@ -67,15 +67,21 @@ function collectByIds( return nextValues; } -function selectThreadMessages(state: EnvironmentState, threadId: ThreadId): Thread["messages"] { +export function selectThreadMessages( + state: EnvironmentState, + threadId: ThreadId, +): Thread["messages"] { return state.messagesByThreadId[threadId] ?? EMPTY_MESSAGES; } -function selectThreadActivities(state: EnvironmentState, threadId: ThreadId): Thread["activities"] { +export function selectThreadActivities( + state: EnvironmentState, + threadId: ThreadId, +): Thread["activities"] { return state.activitiesByThreadId[threadId] ?? EMPTY_ACTIVITIES; } -function selectThreadProposedPlans( +export function selectThreadProposedPlans( state: EnvironmentState, threadId: ThreadId, ): Thread["proposedPlans"] { @@ -86,7 +92,7 @@ function selectThreadProposedPlans( ); } -function selectThreadTurnDiffSummaries( +export function selectThreadTurnDiffSummaries( state: EnvironmentState, threadId: ThreadId, ): Thread["turnDiffSummaries"] { diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts index 1d7b15e22..f8add9152 100644 --- a/apps/web/src/uiStateStore.test.ts +++ b/apps/web/src/uiStateStore.test.ts @@ -11,12 +11,14 @@ import { readLegacyInboxState, readPersistedState, reorderProjects, + resolveDoneOverlay, setDefaultAdvertisedEndpointKey, setProjectExpanded, setThreadChangedFilesExpanded, setThreadWrapUpOnPullRequestSettled, settleSeenOverlay, syncProjects, + syncThread, syncThreads, type UiState, } from "./uiStateStore"; @@ -811,4 +813,89 @@ describe("uiStateStore persistence round-trip", () => { expect(rehydrated.projectExpandedById[nextLogicalKey]).toBe(false); }); + + it("syncThread updates one thread incrementally and preserves reference identity on no-ops", () => { + const threadKey = "env-1:thread-1"; + const otherKey = "env-1:thread-2"; + const initial = makeUiState({ + threadSeedVisitedAtById: { [otherKey]: "2026-04-01T00:00:00.000Z" }, + seenThreadOverlays: { + [threadKey]: { + at: "2026-04-02T00:00:00.000Z", + baselineAt: "2026-04-01T00:00:00.000Z", + settled: true, + writeId: 1, + }, + [otherKey]: { + at: "2026-04-02T00:00:00.000Z", + baselineAt: "2026-04-01T00:00:00.000Z", + settled: true, + writeId: 2, + }, + }, + doneThreadOverlays: { + [threadKey]: { + state: "done", + at: "2026-04-02T00:00:00.000Z", + baselineAt: null, + settled: true, + }, + }, + }); + + const seeded = syncThread(initial, { + key: threadKey, + seedVisitedAt: "2026-04-01T00:00:00.000Z", + serverLastSeenAt: "2026-04-01T00:00:00.000Z", + serverDoneOverrideAt: null, + }); + expect(seeded.threadSeedVisitedAtById[threadKey]).toBe("2026-04-01T00:00:00.000Z"); + expect(seeded.seenThreadOverlays).toBe(initial.seenThreadOverlays); + expect(seeded.doneThreadOverlays).toBe(initial.doneThreadOverlays); + + const noop = syncThread(seeded, { + key: threadKey, + seedVisitedAt: "2026-04-03T00:00:00.000Z", + serverLastSeenAt: "2026-04-01T00:00:00.000Z", + serverDoneOverrideAt: null, + }); + expect(noop).toBe(seeded); + + const retired = syncThread(seeded, { + key: threadKey, + seedVisitedAt: "2026-04-03T00:00:00.000Z", + serverLastSeenAt: "2026-04-02T00:00:00.000Z", + serverDoneOverrideAt: "2026-04-02T00:00:00.000Z", + }); + expect(retired.seenThreadOverlays[threadKey]).toBeUndefined(); + expect(retired.seenThreadOverlays[otherKey]).toEqual(initial.seenThreadOverlays[otherKey]); + expect(retired.doneThreadOverlays[threadKey]).toBeUndefined(); + expect(retired.threadSeedVisitedAtById).toBe(seeded.threadSeedVisitedAtById); + }); + + it("resolveDoneOverlay retires immediately when the server already echoed past baseline", () => { + const threadKey = "env-1:thread-done-race"; + const at = "2026-04-02T00:00:00.000Z"; + const pending = makeUiState({ + doneThreadOverlays: { + [threadKey]: { + state: "done", + at, + baselineAt: null, + settled: false, + }, + }, + }); + + const stillPendingServer = resolveDoneOverlay(pending, threadKey, at, "confirmed", null); + expect(stillPendingServer.doneThreadOverlays[threadKey]).toEqual({ + state: "done", + at, + baselineAt: null, + settled: true, + }); + + const alreadyEchoed = resolveDoneOverlay(pending, threadKey, at, "confirmed", at); + expect(alreadyEchoed.doneThreadOverlays[threadKey]).toBeUndefined(); + }); }); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts index 101113191..08cb5a8ec 100644 --- a/apps/web/src/uiStateStore.ts +++ b/apps/web/src/uiStateStore.ts @@ -783,6 +783,54 @@ function shouldRetireOverlay( return overlay.settled && (serverAt ?? null) !== overlay.baselineAt; } +export function syncThread(state: UiState, thread: SyncThreadInput): UiState { + const seedVisitedAt = thread.seedVisitedAt; + const shouldAddSeed = + state.threadSeedVisitedAtById[thread.key] === undefined && + seedVisitedAt !== undefined && + seedVisitedAt.length > 0; + + const existingSeenOverlay = state.seenThreadOverlays[thread.key]; + const shouldRetireSeen = + existingSeenOverlay !== undefined && + shouldRetireOverlay(existingSeenOverlay, thread.serverLastSeenAt ?? null); + + const existingDoneOverlay = state.doneThreadOverlays[thread.key]; + const shouldRetireDone = + existingDoneOverlay !== undefined && + shouldRetireOverlay(existingDoneOverlay, thread.serverDoneOverrideAt ?? null); + + if (!shouldAddSeed && !shouldRetireSeen && !shouldRetireDone) { + return state; + } + + let nextSeenThreadOverlays = state.seenThreadOverlays; + if (shouldRetireSeen) { + const { [thread.key]: _removed, ...rest } = state.seenThreadOverlays; + nextSeenThreadOverlays = rest; + } + + let nextDoneThreadOverlays = state.doneThreadOverlays; + if (shouldRetireDone) { + const { [thread.key]: _removed, ...rest } = state.doneThreadOverlays; + nextDoneThreadOverlays = rest; + } + + return { + ...state, + ...(shouldAddSeed + ? { + threadSeedVisitedAtById: { + ...state.threadSeedVisitedAtById, + [thread.key]: seedVisitedAt, + }, + } + : {}), + seenThreadOverlays: nextSeenThreadOverlays, + doneThreadOverlays: nextDoneThreadOverlays, + }; +} + export function syncThreads( state: UiState, threads: readonly SyncThreadInput[], @@ -922,6 +970,7 @@ export function resolveDoneOverlay( threadKey: string, at: string, outcome: "confirmed" | "failed", + serverDoneOverrideAt?: string | null, ): UiState { const overlay = state.doneThreadOverlays[threadKey]; if (overlay === undefined || overlay.at !== at) { @@ -931,7 +980,12 @@ export function resolveDoneOverlay( if (outcome === "failed") { delete nextOverlays[threadKey]; } else { - nextOverlays[threadKey] = { ...overlay, settled: true }; + const settled: ThreadDoneOverlayWrite = { ...overlay, settled: true }; + if (serverDoneOverrideAt !== undefined && shouldRetireOverlay(settled, serverDoneOverrideAt)) { + delete nextOverlays[threadKey]; + } else { + nextOverlays[threadKey] = settled; + } } return { ...state, doneThreadOverlays: nextOverlays }; } @@ -1242,13 +1296,19 @@ function setSidebarListShown(state: T, open: boolean): interface UiStateStore extends UiState { syncProjects: (projects: readonly SyncProjectInput[]) => void; + syncThread: (thread: SyncThreadInput) => void; syncThreads: ( threads: readonly SyncThreadInput[], options?: { readonly loadedEnvironmentIds?: ReadonlySet }, ) => void; setDoneOverlay: (threadKey: string, overlay: ThreadDoneOverlayWrite) => void; setSeenOverlay: (threadKey: string, overlay: ThreadSeenOverlayWrite) => void; - resolveDoneOverlay: (threadKey: string, at: string, outcome: "confirmed" | "failed") => void; + resolveDoneOverlay: ( + threadKey: string, + at: string, + outcome: "confirmed" | "failed", + serverDoneOverrideAt?: string | null, + ) => void; settleSeenOverlay: ( threadKey: string, writeId: number, @@ -1286,11 +1346,12 @@ interface UiStateStore extends UiState { export const useUiStateStore = create((set) => ({ ...readPersistedState(), syncProjects: (projects) => set((state) => syncProjects(state, projects)), + syncThread: (thread) => set((state) => syncThread(state, thread)), syncThreads: (threads, options) => set((state) => syncThreads(state, threads, options)), setDoneOverlay: (threadKey, overlay) => set((state) => setDoneOverlay(state, threadKey, overlay)), setSeenOverlay: (threadKey, overlay) => set((state) => setSeenOverlay(state, threadKey, overlay)), - resolveDoneOverlay: (threadKey, at, outcome) => - set((state) => resolveDoneOverlay(state, threadKey, at, outcome)), + resolveDoneOverlay: (threadKey, at, outcome, serverDoneOverrideAt) => + set((state) => resolveDoneOverlay(state, threadKey, at, outcome, serverDoneOverrideAt)), settleSeenOverlay: (threadKey, writeId, outcome) => set((state) => settleSeenOverlay(state, threadKey, writeId, outcome)), setInboxProjectScope: (projectKeys) => From d77f0e446794bdd4faaabdd00c0ae66c7e7f8a11 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:02:46 -0500 Subject: [PATCH 3/4] perf: deduplicate checkpoints, share shell fanout, and move hot writes async Reduces checkpoint git overhead, WebSocket fanout work, retained evicted thread memory, idle reveal animation frames, and blocking main-thread log and cache writes. - Coordinate pre-turn checkpoints across ProviderCommandReactor and CheckpointReactor, shard checkpoint work across threads with per-checkout revert serialization, and cache stable git lookups in scratchIndex. - Share one coalesced shell stream producer across WebSocket clients, bound shell and thread subscriber queues with clean resync on overflow, and return only the sequence on event store appends. - Release evicted thread detail slices and derivation caches while pausing idle eviction offline and preserving pending scroll anchors and worktree locks. - Create streaming text reveal observers lazily, stop idle animation frames when caught up, and advance only the live reveal tail. - Move rotating trace and provider logs to fs.promises with per-path rotation locks and shutdown flush, batch desktop child logs, optimize terminal ANSI scans and output bursts, compact usage rate caches, and debounce usage scan cache writes. --- apps/desktop/src/app/DesktopObservability.ts | 112 +++- .../orchestration/Layers/CheckpointReactor.ts | 499 +++++++++++------- .../Layers/ProviderCommandReactor.ts | 84 ++- .../orchestration/checkpointHandover.test.ts | 52 ++ .../src/orchestration/checkpointHandover.ts | 72 +++ .../Layers/OrchestrationEventStore.ts | 21 +- .../provider/Layers/EventNdjsonLogger.test.ts | 56 +- .../src/provider/Layers/EventNdjsonLogger.ts | 210 ++++---- .../provider/Layers/ProviderEventLoggers.ts | 5 + apps/server/src/terminal/Layers/Manager.ts | 86 ++- apps/server/src/usage/UsageService.test.ts | 15 + apps/server/src/usage/UsageService.ts | 120 ++++- apps/server/src/usage/usagePricing.ts | 35 ++ apps/server/src/vcs/scratchIndex.ts | 177 ++++--- apps/server/src/ws.ts | 397 +++++++++----- apps/web/src/components/ChatView.tsx | 11 +- .../src/components/chat/MessagesTimeline.tsx | 13 +- .../runtime/threadDetailSubscriptions.ts | 16 +- .../hooks/useStreamingTextReveal.browser.tsx | 34 ++ apps/web/src/hooks/useStreamingTextReveal.ts | 201 +++++-- apps/web/src/lib/derivationMemo.ts | 20 + apps/web/src/store.test.ts | 11 +- apps/web/src/store.ts | 105 +++- apps/web/src/threadDerivation.ts | 6 + packages/shared/src/DrainableWorker.test.ts | 58 +- packages/shared/src/DrainableWorker.ts | 168 ++++++ packages/shared/src/logging.ts | 137 +++++ packages/shared/src/observability.test.ts | 58 +- packages/shared/src/observability.ts | 193 ++++--- 29 files changed, 2259 insertions(+), 713 deletions(-) diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts index 0e7daa302..acf206d8b 100644 --- a/apps/desktop/src/app/DesktopObservability.ts +++ b/apps/desktop/src/app/DesktopObservability.ts @@ -4,6 +4,7 @@ import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; @@ -13,6 +14,7 @@ import * as PlatformError from "effect/PlatformError"; import * as References from "effect/References"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Tracer from "effect/Tracer"; import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/observability"; @@ -22,6 +24,8 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts"; const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024; const DESKTOP_LOG_FILE_MAX_FILES = 10; +const DESKTOP_LOG_BATCH_WINDOW_MS = 25; +const DESKTOP_LOG_BATCH_MAX_BYTES = 16 * 1024; const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child"; const DESKTOP_TRACE_BATCH_WINDOW_MS = 200; @@ -50,6 +54,7 @@ ignoreDevelopmentConsoleBrokenPipe(process.stderr); export interface RotatingLogFileWriter { readonly writeBytes: (chunk: Uint8Array) => Effect.Effect; readonly writeText: (chunk: string) => Effect.Effect; + readonly flush: Effect.Effect; } export interface DesktopBackendOutputLogShape { @@ -162,10 +167,11 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio }): Effect.fn.Return< RotatingLogFileWriter, DesktopLogFileWriterError, - FileSystem.FileSystem | Path.Path + FileSystem.FileSystem | Path.Path | Scope.Scope > { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const writerScope = yield* Scope.Scope; const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES; const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES; const directory = path.dirname(input.filePath); @@ -189,6 +195,10 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio const withSuffix = (index: number) => `${input.filePath}.${index}`; const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath)); const mutex = yield* Semaphore.make(1); + let pendingChunks: Array = []; + let pendingBytes = 0; + let flushTimer: Fiber.Fiber | null = null; + let closed = false; const pruneOverflowBackups = Effect.gen(function* () { const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); @@ -224,38 +234,99 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio ), ); + const writeCombinedLocked = (combined: Uint8Array): Effect.Effect => + Effect.gen(function* () { + const beforeSize = yield* Ref.get(currentSize); + if (beforeSize > 0 && beforeSize + combined.byteLength > maxBytes) { + yield* rotate; + } + + yield* fileSystem.writeFile(input.filePath, combined, { flag: "a" }); + const afterSize = (yield* Ref.get(currentSize)) + combined.byteLength; + yield* Ref.set(currentSize, afterSize); + + if (afterSize > maxBytes) { + yield* rotate; + } + }).pipe( + Effect.catch(() => + refreshFileSize(fileSystem, input.filePath).pipe( + Effect.flatMap((size) => Ref.set(currentSize, size)), + ), + ), + ); + + const flushPending: Effect.Effect = mutex.withPermits(1)( + Effect.gen(function* () { + if (pendingChunks.length === 0) { + return; + } + const chunks = pendingChunks; + const totalBytes = pendingBytes; + pendingChunks = []; + pendingBytes = 0; + + let combined: Uint8Array; + if (chunks.length === 1) { + combined = chunks[0]!; + } else { + combined = new Uint8Array(totalBytes); + let offset = 0; + for (const chunk of chunks) { + combined.set(chunk, offset); + offset += chunk.byteLength; + } + } + yield* writeCombinedLocked(combined); + }).pipe(Effect.uninterruptible), + ); + + const flush: Effect.Effect = Effect.gen(function* () { + const timer = flushTimer; + flushTimer = null; + if (timer !== null) { + yield* Fiber.interrupt(timer).pipe(Effect.ignore); + } + yield* flushPending; + }); + const writeBytes = (chunk: Uint8Array): Effect.Effect => { if (chunk.byteLength === 0) return Effect.void; - return mutex.withPermits(1)( - Effect.gen(function* () { - const beforeSize = yield* Ref.get(currentSize); - if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) { - yield* rotate; - } + return Effect.gen(function* () { + pendingChunks.push(chunk); + pendingBytes += chunk.byteLength; - yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" }); - const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength; - yield* Ref.set(currentSize, afterSize); + if (closed || pendingBytes >= DESKTOP_LOG_BATCH_MAX_BYTES) { + yield* flush; + return; + } - if (afterSize > maxBytes) { - yield* rotate; - } - }).pipe( - Effect.catch(() => - refreshFileSize(fileSystem, input.filePath).pipe( - Effect.flatMap((size) => Ref.set(currentSize, size)), + if (flushTimer === null) { + flushTimer = yield* Effect.sleep(`${DESKTOP_LOG_BATCH_WINDOW_MS} millis`).pipe( + Effect.andThen( + Effect.gen(function* () { + flushTimer = null; + yield* flushPending; + }), ), - ), - ), - ); + Effect.forkIn(writerScope), + ); + } + }); }; yield* pruneOverflowBackups; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + closed = true; + }).pipe(Effect.andThen(flush), Effect.ignore), + ); return { writeBytes, writeText: (chunk) => writeBytes(textEncoder.encode(chunk)), + flush, } satisfies RotatingLogFileWriter; }); @@ -350,6 +421,7 @@ const backendOutputLogLayer = Layer.effect( details: sanitizeLogValue(details), }, }); + yield* logFile.flush; }), writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")( function* (streamName, chunk) { diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 75a36a1b7..928037cf3 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -28,11 +28,12 @@ import { } from "@threadlines/shared/threadParticipants"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import { settingsChangeTurnsRevertKeeps } from "../settingsChangeDecisions.ts"; import { turnAdmission } from "../turnAdmission.ts"; import { checkpointHandover } from "../checkpointHandover.ts"; -import { makeDrainableWorker } from "@threadlines/shared/DrainableWorker"; +import { makeKeyedDrainableWorker } from "@threadlines/shared/DrainableWorker"; import { normalizeWorkspacePath } from "@threadlines/shared/path"; import { compareTranscriptOrder } from "@threadlines/shared/transcriptOrder"; @@ -1076,24 +1077,50 @@ const make = Effect.gen(function* () { 0, ); const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); const preTurnCheckpointRef = checkpointPreTurnRefForThreadTurn(thread.id, turnId); - const preTurnCheckpointExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: preTurnCheckpointRef, - }); - yield* captureBaselineWith({ - cwd: checkpointCwd, - threadId: thread.id, - turnCount: currentTurnCount, - baselineRef: baselineCheckpointRef, - baselineExists, - preTurnRef: preTurnCheckpointExists ? undefined : preTurnCheckpointRef, - createdAt: event.createdAt, - }); + yield* checkpointHandover.withPreTurnLock(thread.id, (preTurn) => + Effect.gen(function* () { + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + // Only consume `pre/turn/` when ProviderCommandReactor actively + // dispatched this turn start to the provider: a failed request or a + // direct runtime `turn.started` after checkout edits must take a fresh + // `pre/` baseline instead of inheriting an older capture. + const latest = preTurn.getLatest(); + if ( + baselineExists && + latest !== null && + latest.sentToProvider && + latest.consumedByTurnId === null && + latest.cwd === checkpointCwd && + latest.turnCount === currentTurnCount + 1 + ) { + const latestExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: latest.checkpointRef as CheckpointRef, + }); + if (latestExists) { + latest.consumedByTurnId = turnId; + return; + } + } + const preTurnCheckpointExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: preTurnCheckpointRef, + }); + yield* captureBaselineWith({ + cwd: checkpointCwd, + threadId: thread.id, + turnCount: currentTurnCount, + baselineRef: baselineCheckpointRef, + baselineExists, + preTurnRef: preTurnCheckpointExists ? undefined : preTurnCheckpointRef, + createdAt: event.createdAt, + }); + }), + ); }, ); @@ -1159,19 +1186,13 @@ const make = Effect.gen(function* () { (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), 0, ); + const nextTurnCount = currentTurnCount + 1; const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: baselineCheckpointRef, - }); const preTurnCountCheckpointRef = checkpointPreTurnRefForThreadTurnCount( threadId, - currentTurnCount + 1, + nextTurnCount, ); - const preTurnCountCheckpointExists = yield* checkpointStore.hasCheckpointRef({ - cwd: checkpointCwd, - checkpointRef: preTurnCountCheckpointRef, - }); + const requestKey = `${event.commandId ?? ""}:${event.payload.messageId}:${event.payload.createdAt}`; // A snapshot left by an earlier request that never became a turn (the // provider failed to start) would stretch this turn's diff back to that // attempt, claiming everything that changed in the checkout since. Each @@ -1185,141 +1206,212 @@ const make = Effect.gen(function* () { (event.type === "thread.message-sent" || thread.messages.find((message) => message.id === event.payload.messageId)?.createdAt !== event.payload.createdAt); - yield* captureBaselineWith({ - cwd: checkpointCwd, - threadId, - turnCount: currentTurnCount, - baselineRef: baselineCheckpointRef, - baselineExists, - preTurnRef: - !preTurnCountCheckpointExists || retakesSnapshot ? preTurnCountCheckpointRef : undefined, - createdAt: event.occurredAt, - }); + + yield* checkpointHandover.withPreTurnLock(threadId, (preTurn) => + Effect.gen(function* () { + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: baselineCheckpointRef, + }); + const preTurnCountCheckpointExists = yield* checkpointStore.hasCheckpointRef({ + cwd: checkpointCwd, + checkpointRef: preTurnCountCheckpointRef, + }); + const latest = preTurn.getLatest(); + const alreadyCapturedForRequest = + latest !== null && + latest.consumedByTurnId === null && + latest.cwd === checkpointCwd && + latest.turnCount === nextTurnCount && + latest.requestKey === requestKey && + preTurnCountCheckpointExists; + const shouldCapturePreTurn = + !alreadyCapturedForRequest && (!preTurnCountCheckpointExists || retakesSnapshot); + yield* captureBaselineWith({ + cwd: checkpointCwd, + threadId, + turnCount: currentTurnCount, + baselineRef: baselineCheckpointRef, + baselineExists, + preTurnRef: shouldCapturePreTurn ? preTurnCountCheckpointRef : undefined, + createdAt: event.occurredAt, + }); + if (shouldCapturePreTurn) { + preTurn.setLatest({ + cwd: checkpointCwd, + turnCount: nextTurnCount, + requestKey, + checkpointRef: preTurnCountCheckpointRef, + sentToProvider: false, + consumedByTurnId: null, + }); + } + }), + ); }); + const checkoutRevertLocks = new Map(); + const revertLockFor = (cwd: string) => + Effect.gen(function* () { + const normalized = normalizeWorkspacePath(cwd); + const existing = checkoutRevertLocks.get(normalized); + if (existing !== undefined) { + return existing; + } + const created = yield* Semaphore.make(1); + checkoutRevertLocks.set(normalized, created); + return created; + }); + const handleRevertRequested = Effect.fn("handleRevertRequested")(function* ( event: Extract, ) { - const now = DateTime.formatIso(yield* DateTime.now); - const failRevert = (detail: string) => - appendRevertFailureActivity({ + const runRevert = Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const failRevert = (detail: string) => + appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail, + createdAt: now, + }).pipe( + Effect.catch(() => Effect.void), + Effect.asVoid, + ); + + const contextResult = yield* checkpointRevert.resolveContext({ threadId: event.payload.threadId, turnCount: event.payload.turnCount, - detail, - createdAt: now, - }).pipe( - Effect.catch(() => Effect.void), - Effect.asVoid, - ); - - const contextResult = yield* checkpointRevert.resolveContext({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - }); - if (contextResult.kind === "unavailable") { - yield* failRevert(contextResult.detail); - return; - } - const context = contextResult.context; + }); + if (contextResult.kind === "unavailable") { + yield* failRevert(contextResult.detail); + return; + } + const context = contextResult.context; - const rolledBackTurns = Math.max(0, context.currentTurnCount - event.payload.turnCount); - const targetUserMessageId = targetUserMessageIdForCheckpointRewind({ - thread: context.thread, - targetTurnCount: event.payload.turnCount, - }); - // An agent that forgets by starting over (Antigravity) is stopped, and - // its conversation forgotten, before any file is restored: a command it - // still ran could otherwise write over a restored file. Nothing is - // started for an agent that isn't running. - // The lookup fails only when the thread's provider instance is no longer - // registered (removed or turned off). Removing an instance ends its - // runtimes, so nothing of it can still write: the files are restored as - // for an agent that isn't running. - const capabilities = - rolledBackTurns > 0 + const rolledBackTurns = Math.max(0, context.currentTurnCount - event.payload.turnCount); + const targetUserMessageId = targetUserMessageIdForCheckpointRewind({ + thread: context.thread, + targetTurnCount: event.payload.turnCount, + }); + // An agent that forgets by starting over (Antigravity) is stopped, and + // its conversation forgotten, before any file is restored: a command it + // still ran could otherwise write over a restored file. Nothing is + // started for an agent that isn't running. + // The lookup fails only when the thread's provider instance is no longer + // registered (removed or turned off). Removing an instance ends its + // runtimes, so nothing of it can still write: the files are restored as + // for an agent that isn't running. + const capabilities = + rolledBackTurns > 0 + ? yield* Effect.result( + providerService.getCapabilities( + context.thread.session?.providerInstanceId ?? + context.thread.modelSelection.instanceId, + ), + ) + : undefined; + const startsOver = + capabilities?._tag === "Success" && + capabilities.success.conversationRollback === "new-session"; + // Undefined: not such an agent. A failure means it couldn't be found or + // stopped: something it runs could still write, so no file is restored. + const stopped = startsOver ? yield* Effect.result( - providerService.getCapabilities( - context.thread.session?.providerInstanceId ?? - context.thread.modelSelection.instanceId, - ), + providerService.rollbackConversation({ + threadId: event.payload.threadId, + numTurns: rolledBackTurns, + ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), + }), ) : undefined; - const startsOver = - capabilities?._tag === "Success" && - capabilities.success.conversationRollback === "new-session"; - // Undefined: not such an agent. A failure means it couldn't be found or - // stopped: something it runs could still write, so no file is restored. - const stopped = startsOver - ? yield* Effect.result( - providerService.rollbackConversation({ - threadId: event.payload.threadId, - numTurns: rolledBackTurns, - ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), - }), - ) - : undefined; - if (stopped !== undefined && stopped._tag === "Failure") { - yield* Effect.logWarning("checkpoint revert could not stop the agent", { - threadId: event.payload.threadId, - cause: String(stopped.failure), - }); - yield* failRevert( - "The agent couldn't be stopped, so no file was restored: something it runs could still write to them. Stop it and try again.", - ); - return; - } - const startedOver = - stopped?._tag === "Success" ? stopped.success.conversationRolledBack : undefined; - - const restored = yield* Effect.result(checkpointRevert.applyRevert(context)); - const revertOutcome = restored._tag === "Success" ? restored.success : null; - if (revertOutcome === null) { - const filesDetail = - restored._tag === "Failure" - ? restored.failure.message - : `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`; - // Both facts: the agent already forgot, the files stayed as they were. - yield* failRevert( - startedOver === true - ? `${filesDetail} The agent's conversation was already reset: it no longer remembers the turns after this point.` - : filesDetail, - ); - return; - } + if (stopped !== undefined && stopped._tag === "Failure") { + yield* Effect.logWarning("checkpoint revert could not stop the agent", { + threadId: event.payload.threadId, + cause: String(stopped.failure), + }); + yield* failRevert( + "The agent couldn't be stopped, so no file was restored: something it runs could still write to them. Stop it and try again.", + ); + return; + } + const startedOver = + stopped?._tag === "Success" ? stopped.success.conversationRolledBack : undefined; + + const restored = yield* Effect.result(checkpointRevert.applyRevert(context)); + const revertOutcome = restored._tag === "Success" ? restored.success : null; + if (revertOutcome === null) { + const filesDetail = + restored._tag === "Failure" + ? restored.failure.message + : `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`; + // Both facts: the agent already forgot, the files stayed as they were. + yield* failRevert( + startedOver === true + ? `${filesDetail} The agent's conversation was already reset: it no longer remembers the turns after this point.` + : filesDetail, + ); + return; + } - // Invalidate the workspace entry cache so the @-mention file picker - // reflects the reverted filesystem state. - yield* workspaceEntries.invalidate(context.cwd); - - yield* appendRevertOutcomeActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - outcome: revertOutcome, - createdAt: now, - }).pipe(Effect.catch(() => Effect.void)); - - if (rolledBackTurns > 0) { - if (startsOver || context.hasProviderSession) { - const rollback = - startedOver !== undefined - ? { conversationRolledBack: startedOver } - : yield* providerService.rollbackConversation({ + // Invalidate the workspace entry cache so the @-mention file picker + // reflects the reverted filesystem state. + yield* workspaceEntries.invalidate(context.cwd); + + yield* appendRevertOutcomeActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + outcome: revertOutcome, + createdAt: now, + }).pipe(Effect.catch(() => Effect.void)); + + if (rolledBackTurns > 0) { + if (startsOver || context.hasProviderSession) { + const rollback = + startedOver !== undefined + ? { conversationRolledBack: startedOver } + : yield* providerService.rollbackConversation({ + threadId: event.payload.threadId, + numTurns: rolledBackTurns, + ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), + }); + if (!rollback.conversationRolledBack) { + yield* orchestrationEngine + .dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("checkpoint-revert-rollback-unsupported"), threadId: event.payload.threadId, - numTurns: rolledBackTurns, - ...(targetUserMessageId !== undefined ? { targetUserMessageId } : {}), - }); - if (!rollback.conversationRolledBack) { + activity: { + id: EventId.make(crypto.randomUUID()), + tone: "warning", + kind: "checkpoint.revert.rollback-unsupported", + summary: + "Files were reverted, but this agent can't forget the reverted turns: it still remembers them.", + payload: { + turnCount: event.payload.turnCount, + rolledBackTurns, + }, + turnId: null, + createdAt: now, + }, + createdAt: now, + }) + .pipe(Effect.catch(() => Effect.void)); + } + } else { + // Files can revert without a live session, but provider conversation + // state cannot; surface it instead of failing the whole revert. yield* orchestrationEngine .dispatch({ type: "thread.activity.append", - commandId: serverCommandId("checkpoint-revert-rollback-unsupported"), + commandId: serverCommandId("checkpoint-revert-rollback-skipped"), threadId: event.payload.threadId, activity: { id: EventId.make(crypto.randomUUID()), tone: "warning", - kind: "checkpoint.revert.rollback-unsupported", + kind: "checkpoint.revert.rollback-skipped", summary: - "Files were reverted, but this agent can't forget the reverted turns: it still remembers them.", + "Provider conversation was not rolled back: no active session. The provider may still remember reverted turns.", payload: { turnCount: event.payload.turnCount, rolledBackTurns, @@ -1331,71 +1423,71 @@ const make = Effect.gen(function* () { }) .pipe(Effect.catch(() => Effect.void)); } - } else { - // Files can revert without a live session, but provider conversation - // state cannot; surface it instead of failing the whole revert. - yield* orchestrationEngine - .dispatch({ - type: "thread.activity.append", - commandId: serverCommandId("checkpoint-revert-rollback-skipped"), - threadId: event.payload.threadId, - activity: { - id: EventId.make(crypto.randomUUID()), - tone: "warning", - kind: "checkpoint.revert.rollback-skipped", - summary: - "Provider conversation was not rolled back: no active session. The provider may still remember reverted turns.", - payload: { - turnCount: event.payload.turnCount, - rolledBackTurns, - }, - turnId: null, - createdAt: now, - }, - createdAt: now, - }) - .pipe(Effect.catch(() => Effect.void)); } - } - const staleCheckpointRefs = context.thread.checkpoints - .filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount) - .flatMap((checkpoint) => [ - checkpoint.checkpointRef, - checkpointPreTurnRefForThreadTurn(event.payload.threadId, checkpoint.turnId), - checkpointPreTurnRefForThreadTurnCount( - event.payload.threadId, - checkpoint.checkpointTurnCount, - ), - ]); + const staleCheckpointRefs = context.thread.checkpoints + .filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount) + .flatMap((checkpoint) => [ + checkpoint.checkpointRef, + checkpointPreTurnRefForThreadTurn(event.payload.threadId, checkpoint.turnId), + checkpointPreTurnRefForThreadTurnCount( + event.payload.threadId, + checkpoint.checkpointTurnCount, + ), + ]); - if (staleCheckpointRefs.length > 0) { - yield* checkpointStore.deleteCheckpointRefs({ - cwd: context.cwd, - checkpointRefs: staleCheckpointRefs, - }); + if (staleCheckpointRefs.length > 0) { + yield* checkpointStore.deleteCheckpointRefs({ + cwd: context.cwd, + checkpointRefs: staleCheckpointRefs, + }); + } + yield* checkpointHandover.clearPreTurn(event.payload.threadId); + + yield* orchestrationEngine + .dispatch({ + type: "thread.revert.complete", + commandId: serverCommandId("checkpoint-revert-complete"), + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + keptTurnIds: settingsChangeTurnsRevertKeeps(context.thread, event.payload.turnCount), + createdAt: now, + }) + .pipe( + Effect.catch((error) => + appendRevertFailureActivity({ + threadId: event.payload.threadId, + turnCount: event.payload.turnCount, + detail: error.message, + createdAt: now, + }), + ), + Effect.asVoid, + ); + }); + + // Serialize reverts per physical checkout across concurrent thread lanes so + // two threads sharing one working tree cannot interleave selective file edits. + const threadForLock = yield* resolveThreadDetail(event.payload.threadId); + const projectsForLock = threadForLock + ? yield* resolveThreadProjects(threadForLock.projectId) + : []; + const lockCwd = threadForLock + ? yield* resolveCheckpointCwd({ + threadId: event.payload.threadId, + thread: threadForLock, + projects: projectsForLock, + preferSessionRuntime: true, + }) + : null; + + if (!lockCwd) { + yield* runRevert; + return; } - yield* orchestrationEngine - .dispatch({ - type: "thread.revert.complete", - commandId: serverCommandId("checkpoint-revert-complete"), - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - keptTurnIds: settingsChangeTurnsRevertKeeps(context.thread, event.payload.turnCount), - createdAt: now, - }) - .pipe( - Effect.catch((error) => - appendRevertFailureActivity({ - threadId: event.payload.threadId, - turnCount: event.payload.turnCount, - detail: error.message, - createdAt: now, - }), - ), - Effect.asVoid, - ); + const revertLock = yield* revertLockFor(lockCwd); + yield* revertLock.withPermits(1)(runRevert); }); const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) { @@ -1528,7 +1620,10 @@ const make = Effect.gen(function* () { }), ); - const worker = yield* makeDrainableWorker(processInputSafely); + const worker = yield* makeKeyedDrainableWorker(processInputSafely, { + keyOf: (input) => (input.source === "domain" ? input.event.aggregateId : input.event.threadId), + maxConcurrency: 4, + }); const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () { yield* Effect.forkScoped( diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index eea056ebe..8809e532c 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -3209,7 +3209,12 @@ const make = Effect.gen(function* () { ); const capturePreTurnCheckpointForTurnStart = Effect.fn("capturePreTurnCheckpointForTurnStart")( - function* (input: { readonly threadId: ThreadId }) { + function* (input: { + readonly threadId: ThreadId; + readonly commandId: CommandId | null; + readonly messageId: MessageId; + readonly createdAt: string; + }) { const thread = yield* resolveThread(input.threadId); if (!thread) { return; @@ -3244,28 +3249,56 @@ const make = Effect.gen(function* () { (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount), 0, ); + const nextTurnCount = currentTurnCount + 1; const baselineCheckpointRef = checkpointRefForThreadTurn(input.threadId, currentTurnCount); - const baselineExists = yield* checkpointStore.hasCheckpointRef({ - cwd, - checkpointRef: baselineCheckpointRef, - }); const preTurnCountCheckpointRef = checkpointPreTurnRefForThreadTurnCount( input.threadId, - currentTurnCount + 1, + nextTurnCount, + ); + const requestKey = `${input.commandId ?? ""}:${input.messageId}:${input.createdAt}`; + const turnInFlight = thread.latestTurn?.state === "running"; + + yield* checkpointHandover.withPreTurnLock(input.threadId, (preTurn) => + Effect.gen(function* () { + const baselineExists = yield* checkpointStore.hasCheckpointRef({ + cwd, + checkpointRef: baselineCheckpointRef, + }); + const preTurnCountCheckpointExists = yield* checkpointStore.hasCheckpointRef({ + cwd, + checkpointRef: preTurnCountCheckpointRef, + }); + const latest = preTurn.getLatest(); + const alreadyCapturedForRequest = + latest !== null && + latest.consumedByTurnId === null && + latest.cwd === cwd && + latest.turnCount === nextTurnCount && + latest.requestKey === requestKey && + preTurnCountCheckpointExists; + const shouldCapturePreTurn = + !alreadyCapturedForRequest && (!preTurnCountCheckpointExists || !turnInFlight); + // Both missing (a thread's first message): nothing happens between them, + // so they are one snapshot, and the message waits for one capture. + const [checkpointRef, ...alsoCheckpointRefs] = [ + ...(baselineExists ? [] : [baselineCheckpointRef]), + ...(shouldCapturePreTurn ? [preTurnCountCheckpointRef] : []), + ]; + if (checkpointRef !== undefined) { + yield* checkpointStore.captureCheckpoint({ cwd, checkpointRef, alsoCheckpointRefs }); + if (shouldCapturePreTurn) { + preTurn.setLatest({ + cwd, + turnCount: nextTurnCount, + requestKey, + checkpointRef: preTurnCountCheckpointRef, + sentToProvider: false, + consumedByTurnId: null, + }); + } + } + }), ); - const preTurnCountCheckpointExists = yield* checkpointStore.hasCheckpointRef({ - cwd, - checkpointRef: preTurnCountCheckpointRef, - }); - // Both missing (a thread's first message): nothing happens between them, - // so they are one snapshot, and the message waits for one capture. - const [checkpointRef, ...alsoCheckpointRefs] = [ - ...(baselineExists ? [] : [baselineCheckpointRef]), - ...(preTurnCountCheckpointExists ? [] : [preTurnCountCheckpointRef]), - ]; - if (checkpointRef !== undefined) { - yield* checkpointStore.captureCheckpoint({ cwd, checkpointRef, alsoCheckpointRefs }); - } }, ); @@ -3903,9 +3936,13 @@ const make = Effect.gen(function* () { return; } + const preTurnRequestKey = `${event.commandId ?? ""}:${event.payload.messageId}:${event.payload.createdAt}`; const checkpointStartedAtMs = yield* Clock.currentTimeMillis; const checkpointFailed = yield* capturePreTurnCheckpointForTurnStart({ threadId: event.payload.threadId, + commandId: event.commandId, + messageId: event.payload.messageId, + createdAt: event.payload.createdAt, }).pipe( Effect.as(false), Effect.catchCause((cause) => @@ -3936,6 +3973,7 @@ const make = Effect.gen(function* () { // computer may have taken the request back meanwhile too, or the user // may have written over a continue. if ((yield* stoppedSinceRequested) || (yield* remoteTurnHeld) || (yield* continueOvertaken)) { + yield* checkpointHandover.clearPreTurn(event.payload.threadId); return; } // The turn request already recorded the model it expected to go out. @@ -3970,6 +4008,7 @@ const make = Effect.gen(function* () { let contextDeferred = false; const suggestionThread = origin === "person" ? thread : ((yield* resolveThread(event.payload.threadId)) ?? thread); + yield* checkpointHandover.markPreTurnSent(event.payload.threadId, preTurnRequestKey); yield* providerService .sendTurn({ ...turnRequest, @@ -4046,7 +4085,12 @@ const make = Effect.gen(function* () { ), }), ), - Effect.catchCause((cause) => recoverTurnStartFailure(cause, !providerTookTurn)), + Effect.catchCause((cause) => + (providerTookTurn + ? Effect.void + : checkpointHandover.clearPreTurn(event.payload.threadId) + ).pipe(Effect.andThen(recoverTurnStartFailure(cause, !providerTookTurn))), + ), Effect.forkScoped, ); }); diff --git a/apps/server/src/orchestration/checkpointHandover.test.ts b/apps/server/src/orchestration/checkpointHandover.test.ts index 18af34455..24c81b4f5 100644 --- a/apps/server/src/orchestration/checkpointHandover.test.ts +++ b/apps/server/src/orchestration/checkpointHandover.test.ts @@ -81,4 +81,56 @@ describe("checkpointHandover", () => { await run(checkpointHandover.handOver(thread, "turn-before-restart", Duration.seconds(10))); expect(Date.now() - started).toBeLessThan(1_000); }); + + it("serializes pre-turn capture coordination per thread and clears it on reset", async () => { + const thread = "thread-preturn-1"; + const events: string[] = []; + await run( + Effect.gen(function* () { + const entered = yield* Deferred.make(); + const release = yield* Deferred.make(); + const first = yield* checkpointHandover + .withPreTurnLock(thread, (gate) => + Effect.gen(function* () { + events.push("first-enter"); + yield* Deferred.succeed(entered, undefined); + yield* Deferred.await(release); + gate.setLatest({ + cwd: "/repo", + turnCount: 1, + requestKey: "cmd-1:msg-1:t1", + checkpointRef: "refs/t3/checkpoints/thread-preturn-1/pre/turn/1", + sentToProvider: false, + consumedByTurnId: null, + }); + events.push("first-exit"); + }), + ) + .pipe(Effect.forkChild); + + yield* Deferred.await(entered); + const second = yield* checkpointHandover + .withPreTurnLock(thread, (gate) => + Effect.sync(() => { + events.push(`second-saw:${gate.getLatest()?.requestKey ?? "none"}`); + }), + ) + .pipe(Effect.forkChild); + + yield* Effect.sleep(Duration.millis(15)); + expect(events).toEqual(["first-enter"]); + yield* Deferred.succeed(release, undefined); + yield* Fiber.join(first); + yield* Fiber.join(second); + }), + ); + + expect(events).toEqual(["first-enter", "first-exit", "second-saw:cmd-1:msg-1:t1"]); + + await run(checkpointHandover.clearPreTurn(thread)); + const afterClear = await run( + checkpointHandover.withPreTurnLock(thread, (gate) => Effect.succeed(gate.getLatest())), + ); + expect(afterClear).toBeNull(); + }); }); diff --git a/apps/server/src/orchestration/checkpointHandover.ts b/apps/server/src/orchestration/checkpointHandover.ts index 3bfe4e3d1..3998a1235 100644 --- a/apps/server/src/orchestration/checkpointHandover.ts +++ b/apps/server/src/orchestration/checkpointHandover.ts @@ -35,8 +35,25 @@ export const HandoverCaptureWait = Context.Reference( { defaultValue: () => Duration.seconds(10) }, ); +export interface LatestPreTurnCapture { + readonly cwd: string; + readonly turnCount: number; + readonly requestKey: string; + readonly checkpointRef: string; + sentToProvider: boolean; + consumedByTurnId: string | null; +} + +export interface PreTurnCaptureGate { + readonly getLatest: () => LatestPreTurnCapture | null; + readonly setLatest: (capture: LatestPreTurnCapture) => void; + readonly clearLatest: () => void; +} + interface ThreadGate { readonly lock: Semaphore.Semaphore; + readonly preTurnLock: Semaphore.Semaphore; + latestPreTurn: LatestPreTurnCapture | null; /** Turns owing their final capture, each with what finishing it resolves. */ readonly pending: Map>; /** Turns whose final capture is done, so a late registration owes nothing. */ @@ -55,6 +72,8 @@ const gateFor = (threadId: string) => } const created: ThreadGate = { lock: yield* Semaphore.make(1), + preTurnLock: yield* Semaphore.make(1), + latestPreTurn: null, pending: new Map(), finished: new Set(), closed: new Set(), @@ -146,4 +165,57 @@ export const checkpointHandover = { }), ); }), + + /** + * Serializes pre-turn baseline captures for one thread across + * ProviderCommandReactor and CheckpointReactor so the same turn start is + * captured once instead of three times. + */ + withPreTurnLock: ( + threadId: string, + run: (gate: PreTurnCaptureGate) => Effect.Effect, + ) => + Effect.gen(function* () { + const gate = yield* gateFor(threadId); + const preTurnGate: PreTurnCaptureGate = { + getLatest: () => gate.latestPreTurn, + setLatest: (capture) => { + gate.latestPreTurn = capture; + }, + clearLatest: () => { + gate.latestPreTurn = null; + }, + }; + return yield* gate.preTurnLock.withPermits(1)(run(preTurnGate)); + }), + + /** Marks the latest pre-turn capture as actively dispatched to a provider. */ + markPreTurnSent: (threadId: string, requestKey: string) => + Effect.gen(function* () { + const gate = gates.get(threadId); + if (gate === undefined) { + return; + } + yield* gate.preTurnLock.withPermits(1)( + Effect.sync(() => { + if (gate.latestPreTurn !== null && gate.latestPreTurn.requestKey === requestKey) { + gate.latestPreTurn.sentToProvider = true; + } + }), + ); + }), + + /** Clears remembered pre-turn capture state after a revert, abort, or failed start. */ + clearPreTurn: (threadId: string) => + Effect.gen(function* () { + const gate = gates.get(threadId); + if (gate === undefined) { + return; + } + yield* gate.preTurnLock.withPermits(1)( + Effect.sync(() => { + gate.latestPreTurn = null; + }), + ); + }), }; diff --git a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts index a20f86944..b9d0b5422 100644 --- a/apps/server/src/persistence/Layers/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/Layers/OrchestrationEventStore.ts @@ -46,6 +46,10 @@ const AppendEventRequestSchema = Schema.Struct({ metadataJson: EventMetadataFromJsonString, }); +const AppendEventResultSchema = Schema.Struct({ + sequence: NonNegativeInt, +}); + const OrchestrationEventPersistedRowSchema = Schema.Struct({ sequence: NonNegativeInt, eventId: EventId, @@ -107,7 +111,7 @@ const makeEventStore = Effect.gen(function* () { const appendEventRow = SqlSchema.findOne({ Request: AppendEventRequestSchema, - Result: OrchestrationEventPersistedRowSchema, + Result: AppendEventResultSchema, execute: (request) => sql` INSERT INTO orchestration_events ( @@ -148,18 +152,7 @@ const makeEventStore = Effect.gen(function* () { ${request.payloadJson}, ${request.metadataJson} ) - RETURNING - sequence, - event_id AS "eventId", - event_type AS "type", - aggregate_kind AS "aggregateKind", - stream_id AS "aggregateId", - occurred_at AS "occurredAt", - command_id AS "commandId", - causation_event_id AS "causationEventId", - correlation_id AS "correlationId", - payload_json AS "payload", - metadata_json AS "metadata" + RETURNING sequence `, }); @@ -235,7 +228,7 @@ const makeEventStore = Effect.gen(function* () { ), ), Effect.flatMap((row) => - decodeEvent(row).pipe( + decodeEvent({ ...event, sequence: row.sequence }).pipe( Effect.mapError(toPersistenceDecodeError("OrchestrationEventStore.append:rowToEvent")), ), ), diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts index 2e998d9d6..8a59cf21b 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.test.ts @@ -40,6 +40,27 @@ function parseLogLine(line: string) { }; } +function waitUntil(predicate: () => boolean, timeoutMs = 2_000): Effect.Effect { + return Effect.promise( + () => + new Promise((resolve, reject) => { + const deadline = Date.now() + timeoutMs; + const check = () => { + if (predicate()) { + resolve(); + return; + } + if (Date.now() >= deadline) { + reject(new Error("Timed out waiting for async provider log flush")); + return; + } + setTimeout(check, 5); + }; + check(); + }), + ); +} + describe("EventNdjsonLogger", () => { it.effect("removes old provider log files without touching unrelated files", () => Effect.gen(function* () { @@ -268,13 +289,14 @@ describe("EventNdjsonLogger", () => { yield* Effect.yieldNow; assert.equal(fs.existsSync(globalPath), false); yield* TestClock.adjust("1 millis"); + yield* waitUntil(() => fs.existsSync(globalPath)); yield* Effect.yieldNow; assert.equal(fs.existsSync(globalPath), true); yield* logger.write({ id: "evt-second" }, null); assert.equal(fs.readFileSync(globalPath, "utf8").includes("evt-second"), false); yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; + yield* waitUntil(() => fs.readFileSync(globalPath, "utf8").includes("evt-second")); const lines = fs .readFileSync(globalPath, "utf8") @@ -376,16 +398,16 @@ describe("EventNdjsonLogger", () => { Effect.gen(function* () { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); const basePath = path.join(tempDir, "provider-canonical.ndjson"); - const realAppendFileSync = fs.appendFileSync.bind(fs); + const realAppendFile = fs.promises.appendFile.bind(fs.promises); let appendAttempts = 0; let failWritesAfterFirst = true; let logger: EventNdjsonLogger | undefined; - const appendSpy = vi.spyOn(fs, "appendFileSync").mockImplementation((...args) => { + const appendSpy = vi.spyOn(fs.promises, "appendFile").mockImplementation(async (...args) => { appendAttempts += 1; if (failWritesAfterFirst && appendAttempts > 1) { throw new Error("simulated provider log write failure"); } - Reflect.apply(realAppendFileSync, fs, args); + await Reflect.apply(realAppendFile, fs.promises, args); }); try { @@ -406,6 +428,7 @@ describe("EventNdjsonLogger", () => { yield* logger.write({ id: "evt-2", payload: "x".repeat(60) }, null); yield* logger.write({ id: "evt-3", payload: "x".repeat(60) }, null); yield* TestClock.adjust("1 second"); + yield* waitUntil(() => appendAttempts === 2); yield* Effect.yieldNow; assert.equal(appendAttempts, 2); @@ -417,9 +440,16 @@ describe("EventNdjsonLogger", () => { failWritesAfterFirst = false; yield* TestClock.adjust("1 millis"); - yield* Effect.yieldNow; + yield* waitUntil(() => appendAttempts >= 4); yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; + yield* waitUntil(() => { + const entries = fs + .readdirSync(tempDir) + .filter((entry) => entry === "_global.log" || entry.startsWith("_global.log.")); + return entries.some((entry) => + fs.readFileSync(path.join(tempDir, entry), "utf8").includes("evt-4"), + ); + }); const payloadIds = fs .readdirSync(tempDir) .filter((entry) => entry === "_global.log" || entry.startsWith("_global.log.")) @@ -446,14 +476,16 @@ describe("EventNdjsonLogger", () => { Effect.gen(function* () { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-log-")); const basePath = path.join(tempDir, "provider-canonical.ndjson"); - const realAppendFileSync = fs.appendFileSync.bind(fs); + const realAppendFile = fs.promises.appendFile.bind(fs.promises); let failWrites = true; let logger: EventNdjsonLogger | undefined; - const appendSpy = vi.spyOn(fs, "appendFileSync").mockImplementation((...args) => { + let failedAttemptCount = 0; + const appendSpy = vi.spyOn(fs.promises, "appendFile").mockImplementation(async (...args) => { if (failWrites) { + failedAttemptCount += 1; throw new Error("simulated provider log write failure"); } - Reflect.apply(realAppendFileSync, fs, args); + await Reflect.apply(realAppendFile, fs.promises, args); }); try { @@ -475,11 +507,13 @@ describe("EventNdjsonLogger", () => { ); } yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; + yield* waitUntil(() => failedAttemptCount > 0); failWrites = false; yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; + yield* waitUntil( + () => fs.readdirSync(tempDir).filter((entry) => entry.endsWith(".log")).length > 0, + ); const logFiles = fs.readdirSync(tempDir).filter((entry) => entry.endsWith(".log")); const persistedBytes = logFiles.reduce( (total, entry) => total + fs.statSync(path.join(tempDir, entry)).size, diff --git a/apps/server/src/provider/Layers/EventNdjsonLogger.ts b/apps/server/src/provider/Layers/EventNdjsonLogger.ts index 0813fe880..1bcc77bb0 100644 --- a/apps/server/src/provider/Layers/EventNdjsonLogger.ts +++ b/apps/server/src/provider/Layers/EventNdjsonLogger.ts @@ -15,6 +15,7 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import * as SynchronizedRef from "effect/SynchronizedRef"; import { toSafeThreadAttachmentSegment } from "../../attachmentStore.ts"; @@ -342,6 +343,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { const sink = sinkResult.sink; const scope = yield* Scope.make(); + const flushSemaphore = yield* Semaphore.make(1); const initialRetryDelayMs = input.batchWindowMs > 0 ? input.batchWindowMs : DEFAULT_BATCH_WINDOW_MS; let closed = false; @@ -353,89 +355,111 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { let bufferedBytes = 0; let buffer: Array<{ readonly line: string; readonly bytes: number }> = []; - const flushUnsafe = (): - | { ok: true; attempted: boolean } + type FlushAttemptResult = + | { readonly ok: true; readonly attempted: boolean } | { - ok: false; - error: unknown; - droppedRecords: number; - droppedBytes: number; - } => { - if (buffer.length === 0) { - return { ok: true, attempted: false }; - } - - const messages = buffer; - buffer = []; - bufferedBytes = 0; - let persistedCount = 0; + readonly ok: false; + readonly error: unknown; + readonly droppedRecords: number; + readonly droppedBytes: number; + }; - try { - while (persistedCount < messages.length) { - const firstMessage = messages[persistedCount]; - if (!firstMessage) { - break; + const runFlushAsync = (allowDuringBackoff: boolean) => + flushSemaphore.withPermits(1)( + Effect.gen(function* () { + if (buffer.length === 0 || (!allowDuringBackoff && recovering)) { + return { + result: { ok: true as const, attempted: false } satisfies FlushAttemptResult, + reportFailure: false, + }; } - let nextIndex = persistedCount + 1; - let chunkBytes = firstMessage.bytes; - while (nextIndex < messages.length) { - const nextMessage = messages[nextIndex]; - if (!nextMessage || chunkBytes + nextMessage.bytes > input.maxBytes) { + + const messages = buffer; + buffer = []; + bufferedBytes = 0; + let persistedCount = 0; + let failureError: unknown = undefined; + let failed = false; + + while (persistedCount < messages.length) { + const firstMessage = messages[persistedCount]; + if (!firstMessage) { break; } - chunkBytes += nextMessage.bytes; - nextIndex += 1; - } - sink.write( - messages + let nextIndex = persistedCount + 1; + let chunkBytes = firstMessage.bytes; + while (nextIndex < messages.length) { + const nextMessage = messages[nextIndex]; + if (!nextMessage || chunkBytes + nextMessage.bytes > input.maxBytes) { + break; + } + chunkBytes += nextMessage.bytes; + nextIndex += 1; + } + const chunk = messages .slice(persistedCount, nextIndex) .map((message) => message.line) - .join(""), - ); - input.bufferBudget.release(chunkBytes); - persistedCount = nextIndex; - } - return { ok: true, attempted: true }; - } catch (error) { - buffer = [...messages.slice(persistedCount), ...buffer]; - bufferedBytes = buffer.reduce((total, message) => total + message.bytes, 0); - let droppedRecords = 0; - let droppedBytes = 0; - while (input.bufferBudget.usedBytes > input.bufferBudget.maxBytes && buffer.length > 0) { - const dropped = buffer.pop(); - if (!dropped) { - break; + .join(""); + const writeOutcome = yield* Effect.tryPromise(() => sink.writeAsync(chunk)).pipe( + Effect.as({ ok: true as const }), + Effect.catch((error) => Effect.succeed({ ok: false as const, error })), + ); + if (!writeOutcome.ok) { + failed = true; + failureError = writeOutcome.error; + break; + } + input.bufferBudget.release(chunkBytes); + persistedCount = nextIndex; } - bufferedBytes -= dropped.bytes; - input.bufferBudget.release(dropped.bytes); - droppedRecords += 1; - droppedBytes += dropped.bytes; - } - return { ok: false, error, droppedRecords, droppedBytes }; - } - }; - const runFlushUnsafe = () => { - const result = flushUnsafe(); - if (result.ok) { - if (result.attempted) { - recovering = false; - failureReported = false; - nextRetryDelayMs = initialRetryDelayMs; - } - return { result, reportFailure: false }; - } + if (!failed) { + recovering = false; + failureReported = false; + nextRetryDelayMs = initialRetryDelayMs; + return { + result: { ok: true as const, attempted: true } satisfies FlushAttemptResult, + reportFailure: false, + }; + } - nextRetryDelayMs = recovering - ? Math.min(MAX_RETRY_DELAY_MS, nextRetryDelayMs * 2) - : initialRetryDelayMs; - recovering = true; - const reportFailure = !failureReported; - failureReported = true; - return { result, reportFailure }; - }; + buffer = [...messages.slice(persistedCount), ...buffer]; + bufferedBytes = buffer.reduce((total, message) => total + message.bytes, 0); + let droppedRecords = 0; + let droppedBytes = 0; + while (input.bufferBudget.usedBytes > input.bufferBudget.maxBytes && buffer.length > 0) { + const dropped = buffer.pop(); + if (!dropped) { + break; + } + bufferedBytes -= dropped.bytes; + input.bufferBudget.release(dropped.bytes); + droppedRecords += 1; + droppedBytes += dropped.bytes; + } - const reportFlushResult = (outcome: ReturnType) => + nextRetryDelayMs = recovering + ? Math.min(MAX_RETRY_DELAY_MS, nextRetryDelayMs * 2) + : initialRetryDelayMs; + recovering = true; + const reportFailure = !failureReported; + failureReported = true; + return { + result: { + ok: false as const, + error: failureError, + droppedRecords, + droppedBytes, + } satisfies FlushAttemptResult, + reportFailure, + }; + }).pipe(Effect.uninterruptible, Effect.withTracerEnabled(false)), + ); + + const reportFlushResult = (outcome: { + readonly result: FlushAttemptResult; + readonly reportFailure: boolean; + }) => outcome.result.ok || !outcome.reportFailure ? Effect.void : logWarning("provider event log batch flush failed", { @@ -445,7 +469,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { droppedBytes: outcome.result.droppedBytes, }); - const flush = Effect.sync(runFlushUnsafe).pipe( + const flush = runFlushAsync(true).pipe( Effect.flatMap(reportFlushResult), Effect.withTracerEnabled(false), ); @@ -456,17 +480,14 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { Effect.sleep(`${delayMs} millis`).pipe( Effect.andThen( Effect.gen(function* () { - const outcome = yield* Effect.sync(() => { - flushScheduled = false; - return runFlushUnsafe(); - }); + const outcome = yield* runFlushAsync(true); yield* reportFlushResult(outcome); const retry = yield* Effect.sync(() => { - if (closed || buffer.length === 0 || flushScheduled) { + if (closed || buffer.length === 0) { + flushScheduled = false; return false; } - flushScheduled = true; return true; }); if (retry) { @@ -487,7 +508,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { const action = yield* Effect.sync(() => { if (closed) { return { - outcome: undefined, + flushNow: false, schedule: false, droppedBytes: 0, reportDrop: false, @@ -500,7 +521,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { const reportOversized = !oversizedRecordWarningReported; oversizedRecordWarningReported = true; return { - outcome: undefined, + flushNow: false, schedule: false, droppedBytes: bytes, reportDrop: false, @@ -510,7 +531,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { const reservation = input.bufferBudget.reserve(bytes, !recovering); if (!reservation.reserved) { return { - outcome: undefined, + flushNow: false, schedule: false, droppedBytes: bytes, reportDrop: reservation.reportDrop, @@ -526,14 +547,9 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { buffer.length >= FLUSH_BUFFER_THRESHOLD || bufferedBytes >= input.bufferBudget.maxBytes) ) { - const outcome = runFlushUnsafe(); - const schedule = !outcome.result.ok && buffer.length > 0 && !flushScheduled; - if (schedule) { - flushScheduled = true; - } return { - outcome, - schedule, + flushNow: true, + schedule: false, droppedBytes: 0, reportDrop: false, reportOversized: false, @@ -543,7 +559,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { if (!flushScheduled && (input.batchWindowMs > 0 || recovering)) { flushScheduled = true; return { - outcome: undefined, + flushNow: false, schedule: true, droppedBytes: 0, reportDrop: false, @@ -551,7 +567,7 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { }; } return { - outcome: undefined, + flushNow: false, schedule: false, droppedBytes: 0, reportDrop: false, @@ -575,10 +591,16 @@ const makeThreadWriter = Effect.fnUntraced(function* (input: { droppedBytes: action.droppedBytes, }); } - if (action.outcome) { - yield* reportFlushResult(action.outcome); + let scheduleAfterFlush = action.schedule; + if (action.flushNow) { + const outcome = yield* runFlushAsync(false); + yield* reportFlushResult(outcome); + if ((!outcome.result.ok || recovering) && !closed && buffer.length > 0 && !flushScheduled) { + flushScheduled = true; + scheduleAfterFlush = true; + } } - if (action.schedule) { + if (scheduleAfterFlush) { yield* scheduleFlush(); } }).pipe(Effect.uninterruptible, Effect.withTracerEnabled(false)); diff --git a/apps/server/src/provider/Layers/ProviderEventLoggers.ts b/apps/server/src/provider/Layers/ProviderEventLoggers.ts index 40b08171f..6e919efbd 100644 --- a/apps/server/src/provider/Layers/ProviderEventLoggers.ts +++ b/apps/server/src/provider/Layers/ProviderEventLoggers.ts @@ -129,6 +129,11 @@ export const ProviderEventLoggersLive = Layer.effect( stream: "canonical", keepStreamFragments, }); + yield* Effect.addFinalizer(() => + Effect.all([native?.close() ?? Effect.void, canonical?.close() ?? Effect.void], { + discard: true, + }).pipe(Effect.ignore), + ); return { native, canonical, diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index e4f5ba0e3..88a6b32b6 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; + import { DEFAULT_TERMINAL_ID, type TerminalEvent, @@ -1132,8 +1134,23 @@ function sanitizeTerminalHistoryChunk( continue; } - append(input[index] ?? ""); + const plainStart = index; index += 1; + while (index < input.length) { + const nextCode = input.charCodeAt(index); + if ( + nextCode === 0x1b || + nextCode === 0x9b || + nextCode === 0x9d || + nextCode === 0x90 || + nextCode === 0x9e || + nextCode === 0x9f + ) { + break; + } + index += 1; + } + append(input.slice(plainStart, index)); } return result(null); @@ -2005,11 +2022,15 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith // overwrites newer history or brings back a deleted file. let persistVersion = 0; const writtenVersions = new Map(); + const writtenHistoryDigests = new Map(); const pendingPersists = new Map< string, { history: string; version: number; timer: Fiber.Fiber | null } >(); + const historyDigestOf = (history: string): string => + `${history.length}:${createHash("sha256").update(history).digest("hex")}`; + const persistWorker = yield* makeKeyedCoalescingWorker< string, PersistHistoryRequest, @@ -2020,21 +2041,33 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { if (request.version <= (writtenVersions.get(sessionKey) ?? -1)) return; writtenVersions.set(sessionKey, request.version); + const digest = historyDigestOf(request.history); + if (writtenHistoryDigests.get(sessionKey) === digest) return; const [threadId, terminalId] = sessionKey.split("\u0000"); if (!threadId || !terminalId) { return; } - yield* fileSystem.writeFileString(historyPath(threadId, terminalId), request.history).pipe( - Effect.catch((error) => - Effect.logWarning("failed to persist terminal history", { - threadId, - terminalId, - error, - }), - ), - ); + const wrote = yield* fileSystem + .writeFileString(historyPath(threadId, terminalId), request.history) + .pipe( + Effect.as(true), + Effect.catch((error) => + Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + error, + }).pipe(Effect.as(false)), + ), + ); + if (wrote) { + writtenHistoryDigests.set(sessionKey, digest); + } else { + // A partial write may have altered disk contents; clear the cached + // digest so a subsequent Clear or retry always overwrites disk. + writtenHistoryDigests.delete(sessionKey); + } }), }); @@ -2117,6 +2150,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith yield* takePendingPersist(sessionKey); persistVersion += 1; writtenVersions.set(sessionKey, persistVersion); + writtenHistoryDigests.delete(sessionKey); yield* persistWorker.drainKey(sessionKey); }); @@ -2560,6 +2594,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith for (const session of toEvict) { const key = toSessionKey(session.threadId, session.terminalId); sessions.delete(key); + writtenHistoryDigests.delete(key); } return [toEvict, { ...state, sessions }] as const; @@ -2826,6 +2861,32 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith } session.pendingProcessEventIndex += 1; + let eventData = nextEvent.type === "output" ? nextEvent.data : ""; + if ( + nextEvent.type === "output" && + !eventData.includes("\u001b]") && + !eventData.includes("\u009d") + ) { + // Merge consecutive queued output chunks sharing the same command + // generation so bursty PTY output sanitizes and publishes once, + // while never merging past OSC command-completion markers. + const MAX_COALESCED_OUTPUT_CHARS = 64 * 1024; + while (session.pendingProcessEventIndex < session.pendingProcessEvents.length) { + const queued = session.pendingProcessEvents[session.pendingProcessEventIndex]; + if ( + !queued || + queued.type !== "output" || + queued.commandGeneration !== nextEvent.commandGeneration || + queued.data.includes("\u001b]") || + queued.data.includes("\u009d") || + eventData.length + queued.data.length > MAX_COALESCED_OUTPUT_CHARS + ) { + break; + } + eventData += queued.data; + session.pendingProcessEventIndex += 1; + } + } if (session.pendingProcessEventIndex >= session.pendingProcessEvents.length) { session.pendingProcessEvents = []; session.pendingProcessEventIndex = 0; @@ -2836,7 +2897,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith session.subprocessPoll.outputSincePoll = true; const sanitized = sanitizeTerminalHistoryChunk( session.pendingHistoryControlSequence, - nextEvent.data, + eventData, nextEvent.commandGeneration, ); // A sequence that never ends (a broken program) is dropped @@ -3008,7 +3069,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith threadId: session.threadId, terminalId: session.terminalId, history: sanitized.visibleText.length > 0 ? session.history : null, - data: nextEvent.data, + data: eventData, commandFinished: commandFinished || (runEnd !== null && runEnd.run.mode === "run"), runEnd, insertEnd, @@ -3548,6 +3609,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith } const sessions = new Map(state.sessions); sessions.delete(key); + writtenHistoryDigests.delete(key); return [undefined, { ...state, sessions }] as const; }); yield* removeCatalogTab(threadId, terminalId); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index a2fcc0aca..e0c1d2d0e 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -307,6 +307,21 @@ describe("UsageService.readSummary", () => { expect(summary.pricing.status).toBe("fresh"); expect(summary.sources.map((source) => source.status)).toEqual(["ok", "ok"]); expect(summary.sources.every((source) => source.lastScannedAt.length > 0)).toBe(true); + + // The persisted rates cache stores only the compact parsed table, and the + // debounced scan cache flushes when the service scope closes. + const ratesCache = JSON.parse( + yield* Effect.promise(() => + NodeFSP.readFile( + NodePath.join(fixture.config.stateDir, "usage-model-rates.json"), + "utf8", + ), + ), + ) as { fetchedAtMs: number; rates?: Record; document?: unknown }; + expect(ratesCache.document).toBeUndefined(); + expect(ratesCache.rates?.[CLAUDE_MODEL]).toBeDefined(); + expect(ratesCache.rates?.[CODEX_MODEL]).toBeDefined(); + yield* Effect.promise(() => NodeFSP.rm(fixture.root, { recursive: true, force: true })); }), ); diff --git a/apps/server/src/usage/UsageService.ts b/apps/server/src/usage/UsageService.ts index ad6e88136..f3c5285c2 100644 --- a/apps/server/src/usage/UsageService.ts +++ b/apps/server/src/usage/UsageService.ts @@ -38,11 +38,14 @@ import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; 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 Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import { HttpClient, HttpClientResponse } from "effect/http"; import { writeFileStringAtomically } from "../atomicWrite.ts"; @@ -67,7 +70,12 @@ import { ServerSettingsService } from "../serverSettings.ts"; import { hourStartOf, UsageAggregator } from "./usageAggregation.ts"; import { USAGE_LEDGER_PROVIDERS, usageLedgerDir } from "./usageLedger.ts"; import { readOpenCodeUsage } from "./usageOpenCode.ts"; -import { parseRateTable, type RateTable } from "./usagePricing.ts"; +import { + type ModelRate, + parseCompactRateTable, + parseRateTable, + type RateTable, +} from "./usagePricing.ts"; import { decodeScanCache, dedupeWithinFile, @@ -89,6 +97,7 @@ const LITELLM_RATES_URL = const RATES_TTL_MS = 24 * 60 * 60 * 1000; const RATES_FETCH_TIMEOUT_MS = 10_000; +const SCAN_CACHE_PERSIST_DEBOUNCE_MS = 5_000; const DAY_MS = 24 * 60 * 60 * 1000; const HOUR_MS = 60 * 60 * 1000; @@ -124,11 +133,23 @@ type UsageScanSource = readonly read: (sinceMs: number) => readonly UsageRecord[] | null; }; -interface RatesCacheFile { +interface CompactRatesCacheFile { readonly fetchedAtMs: number; - readonly document: unknown; + readonly rates: Readonly>; } +type RatesCacheFile = + | { + readonly kind: "compact"; + readonly fetchedAtMs: number; + readonly rates: unknown; + } + | { + readonly kind: "legacy"; + readonly fetchedAtMs: number; + readonly document: unknown; + }; + /** A cache file that is not JSON. */ class CacheFileParseError extends Data.TaggedError("CacheFileParseError")<{ readonly cause: unknown; @@ -147,9 +168,16 @@ const parseJsonFile = (raw: string): Effect.Effect function readRatesCacheFile(document: unknown): RatesCacheFile | null { if (typeof document !== "object" || document === null) return null; - const record = document as Partial; + const record = document as { + readonly fetchedAtMs?: unknown; + readonly rates?: unknown; + readonly document?: unknown; + }; if (typeof record.fetchedAtMs !== "number" || !Number.isFinite(record.fetchedAtMs)) return null; - return { fetchedAtMs: record.fetchedAtMs, document: record.document }; + if (record.rates !== undefined) { + return { kind: "compact", fetchedAtMs: record.fetchedAtMs, rates: record.rates }; + } + return { kind: "legacy", fetchedAtMs: record.fetchedAtMs, document: record.document }; } export interface UsageServiceShape { @@ -191,9 +219,20 @@ export const make = Effect.gen(function* () { const config = yield* ServerConfig; const settingsService = yield* ServerSettingsService; const httpClient = yield* HttpClient.HttpClient; + const serviceScope = yield* Scope.Scope; const fileCache: ScanCache = new Map(); + const persistLock = yield* Semaphore.make(1); let cacheDirty = false; + let cacheDirtyGeneration = 0; + let lastAttemptedPersistGeneration = 0; + let pendingPersistFiber: Fiber.Fiber | null = null; + let closed = false; + + const markCacheDirty = () => { + cacheDirty = true; + cacheDirtyGeneration += 1; + }; /** * Both caches are rebuildable, so a failed write costs one cold scan and must @@ -230,7 +269,10 @@ export const make = Effect.gen(function* () { Effect.catchCause(() => Effect.succeed(null)), ); if (fromDisk !== null) { - const parsed = parseRateTable(fromDisk.document); + const parsed = + fromDisk.kind === "compact" + ? parseCompactRateTable(fromDisk.rates) + : parseRateTable(fromDisk.document); if (parsed.size > 0) { rates = parsed; ratesFetchedAtMs = fromDisk.fetchedAtMs; @@ -260,9 +302,14 @@ export const make = Effect.gen(function* () { ratesFetchedAtMs = now; ratesStatus = "fresh"; + // Persist only the parsed 5-field rate table rather than the full 3.7 MB + // upstream LiteLLM catalog so cold starts read and parse ~25x less JSON. yield* writeCacheFile( ratesCachePath, - JSON.stringify({ fetchedAtMs: now, document: fetched } satisfies RatesCacheFile), + JSON.stringify({ + fetchedAtMs: now, + rates: Object.fromEntries(parsed), + } satisfies CompactRatesCacheFile), ); }); @@ -424,17 +471,54 @@ export const make = Effect.gen(function* () { }), ); - const persistScanCache = Effect.fn("UsageService.persistScanCache")(function* () { - if (!cacheDirty) return; - // Cleared only after the write lands, so a failed persist is retried on the - // next scan instead of leaving disk permanently stale. - const written = yield* writeCacheFile( - scanCachePath, - JSON.stringify(encodeScanCache(fileCache)), + const flushScanCacheNow = persistLock.withPermits(1)( + Effect.gen(function* () { + if (!cacheDirty) return; + const generation = cacheDirtyGeneration; + lastAttemptedPersistGeneration = generation; + // Cleared only after the write lands and no newer scan dirtied the map, + // so a failed or superseded persist is retried instead of leaving disk stale. + const written = yield* writeCacheFile( + scanCachePath, + JSON.stringify(encodeScanCache(fileCache)), + ); + if (written && cacheDirtyGeneration === generation) { + cacheDirty = false; + } + }).pipe(Effect.uninterruptible), + ); + + const schedulePersistScanCache: Effect.Effect = Effect.gen(function* () { + if (!cacheDirty || closed || pendingPersistFiber !== null) return; + pendingPersistFiber = yield* Effect.sleep(`${SCAN_CACHE_PERSIST_DEBOUNCE_MS} millis`).pipe( + Effect.andThen( + Effect.gen(function* () { + pendingPersistFiber = null; + yield* flushScanCacheNow; + // Only re-arm automatically if a newer scan arrived while the write + // was in flight; a failed write on an idle server waits for the next + // scan instead of spinning every 5 seconds. + if (cacheDirty && !closed && cacheDirtyGeneration !== lastAttemptedPersistGeneration) { + yield* schedulePersistScanCache; + } + }), + ), + Effect.forkIn(serviceScope), ); - if (written) cacheDirty = false; }); + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + closed = true; + const pending = pendingPersistFiber; + pendingPersistFiber = null; + if (pending !== null) { + yield* Fiber.interrupt(pending).pipe(Effect.ignore); + } + yield* flushScanCacheNow; + }).pipe(Effect.ignore), + ); + /** Parses one transcript, reusing the cached result when it is unchanged. */ const readFileRecords = ( filePath: string, @@ -466,7 +550,7 @@ export const make = Effect.gen(function* () { const records = dedupeWithinFile(parsed); fileCache.set(filePath, { size, mtimeMs, provider, records }); - cacheDirty = true; + markCacheDirty(); return records; }); @@ -619,8 +703,8 @@ export const make = Effect.gen(function* () { windowStartMs, retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * DAY_MS, }); - if (pruned > 0) cacheDirty = true; - yield* persistScanCache(); + if (pruned > 0) markCacheDirty(); + yield* schedulePersistScanCache; const aggregated = aggregator.finish(); const readAt = yield* DateTime.now; diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 3f18ae4d0..36f207555 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -89,6 +89,41 @@ export function parseRateTable(document: unknown): RateTable { return table; } +/** + * Decodes a compacted on-disk rate table produced from `parseRateTable`. + */ +export function parseCompactRateTable(document: unknown): RateTable { + const table = new Map(); + if (typeof document !== "object" || document === null) return table; + + for (const [name, raw] of Object.entries(document as Record)) { + if (typeof raw !== "object" || raw === null) continue; + const entry = raw as Partial; + const inputCostPerToken = finiteNumber(entry.inputCostPerToken); + const outputCostPerToken = finiteNumber(entry.outputCostPerToken); + const cacheReadCostPerToken = finiteNumber(entry.cacheReadCostPerToken); + const cacheCreationCostPerToken = finiteNumber(entry.cacheCreationCostPerToken); + const cacheCreation1hCostPerToken = finiteNumber(entry.cacheCreation1hCostPerToken); + if ( + inputCostPerToken === null || + outputCostPerToken === null || + cacheReadCostPerToken === null || + cacheCreationCostPerToken === null || + cacheCreation1hCostPerToken === null + ) { + continue; + } + table.set(name, { + inputCostPerToken, + outputCostPerToken, + cacheReadCostPerToken, + cacheCreationCostPerToken, + cacheCreation1hCostPerToken, + }); + } + return table; +} + /** Anthropic publishes USD per million tokens; the table stores USD per token. */ const perMillion = (usd: number): number => usd / 1_000_000; diff --git a/apps/server/src/vcs/scratchIndex.ts b/apps/server/src/vcs/scratchIndex.ts index a518585bd..83f7e201d 100644 --- a/apps/server/src/vcs/scratchIndex.ts +++ b/apps/server/src/vcs/scratchIndex.ts @@ -260,6 +260,15 @@ interface Rules { export const makeScratchIndexes = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; + const gitVersionCache = new Map(); + const gitSystemAttrCache = new Map(); + const gitExecPathCache = new Map>(); + + const binaryCacheKey = (env: NodeJS.ProcessEnv): string => + `${env.PATH ?? process.env.PATH ?? ""}\0${env.GIT_EXEC_PATH ?? process.env.GIT_EXEC_PATH ?? ""}`; + + const systemAttrCacheKey = (env: NodeJS.ProcessEnv): string => + `${binaryCacheKey(env)}\0${env.GIT_ATTR_NOSYSTEM ?? process.env.GIT_ATTR_NOSYSTEM ?? ""}\0${env.GIT_CONFIG_NOSYSTEM ?? process.env.GIT_CONFIG_NOSYSTEM ?? ""}\0${env.GIT_CONFIG_SYSTEM ?? process.env.GIT_CONFIG_SYSTEM ?? ""}`; const hashFile = (filePath: string) => fileSystem.readFile(filePath).pipe( @@ -309,6 +318,8 @@ export const makeScratchIndexes = Effect.gen(function* () { Effect.gen(function* () { // Pathspecs here are patterns, even under an agent's literal profile. const listingEnv: NodeJS.ProcessEnv = { ...input.env, GIT_LITERAL_PATHSPECS: "0" }; + const binKey = binaryCacheKey(input.env); + const sysKey = systemAttrCacheKey(input.env); // Attribute file paths as git itself resolves them, on git 2.42 and later. const gitVar = (variable: "GIT_ATTR_GLOBAL" | "GIT_ATTR_SYSTEM") => input.git(["var", variable], input.env).pipe( @@ -316,21 +327,44 @@ export const makeScratchIndexes = Effect.gen(function* () { Effect.map(withoutLineEnding), Effect.orElseSucceed(() => ""), ); - const [version, globalVar, systemVar, treeListing, fileListing] = yield* Effect.all( - [ - input.git(["version"], input.env), - gitVar("GIT_ATTR_GLOBAL"), - gitVar("GIT_ATTR_SYSTEM"), - input.tree === null - ? Effect.succeed({ stdout: "" }) - : input.git(["ls-tree", "-r", "-z", "--full-tree", input.tree], input.env, { - maxOutputBytes: LISTING_MAX_OUTPUT_BYTES, - }), - listUntracked(input, listingEnv), - ], - { concurrency: "unbounded" }, - ); + const cachedVersion = gitVersionCache.get(binKey); + const cachedSystemVar = gitSystemAttrCache.get(sysKey); + const [versionText, globalVar, systemVar, configListing, treeListing, fileListing] = + yield* Effect.all( + [ + cachedVersion !== undefined + ? Effect.succeed(cachedVersion) + : input.git(["version"], input.env).pipe( + Effect.flatMap(completeOutput), + Effect.map((stdout) => stdout.trim()), + Effect.tap((value) => + Effect.sync(() => { + gitVersionCache.set(binKey, value); + }), + ), + ), + gitVar("GIT_ATTR_GLOBAL"), + cachedSystemVar !== undefined + ? Effect.succeed(cachedSystemVar) + : gitVar("GIT_ATTR_SYSTEM").pipe( + Effect.tap((value) => + Effect.sync(() => { + gitSystemAttrCache.set(sysKey, value); + }), + ), + ), + input.git(["config", "-z", "--list"], input.env), + input.tree === null + ? Effect.succeed({ stdout: "" }) + : input.git(["ls-tree", "-r", "-z", "--full-tree", input.tree], input.env, { + maxOutputBytes: LISTING_MAX_OUTPUT_BYTES, + }), + listUntracked(input, listingEnv), + ], + { concurrency: "unbounded" }, + ); + const initialSettings = parseConfigList(yield* completeOutput(configListing)); const treeEntries = parseEntries(yield* completeOutput(treeListing), 2); // `ls-files --others` names a nested repository by its folder, `sub/`. const untrackedFiles = splitNul(yield* completeOutput(fileListing)).map((file) => @@ -351,75 +385,84 @@ export const makeScratchIndexes = Effect.gen(function* () { const globalFiles = globalVar.length > 0 ? [path.resolve(input.cwd, globalVar)] - : yield* olderGitGlobalAttributes(input); + : olderGitGlobalAttributes(input, initialSettings); const systemFiles = systemVar.length > 0 ? [path.resolve(input.cwd, systemVar)] - : yield* olderGitSystemAttributes(input); + : yield* olderGitSystemAttributes(input, binKey); if (globalFiles === null) { return null; } return { - version: (yield* completeOutput(version)).trim(), - attributeFiles: [ - ...inTreeAttributes, - path.join(input.gitCommonDir, "info", "attributes"), - ...globalFiles, - ...systemFiles, - ], - indexedAttributes, - treeEntries, - untrackedFiles, - } satisfies RuleSources; + sources: { + version: versionText, + attributeFiles: [ + ...inTreeAttributes, + path.join(input.gitCommonDir, "info", "attributes"), + ...globalFiles, + ...systemFiles, + ], + indexedAttributes, + treeEntries, + untrackedFiles, + } satisfies RuleSources, + initialSettings, + }; }).pipe(Effect.orElseSucceed(() => null)); /** * Where a git older than 2.42 reads the global attributes file, or null * when only git can expand the configured path (`~user/`, `%(prefix)/`). */ - const olderGitGlobalAttributes = (input: { - readonly git: ScratchIndexGit; - readonly env: NodeJS.ProcessEnv; - readonly cwd: string; - }) => - input.git(["config", "-z", "--list"], input.env).pipe( - Effect.flatMap(completeOutput), - Effect.map((config) => { - const configured = lastValue(parseConfigList(config), "core.attributesfile")?.[1]; - if (configured === undefined || configured.trim().length === 0) { - const configHome = - input.env.XDG_CONFIG_HOME || - process.env.XDG_CONFIG_HOME || - path.join(homedir(), ".config"); - return [path.join(configHome, "git", "attributes")]; - } - if (/^~[^/\\]/.test(configured) || configured.includes("%(")) { - return null; - } - return [path.resolve(input.cwd, configured.replace(/^~(?=$|[/\\])/, homedir()))]; - }), - ); + const olderGitGlobalAttributes = ( + input: { + readonly env: NodeJS.ProcessEnv; + readonly cwd: string; + }, + settings: ReadonlyArray, + ): ReadonlyArray | null => { + const configured = lastValue(settings, "core.attributesfile")?.[1]; + if (configured === undefined || configured.trim().length === 0) { + const configHome = + input.env.XDG_CONFIG_HOME || process.env.XDG_CONFIG_HOME || path.join(homedir(), ".config"); + return [path.join(configHome, "git", "attributes")]; + } + if (/^~[^/\\]/.test(configured) || configured.includes("%(")) { + return null; + } + return [path.resolve(input.cwd, configured.replace(/^~(?=$|[/\\])/, homedir()))]; + }; /** * Where a git older than 2.42 may keep its system attributes file. It * cannot say, so every place a standard build looks is read. */ - const olderGitSystemAttributes = (input: { - readonly git: ScratchIndexGit; - readonly env: NodeJS.ProcessEnv; - }) => - input.git(["--exec-path"], input.env).pipe( + const olderGitSystemAttributes = ( + input: { + readonly git: ScratchIndexGit; + readonly env: NodeJS.ProcessEnv; + }, + binKey: string, + ) => { + const cached = gitExecPathCache.get(binKey); + if (cached !== undefined) { + return Effect.succeed(cached); + } + return input.git(["--exec-path"], input.env).pipe( Effect.flatMap(completeOutput), Effect.map((execPath) => { // `/libexec/git-core` const prefix = path.dirname(path.dirname(withoutLineEnding(execPath))); - return [ + const files = [ "/etc/gitattributes", path.join(prefix, "etc", "gitattributes"), path.join(prefix, "share", "git-core", "gitattributes"), ]; + gitExecPathCache.set(binKey, files); + return files; }), ); + }; /** * A fingerprint of the rules git converts the checkout's files under, or @@ -429,16 +472,20 @@ export const makeScratchIndexes = Effect.gen(function* () { const fingerprintRules = ( input: { readonly git: ScratchIndexGit; readonly env: NodeJS.ProcessEnv }, sources: RuleSources, + preloadedSettings?: ReadonlyArray, ) => Effect.gen(function* () { - const [config, hashes] = yield* Effect.all( + const [settings, hashes] = yield* Effect.all( [ - input.git(["config", "-z", "--list"], input.env), - Effect.forEach(sources.attributeFiles, hashFile, { concurrency: 16 }), + preloadedSettings !== undefined + ? Effect.succeed(preloadedSettings) + : input + .git(["config", "-z", "--list"], input.env) + .pipe(Effect.flatMap(completeOutput), Effect.map(parseConfigList)), + Effect.forEach(sources.attributeFiles, hashFile, { concurrency: 32 }), ], { concurrency: "unbounded" }, ); - const settings = parseConfigList(yield* completeOutput(config)); if (cacheUnsafe(settings, input.env)) { return null; } @@ -513,14 +560,22 @@ export const makeScratchIndexes = Effect.gen(function* () { const env: NodeJS.ProcessEnv = { ...baseEnv, GIT_INDEX_FILE: indexPath }; const removeIndex = fileSystem.remove(indexPath, { force: true }).pipe(Effect.ignore); const rulesInput = { git: input.git, env: baseEnv }; - const sources = yield* readRuleSources({ + const ruleSourcesResult = yield* readRuleSources({ ...rulesInput, cwd: input.cwd, toplevel, gitCommonDir, tree: input.tree, }); - const rules = sources === null ? null : yield* fingerprintRules(rulesInput, sources); + const sources = ruleSourcesResult?.sources ?? null; + const rules = + ruleSourcesResult === null + ? null + : yield* fingerprintRules( + rulesInput, + ruleSourcesResult.sources, + ruleSourcesResult.initialSettings, + ); const cachePrefix = rules === null ? null : `${SCRATCH_INDEX_CACHE_PREFIX}${rules.fingerprint}`; // A checkpoint's cache names the tree it was staged over: a file it diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 0d5246938..bad2625de 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -6,12 +6,14 @@ import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL, @@ -915,6 +917,90 @@ const makeDeviceRpcLayer = (viewerId: string) => }), ); +const SHELL_SUBSCRIBER_QUEUE_CAPACITY = 256; +const THREAD_SUBSCRIBER_QUEUE_CAPACITY = 512; + +type SharedShellSubscribe = () => Stream.Stream< + | { + readonly kind: "snapshot"; + readonly snapshot: Effect.Success< + ReturnType<(typeof ProjectionSnapshotQuery.Service)["getShellSnapshot"]> + >; + } + | OrchestrationShellStreamEvent, + OrchestrationGetSnapshotError +>; + +const makeToShellStreamEvent = + (projectionSnapshotQuery: { + readonly getProjectShellById: ( + projectId: Parameters<(typeof ProjectionSnapshotQuery.Service)["getProjectShellById"]>[0], + ) => ReturnType<(typeof ProjectionSnapshotQuery.Service)["getProjectShellById"]>; + readonly getThreadShellById: ( + threadId: ThreadId, + ) => ReturnType<(typeof ProjectionSnapshotQuery.Service)["getThreadShellById"]>; + }) => + ( + event: OrchestrationEvent, + ): Effect.Effect, never, never> => { + switch (event.type) { + case "project.created": + case "project.meta-updated": + return projectionSnapshotQuery.getProjectShellById(event.payload.projectId).pipe( + Effect.map((project) => + Option.map(project, (nextProject) => ({ + kind: "project-upserted" as const, + sequence: event.sequence, + project: nextProject, + })), + ), + Effect.catch(() => Effect.succeed(Option.none())), + ); + case "project.deleted": + return Effect.succeed( + Option.some({ + kind: "project-removed" as const, + sequence: event.sequence, + projectId: event.payload.projectId, + }), + ); + case "thread.deleted": + case "thread.archived": + return Effect.succeed( + Option.some({ + kind: "thread-removed" as const, + sequence: event.sequence, + threadId: event.payload.threadId, + }), + ); + case "thread.unarchived": + return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe( + Effect.map((thread) => + Option.map(thread, (nextThread) => ({ + kind: "thread-upserted" as const, + sequence: event.sequence, + thread: nextThread, + })), + ), + Effect.catch(() => Effect.succeed(Option.none())), + ); + default: + if (event.aggregateKind !== "thread") { + return Effect.succeed(Option.none()); + } + return projectionSnapshotQuery.getThreadShellById(ThreadId.make(event.aggregateId)).pipe( + Effect.map((thread) => + Option.map(thread, (nextThread) => ({ + kind: "thread-upserted" as const, + sequence: event.sequence, + thread: nextThread, + })), + ), + Effect.catch(() => Effect.succeed(Option.none())), + ); + } + }; + /** Every RPC the WebSocket serves, for one connection. */ const makeWsRpcLayer = ( currentSession: { @@ -926,9 +1012,10 @@ const makeWsRpcLayer = ( viewerId: string, sentFromRef: Ref.Ref, devicePlace: MessageSentFrom["place"], + subscribeShell: SharedShellSubscribe, ) => Layer.mergeAll( - makeCoreRpcLayer(currentSession, viewerId, sentFromRef, devicePlace), + makeCoreRpcLayer(currentSession, viewerId, sentFromRef, devicePlace, subscribeShell), makeOutsideAgentsRpcLayer(currentSession.role), ThemesRpcLayer, ThemeShowcaseRpcLayer, @@ -951,6 +1038,8 @@ const makeCoreRpcLayer = ( sentFromRef: Ref.Ref, /** Where that device is (sessionDevicePlace), worked out once per connection. */ devicePlace: MessageSentFrom["place"], + /** Server-shared coalesced shell stream fanout. */ + subscribeShell: SharedShellSubscribe, ) => WsCoreRpcGroup.toLayer( Effect.gen(function* () { @@ -1147,69 +1236,6 @@ const makeCoreRpcLayer = ( const enrichOrchestrationEvents = (events: ReadonlyArray) => Effect.forEach(events, enrichProjectEvent, { concurrency: 4 }); - const toShellStreamEvent = ( - event: OrchestrationEvent, - ): Effect.Effect, never, never> => { - switch (event.type) { - case "project.created": - case "project.meta-updated": - return projectionSnapshotQuery.getProjectShellById(event.payload.projectId).pipe( - Effect.map((project) => - Option.map(project, (nextProject) => ({ - kind: "project-upserted" as const, - sequence: event.sequence, - project: nextProject, - })), - ), - Effect.catch(() => Effect.succeed(Option.none())), - ); - case "project.deleted": - return Effect.succeed( - Option.some({ - kind: "project-removed" as const, - sequence: event.sequence, - projectId: event.payload.projectId, - }), - ); - case "thread.deleted": - case "thread.archived": - return Effect.succeed( - Option.some({ - kind: "thread-removed" as const, - sequence: event.sequence, - threadId: event.payload.threadId, - }), - ); - case "thread.unarchived": - return projectionSnapshotQuery.getThreadShellById(event.payload.threadId).pipe( - Effect.map((thread) => - Option.map(thread, (nextThread) => ({ - kind: "thread-upserted" as const, - sequence: event.sequence, - thread: nextThread, - })), - ), - Effect.catch(() => Effect.succeed(Option.none())), - ); - default: - if (event.aggregateKind !== "thread") { - return Effect.succeed(Option.none()); - } - return projectionSnapshotQuery - .getThreadShellById(ThreadId.make(event.aggregateId)) - .pipe( - Effect.map((thread) => - Option.map(thread, (nextThread) => ({ - kind: "thread-upserted" as const, - sequence: event.sequence, - thread: nextThread, - })), - ), - Effect.catch(() => Effect.succeed(Option.none())), - ); - } - }; - // A first send, or a goal set on a draft, that also creates the thread, // cuts its worktree and launches its setup script (see ThreadBootstrap). const dispatchNormalizedCommand = ( @@ -1693,58 +1719,9 @@ const makeCoreRpcLayer = ( { "rpc.aggregate": "orchestration" }, ), [ORCHESTRATION_WS_METHODS.subscribeShell]: (_input) => - observeRpcStreamEffect( - ORCHESTRATION_WS_METHODS.subscribeShell, - Effect.succeed( - Stream.unwrap( - Effect.gen(function* () { - // Subscribe to the event feed before reading the snapshot: - // events committed between the two are buffered by the - // subscription instead of lost, which would leave this - // subscriber stale until the next event for that aggregate. - const domainEvents = yield* orchestrationEngine.subscribeDomainEvents; - - const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe( - Effect.tapError((cause) => - Effect.logError("orchestration shell snapshot load failed", { cause }), - ), - Effect.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: "Failed to load orchestration shell snapshot", - cause, - }), - ), - ); - - // Coalesce the domain-event firehose before resolving shells: - // during streaming turns events arrive ~every 50ms per thread, - // and each resolved event costs projection queries plus a full - // thread-shell push per subscriber. - const liveStream = coalesceLatestAggregateEvents( - Stream.filter( - domainEvents, - (event) => event.sequence > snapshot.snapshotSequence, - ), - ).pipe( - Stream.mapEffect(toShellStreamEvent), - Stream.flatMap((event) => - Option.isSome(event) ? Stream.succeed(event.value) : Stream.empty, - ), - ); - - return Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshot, - }), - liveStream, - ); - }), - ), - ), - { "rpc.aggregate": "orchestration" }, - ), + observeRpcStream(ORCHESTRATION_WS_METHODS.subscribeShell, subscribeShell(), { + "rpc.aggregate": "orchestration", + }), [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) => observeRpcEffect( ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, @@ -1774,7 +1751,51 @@ const makeCoreRpcLayer = ( // between the two reads may be both in the snapshot and // re-delivered, which the client's id-keyed upsert reducers // absorb — losing it instead would leave the thread stale. - const domainEvents = yield* orchestrationEngine.subscribeDomainEvents; + const upstreamScope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(upstreamScope, Exit.void)); + const domainEvents = yield* Scope.provide( + orchestrationEngine.subscribeDomainEvents, + upstreamScope, + ); + const isThreadEvent = (event: OrchestrationEvent) => + event.aggregateKind === "thread" && + event.aggregateId === input.threadId && + isThreadDetailEvent(event); + // Drain this subscriber's domain-event feed into a bounded + // per-thread queue so unrelated threads' events are dropped + // right away and a stalled client disconnects to resync + // instead of accumulating unbounded events in memory. Closing + // `upstreamScope` on overflow immediately releases the PubSub + // subscription even if the client stops reading. + const liveQueue = yield* Queue.bounded< + OrchestrationEvent, + OrchestrationGetSnapshotError | Cause.Done + >(THREAD_SUBSCRIBER_QUEUE_CAPACITY); + yield* Stream.runForEach(domainEvents, (event) => { + if (!isThreadEvent(event)) { + return Effect.void; + } + if (!Queue.offerUnsafe(liveQueue, event)) { + Queue.failCauseUnsafe( + liveQueue, + Cause.fail( + new OrchestrationGetSnapshotError({ + message: + "Thread subscription fell behind; reconnecting for a fresh snapshot.", + }), + ), + ); + return Effect.interrupt; + } + return Effect.void; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + Queue.endUnsafe(liveQueue); + }).pipe(Effect.andThen(Scope.close(upstreamScope, Exit.void))), + ), + Effect.forkScoped, + ); const snapshotSequence = yield* projectionSnapshotQuery .getSnapshotSequence() @@ -1788,14 +1809,8 @@ const makeCoreRpcLayer = ( }), ), ); - const isThreadEvent = (event: OrchestrationEvent) => - event.aggregateKind === "thread" && - event.aggregateId === input.threadId && - isThreadDetailEvent(event); - const liveStream = domainEvents.pipe( - Stream.filter( - (event) => event.sequence > snapshotSequence && isThreadEvent(event), - ), + const liveStream = Stream.fromQueue(liveQueue).pipe( + Stream.filter((event) => event.sequence > snapshotSequence), Stream.map((event) => ({ kind: "event" as const, event, @@ -3784,6 +3799,136 @@ export const websocketRpcRouteLayer = Layer.unwrap( const terminalManager = yield* TerminalManager; const pushAlerts = yield* PushAlerts; const deviceChannels = yield* DeviceChannels; + const orchestrationEngine = yield* OrchestrationEngineService; + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + + // One server-wide coalesced shell producer feeds every connected client's + // bounded queue: shell projection queries run once per coalesced window + // (and zero times when nobody is subscribed) instead of once per client. + const toShellStreamEvent = makeToShellStreamEvent(projectionSnapshotQuery); + const shellSubscribers = new Set< + Queue.Queue + >(); + let shellFanoutClosed = false; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + shellFanoutClosed = true; + for (const queue of shellSubscribers) { + Queue.endUnsafe(queue); + } + shellSubscribers.clear(); + }), + ); + const runShellFanoutOnce = Stream.runForEach( + coalesceLatestAggregateEvents(orchestrationEngine.streamDomainEvents), + (event) => + Effect.gen(function* () { + if (shellSubscribers.size === 0) { + return; + } + const shellEvent = yield* toShellStreamEvent(event); + if (Option.isNone(shellEvent)) { + return; + } + for (const queue of shellSubscribers) { + if (!Queue.offerUnsafe(queue, shellEvent.value)) { + shellSubscribers.delete(queue); + Queue.failCauseUnsafe( + queue, + Cause.fail( + new OrchestrationGetSnapshotError({ + message: "Shell subscription fell behind; reconnecting for a fresh snapshot.", + }), + ), + ); + } + } + }), + ); + yield* Effect.gen(function* () { + while (true) { + if (shellFanoutClosed) { + return; + } + const exit = yield* Effect.exit(runShellFanoutOnce); + if (shellFanoutClosed) { + return; + } + if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) { + return; + } + if (exit._tag === "Failure") { + yield* Effect.logError("shared orchestration shell fanout failed; restarting", { + cause: exit.cause, + }); + } + // Fail every live subscriber so clients reconnect for a fresh snapshot + // instead of sitting on a silently stale stream after a producer restart. + for (const queue of shellSubscribers) { + shellSubscribers.delete(queue); + Queue.failCauseUnsafe( + queue, + Cause.fail( + new OrchestrationGetSnapshotError({ + message: "Shell stream restarted; reconnecting for a fresh snapshot.", + }), + ), + ); + } + yield* Effect.sleep(Duration.millis(500)); + } + }).pipe(Effect.forkScoped); + + const subscribeShell: SharedShellSubscribe = () => + Stream.unwrap( + Effect.gen(function* () { + // Register before loading the snapshot so events committed while the + // snapshot loads buffer in this queue instead of being missed. + const queue = yield* Effect.acquireRelease( + Queue.bounded< + OrchestrationShellStreamEvent, + OrchestrationGetSnapshotError | Cause.Done + >(SHELL_SUBSCRIBER_QUEUE_CAPACITY).pipe( + Effect.tap((nextQueue) => + Effect.sync(() => { + shellSubscribers.add(nextQueue); + }), + ), + ), + (nextQueue) => + Effect.sync(() => { + shellSubscribers.delete(nextQueue); + Queue.endUnsafe(nextQueue); + }), + ); + + const snapshot = yield* projectionSnapshotQuery.getShellSnapshot().pipe( + Effect.tapError((cause) => + Effect.logError("orchestration shell snapshot load failed", { cause }), + ), + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration shell snapshot", + cause, + }), + ), + ); + + const liveStream = Stream.fromQueue(queue).pipe( + Stream.filter((event) => event.sequence > snapshot.snapshotSequence), + ); + + return Stream.concat( + Stream.make({ + kind: "snapshot" as const, + snapshot, + }), + liveStream, + ); + }), + ); + return HttpRouter.add( "GET", "/ws", @@ -3799,7 +3944,7 @@ export const websocketRpcRouteLayer = Layer.unwrap( disableTracing: true, }).pipe( Effect.provide( - makeWsRpcLayer(session, viewerId, sentFromRef, devicePlace).pipe( + makeWsRpcLayer(session, viewerId, sentFromRef, devicePlace, subscribeShell).pipe( Layer.provide( Layer.succeed( SourceControlToolMaintenance.SourceControlToolMaintenance, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 27dd18116..d2b34e273 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3346,9 +3346,14 @@ export default function ChatView(props: ChatViewProps) { rightPanelStateKey, ]); + // Whether the thread's messages are its history yet, or only what events and + // this client wrote before its detail snapshot landed (threadDetailLoadedById). + const threadDetailLoaded = useStore((state) => selectThreadDetailLoaded(state, activeThreadRef)); + const envLocked = Boolean( activeThread && (activeThread.messages.length > 0 || + (isServerThread && !threadDetailLoaded) || (activeThread.session !== null && activeThread.session.status !== "closed")), ); @@ -4160,9 +4165,6 @@ export default function ChatView(props: ChatViewProps) { ] !== undefined : false, ); - // Whether the thread's messages are its history yet, or only what events and - // this client wrote before its detail snapshot landed (threadDetailLoadedById). - const threadDetailLoaded = useStore((state) => selectThreadDetailLoaded(state, activeThreadRef)); // The agents panel mounts in the route's right-panel slot, beside the chat // column, so the live turn state it renders has to be published out of here. useEffect(() => { @@ -5790,7 +5792,8 @@ export default function ChatView(props: ChatViewProps) { } } const threadIdForSend = activeThread.id; - const isFirstMessage = !isServerThread || activeThread.messages.length === 0; + const isFirstMessage = + !isServerThread || (threadDetailLoaded && activeThread.messages.length === 0); const steeringThreadKey = activeThreadKey; const isSteeringFollowUp = !askOnTheSide && diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 3607ead36..d00130edb 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1250,8 +1250,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }); // The remembered row, found once the rows are here; only the list's first // mount opens there (a later remount is the end following itself). + // Wait for detail to finish loading before looking up the anchor: shell-only + // rows (such as a scheduled check-back) can render before history arrives and + // would otherwise miss the remembered message and erase its saved scroll spot. const [rememberedScroll, setRememberedScroll] = useState(null); - if (opensAtRememberedPlace && rememberedScroll === null && rows.length > 0) { + if (!detailPending && opensAtRememberedPlace && rememberedScroll === null && rows.length > 0) { setRememberedScroll( initialScrollForThread({ threadKey: scrollMemory!.threadKey, @@ -1328,9 +1331,17 @@ export const MessagesTimeline = memo(function MessagesTimeline({ // Where the chat was when it is left, read once from the list then: the // anchor, or nothing at the end. Nothing is written while scrolling. const scrollMemoryKey = scrollMemory?.threadKey ?? null; + const detailPendingRef = useRef(detailPending); + detailPendingRef.current = detailPending; useLayoutEffect(() => { if (scrollMemoryKey === null) return; return () => { + // Leaving before an evicted thread's detail finishes loading has either + // no list yet or only shell-derived rows; keep the saved scroll anchor + // intact for the next visit. + if (detailPendingRef.current) { + return; + } // Runs once, when the timeline is left. The list is read then, not // when this ran: a pinned list is rebuilt when a turn settles, and an // emptied chat has none. Layout cleanups run before the list leaves diff --git a/apps/web/src/environments/runtime/threadDetailSubscriptions.ts b/apps/web/src/environments/runtime/threadDetailSubscriptions.ts index 5a2e6bf6c..049a9152b 100644 --- a/apps/web/src/environments/runtime/threadDetailSubscriptions.ts +++ b/apps/web/src/environments/runtime/threadDetailSubscriptions.ts @@ -288,8 +288,14 @@ export function createThreadDetailSubscriptions(host: ThreadDetailSubscriptionHo } } + const disconnectedEnvironments = new Set(); + function shouldEvict(entry: ThreadDetailSubscriptionEntry): boolean { - return entry.refCount === 0 && !isNonIdleThread(entry.environmentId, entry.threadId); + return ( + entry.refCount === 0 && + !disconnectedEnvironments.has(entry.environmentId) && + !isNonIdleThread(entry.environmentId, entry.threadId) + ); } function attach(entry: ThreadDetailSubscriptionEntry): boolean { @@ -986,6 +992,7 @@ export function createThreadDetailSubscriptions(host: ThreadDetailSubscriptionHo * wait was for the connection that just got replaced. */ function attachForEnvironment(environmentId: EnvironmentId): void { + disconnectedEnvironments.delete(environmentId); const environmentEntries = [...entries.values()] .filter((entry) => entry.environmentId === environmentId) .toSorted( @@ -997,6 +1004,7 @@ export function createThreadDetailSubscriptions(host: ThreadDetailSubscriptionHo ); for (const entry of environmentEntries) { attach(entry); + reconcileEvictionState(entry); } if (bootGate) { for (const [key, ref] of bootGate.heldWarms) { @@ -1013,10 +1021,14 @@ export function createThreadDetailSubscriptions(host: ThreadDetailSubscriptionHo } function detachForEnvironment(environmentId: EnvironmentId): void { + disconnectedEnvironments.add(environmentId); for (const entry of entries.values()) { if (entry.environmentId !== environmentId) { continue; } + // Keep already-loaded threads readable while offline instead of letting + // the idle timer evict them while the client cannot reload them. + clearEviction(entry); detach(entry); watchConnection(entry); } @@ -1027,6 +1039,7 @@ export function createThreadDetailSubscriptions(host: ThreadDetailSubscriptionHo } function disposeForEnvironment(environmentId: EnvironmentId): void { + disconnectedEnvironments.delete(environmentId); for (const entry of entries.values()) { if (entry.environmentId === environmentId) { disposeByKey(entry.key); @@ -1108,6 +1121,7 @@ export function createThreadDetailSubscriptions(host: ThreadDetailSubscriptionHo bootForegroundHoldTimeoutId = null; } bootStarted = false; + disconnectedEnvironments.clear(); shellLoadedEnvironments.clear(); entriesAwaitingShell.clear(); if (shellWaitCapTimeoutId !== null) { diff --git a/apps/web/src/hooks/useStreamingTextReveal.browser.tsx b/apps/web/src/hooks/useStreamingTextReveal.browser.tsx index 981d36aa6..2268d754a 100644 --- a/apps/web/src/hooks/useStreamingTextReveal.browser.tsx +++ b/apps/web/src/hooks/useStreamingTextReveal.browser.tsx @@ -71,7 +71,41 @@ describe("useStreamingTextReveal", () => { await expect.element(screen.getByTestId("state")).toMatchTextContent("settled"); expect(body.textContent).toBe(`${FULL_TEXT}Trailing block`); expect(body.querySelectorAll("p")[1]?.style.display).toBe(""); + + // Once settled, no animation frames continue firing while idle. + const rafSpy = vi.spyOn(window, "requestAnimationFrame"); + vi.advanceTimersByTime(300); + expect(rafSpy).not.toHaveBeenCalled(); + rafSpy.mockRestore(); + } finally { + vi.useRealTimers(); + } + }); + + it("does not schedule animation frames for settled messages or caught-up pauses", async () => { + vi.useFakeTimers({ toFake: ["requestAnimationFrame", "cancelAnimationFrame", "performance"] }); + const rafSpy = vi.spyOn(window, "requestAnimationFrame"); + try { + function SettledHarness() { + const ref = useRef(null); + const { revealing } = useStreamingTextReveal(ref, false); + return ( +
+
+

{FULL_TEXT}

+
+ {revealing ? "revealing" : "settled"} +
+ ); + } + + const screen = await render(); + await expect.element(screen.getByTestId("settled-state")).toMatchTextContent("settled"); + expect(screen.getByTestId("settled-body").element().textContent).toBe(FULL_TEXT); + vi.advanceTimersByTime(300); + expect(rafSpy).not.toHaveBeenCalled(); } finally { + rafSpy.mockRestore(); vi.useRealTimers(); } }); diff --git a/apps/web/src/hooks/useStreamingTextReveal.ts b/apps/web/src/hooks/useStreamingTextReveal.ts index 7c24967c6..b016a8024 100644 --- a/apps/web/src/hooks/useStreamingTextReveal.ts +++ b/apps/web/src/hooks/useStreamingTextReveal.ts @@ -1,5 +1,5 @@ import { ASSISTANT_STREAM_FLUSH_INTERVAL_MS } from "@threadlines/shared/threadLimits"; -import { type RefObject, useEffect, useLayoutEffect, useRef, useState } from "react"; +import { type RefObject, useLayoutEffect, useRef, useState } from "react"; /** * Reveals streamed assistant text at a steady per-frame pace instead of in the @@ -20,20 +20,56 @@ export function useStreamingTextReveal( const maskRef = useRef(null); streamingRef.current = streaming; + const disposeMask = () => { + const current = maskRef.current; + if (!current) return; + maskRef.current = null; + current.dispose(); + }; + + // Create the DOM observer only when a message actually streams, and tear it + // down once streaming ends and any trailing drain finishes so settled + // history rows carry zero MutationObservers or DOM walks. useLayoutEffect(() => { const container = containerRef.current; - if (!container || prefersReducedMotion()) return; - const mask = new RevealMask(container, () => streamingRef.current, setRevealing); - maskRef.current = mask; - return () => { - mask.dispose(); - maskRef.current = null; - }; - }, [containerRef]); - - useEffect(() => { - maskRef.current?.sync(); - }, [streaming]); + if (!container || prefersReducedMotion()) { + disposeMask(); + setRevealing(false); + return; + } + + const existing = maskRef.current; + if (existing && existing.container !== container) { + disposeMask(); + } + + if (streaming && maskRef.current === null) { + const mask = new RevealMask( + container, + () => streamingRef.current, + setRevealing, + () => { + if (maskRef.current === mask) { + maskRef.current = null; + mask.dispose(); + } + }, + ); + maskRef.current = mask; + return; + } + + if (!streaming && maskRef.current !== null) { + maskRef.current.sync(); + } + }, [containerRef, streaming]); + + useLayoutEffect( + () => () => { + disposeMask(); + }, + [], + ); // Mask each commit of a live message, and the final one that starts its // drain, before anything above it measures the new text. The chat's virtual @@ -139,12 +175,20 @@ class RevealMask { private drain: { startAt: number; from: number } | null = null; private frame: number | null = null; private active = false; + private disposed = false; + private wasStreaming = false; + private awaitingDeferredSettle = false; + private appliedEntryIndex = 0; + private appliedBlockIndex = 0; + private entriesMasked = false; + private blocksMasked = false; private readonly observer: MutationObserver; constructor( - private readonly container: HTMLElement, + readonly container: HTMLElement, private readonly isStreaming: () => boolean, private readonly onActiveChange: (active: boolean) => void, + private readonly onSettled: () => void, ) { this.observer = new MutationObserver(() => this.sync()); this.observer.observe(container, { childList: true, characterData: true, subtree: true }); @@ -152,6 +196,8 @@ class RevealMask { } dispose() { + if (this.disposed) return; + this.disposed = true; this.observer.disconnect(); if (this.frame !== null) cancelAnimationFrame(this.frame); this.frame = null; @@ -160,6 +206,7 @@ class RevealMask { /** Re-reads the DOM after React (or a deferred render) committed new text. */ sync() { + if (this.disposed) return; const now = performance.now(); const previousTotal = this.total; this.collect(); @@ -172,6 +219,10 @@ class RevealMask { } else if (this.total < this.shown) { // Not an append (retry, edit, thread swap): never animate backwards. this.shown = this.total; + this.appliedEntryIndex = 0; + this.appliedBlockIndex = 0; + this.entriesMasked = false; + this.blocksMasked = false; } else if (streaming && this.total > previousTotal) { const grown = this.total - previousTotal; this.rate = @@ -181,10 +232,23 @@ class RevealMask { this.lastGrowthAt = now; } - if (!streaming && this.drain === null && this.shown < this.total) { - this.drain = { startAt: now, from: this.shown }; + if (streaming) { + this.wasStreaming = true; + this.awaitingDeferredSettle = false; + this.drain = null; + } else if (this.shown < this.total) { + this.wasStreaming = false; + this.awaitingDeferredSettle = false; + if (this.drain === null) { + this.drain = { startAt: now, from: this.shown }; + } + } else if (this.wasStreaming) { + // Markdown blocks defer their text via useDeferredValue, so the commit + // that clears `streaming` can land one frame before the final suffix + // appears in the DOM. Keep the observer alive for one frame to catch it. + this.wasStreaming = false; + this.awaitingDeferredSettle = true; } - if (streaming) this.drain = null; this.apply(); this.observer.takeRecords(); @@ -228,22 +292,51 @@ class RevealMask { // Blocks React dropped or re-created come back visible. for (const element of hiddenBefore) element.style.display = ""; this.blocks = blocks; + this.appliedEntryIndex = 0; + this.appliedBlockIndex = 0; + this.entriesMasked = false; + this.blocksMasked = false; } private schedule() { - const pending = this.shown !== null && (this.isStreaming() || this.shown < this.total); - if (pending && this.frame === null) { - this.frame = requestAnimationFrame(this.step); + const streaming = this.isStreaming(); + const needsFrame = + this.shown !== null && + (this.shown < this.total || (!streaming && this.awaitingDeferredSettle)); + const active = this.shown !== null && (streaming || needsFrame); + if (needsFrame) { + if (this.frame === null) { + this.frame = requestAnimationFrame(this.step); + } + } else { + // Caught up to the latest flush: stop burning animation frames until more + // text arrives, and restart the frame clock fresh when it does. + if (this.frame !== null) { + cancelAnimationFrame(this.frame); + this.frame = null; + } + this.lastFrameAt = null; + } + this.setActive(active); + if (!active && !streaming) { + this.onSettled(); } - // Idle again: the next loop starts its clock fresh instead of counting the - // pause as elapsed time. - if (!pending) this.lastFrameAt = null; - this.setActive(pending); } private readonly step = (now: number) => { this.frame = null; - if (this.shown === null) return; + if (this.disposed || this.shown === null) return; + if (!this.isStreaming() && this.awaitingDeferredSettle) { + this.awaitingDeferredSettle = false; + this.collect(); + if (this.shown < this.total && this.drain === null) { + this.drain = { startAt: now, from: this.shown }; + } + this.apply(); + this.observer.takeRecords(); + this.schedule(); + return; + } const dtSeconds = this.lastFrameAt === null ? 0 : (now - this.lastFrameAt) / 1_000; this.lastFrameAt = now; @@ -269,26 +362,60 @@ class RevealMask { private apply() { const shown = this.shown ?? this.total; - for (const entry of this.entries) { + const entries = this.entries; + for (let index = this.appliedEntryIndex; index < entries.length; index += 1) { + const entry = entries[index]!; const end = entry.start + entry.full.length; - const next = - end <= shown - ? entry.full - : entry.start >= shown - ? "" - : entry.full.slice(0, safePrefixLength(entry.full, shown - entry.start)); + if (end <= shown) { + if (entry.written !== entry.full) { + entry.node.data = entry.full; + entry.written = entry.full; + } + if (index === this.appliedEntryIndex) { + this.appliedEntryIndex = index + 1; + } + continue; + } + if (entry.start >= shown) { + if (this.entriesMasked) { + break; + } + if (entry.written !== "") { + entry.node.data = ""; + entry.written = ""; + } + continue; + } + const next = entry.full.slice(0, safePrefixLength(entry.full, shown - entry.start)); if (next !== entry.written) { entry.node.data = next; entry.written = next; } } - for (const block of this.blocks) { - const hidden = block.start >= shown; - if (hidden !== block.hidden) { - block.element.style.display = hidden ? "none" : ""; - block.hidden = hidden; + this.entriesMasked = true; + + const blocks = this.blocks; + for (let index = this.appliedBlockIndex; index < blocks.length; index += 1) { + const block = blocks[index]!; + if (block.start < shown) { + if (block.hidden) { + block.element.style.display = ""; + block.hidden = false; + } + if (index === this.appliedBlockIndex) { + this.appliedBlockIndex = index + 1; + } + continue; + } + if (this.blocksMasked) { + break; + } + if (!block.hidden) { + block.element.style.display = "none"; + block.hidden = true; } } + this.blocksMasked = true; } private restoreAll() { diff --git a/apps/web/src/lib/derivationMemo.ts b/apps/web/src/lib/derivationMemo.ts index 578a3973d..d1a3afd09 100644 --- a/apps/web/src/lib/derivationMemo.ts +++ b/apps/web/src/lib/derivationMemo.ts @@ -84,10 +84,26 @@ export function threadMemoOfInput( }; } +const registeredThreadCaches = new Set>(); + +/** + * Releases cached per-thread derivations for an evicted or removed thread so + * memo inputs (messages, activities) are not pinned in memory after unload. + */ +export function clearThreadDerivationMemos(threadKey: string): void { + for (const cache of registeredThreadCaches) { + cache.delete(threadKey); + } +} + /** Values by thread key, dropping the least recently used past the limit. */ class RecentThreads { private readonly values = new Map(); + constructor() { + registeredThreadCaches.add(this as RecentThreads); + } + get(threadKey: string): V | undefined { const value = this.values.get(threadKey); if (value !== undefined) { @@ -107,6 +123,10 @@ class RecentThreads { } } } + + delete(threadKey: string): void { + this.values.delete(threadKey); + } } function sameFields(left: I, right: I, sameField: FieldComparisons): boolean { diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index b1685e808..203b265a6 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -383,10 +383,13 @@ describe("thread detail loaded", () => { const loaded = syncServerThreadDetail(fromEvents, detail, localEnvironmentId); expect(selectThreadDetailLoaded(loaded, threadRef)).toBe(true); - // Its detail feed ended, or the thread is gone: no longer known whole. - expect(selectThreadDetailLoaded(markThreadDetailUnloaded(loaded, threadRef), threadRef)).toBe( - false, - ); + // Its detail feed ended, or the thread is gone: no longer known whole, and + // detail slices are released while the thread shell stays in the sidebar. + const unloaded = markThreadDetailUnloaded(loaded, threadRef); + expect(selectThreadDetailLoaded(unloaded, threadRef)).toBe(false); + expect(localEnvironmentStateOf(unloaded).threadShellById[threadId]).toBeDefined(); + expect(localEnvironmentStateOf(unloaded).messagesByThreadId[threadId]).toBeUndefined(); + expect(localEnvironmentStateOf(unloaded).activitiesByThreadId[threadId]).toBeUndefined(); const deleted = applyOrchestrationEvent( loaded, makeEvent("thread.deleted", { threadId, deletedAt: "2026-02-27T00:00:03.000Z" }), diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index b7e86d205..5dd5690fd 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -83,9 +83,10 @@ import { type ThreadTurnState, type TurnDiffSummary, } from "./types"; +import { scopedThreadKey } from "@threadlines/client-runtime"; import { resolveEnvironmentHttpUrl } from "./environments/runtime"; import { attachmentPreviewRoutePath } from "./lib/attachmentPreviewQuery"; -import { keyedMemo } from "./lib/derivationMemo"; +import { clearThreadDerivationMemos, keyedMemo } from "./lib/derivationMemo"; import { createBatchedNotifications } from "./lib/batchedNotifications"; import { sanitizeThreadErrorMessage } from "./rpc/transportError"; import { @@ -97,7 +98,7 @@ import { isBlockingUserInput, sumTurnDiffStats, } from "./session-logic"; -import { getThreadFromEnvironmentState } from "./threadDerivation"; +import { getThreadFromEnvironmentState, invalidateThreadDerivationCache } from "./threadDerivation"; import { threadMoveStatus } from "./threadMove"; import { movedFromAfter, @@ -2724,21 +2725,109 @@ export function syncServerThreadDetail( ); } +function omitThreadKey( + record: Record | undefined, + threadId: ThreadId, +): Record | undefined { + if (record === undefined || !(threadId in record)) { + return record; + } + const { [threadId]: _omitted, ...rest } = record; + return rest as Record; +} + /** * The thread's detail feed ended (its subscription was released and - * disposed): what the store holds may fall behind, so the chat waits for the - * next snapshot before it calls an empty thread empty. + * disposed): release its detail slices and derived cache while keeping its + * shell, session, turn state, and sidebar summary intact so reopening fetches + * a fresh snapshot instead of pinning evicted histories in memory. */ export function markThreadDetailUnloaded(state: AppState, threadRef: ScopedThreadRef): AppState { const environmentState = state.environmentStateById[threadRef.environmentId]; - if (!environmentState?.threadDetailLoadedById?.[threadRef.threadId]) { + if (!environmentState) { + return state; + } + const threadId = threadRef.threadId; + const threadDetailLoadedById = omitThreadKey(environmentState.threadDetailLoadedById, threadId); + const messagesByThreadId = omitThreadKey(environmentState.messagesByThreadId, threadId)!; + const activitiesByThreadId = omitThreadKey(environmentState.activitiesByThreadId, threadId)!; + const proposedPlanIdsByThreadId = omitThreadKey( + environmentState.proposedPlanIdsByThreadId, + threadId, + )!; + const proposedPlanByThreadId = omitThreadKey(environmentState.proposedPlanByThreadId, threadId)!; + const turnDiffIdsByThreadId = omitThreadKey(environmentState.turnDiffIdsByThreadId, threadId)!; + const turnDiffSummaryByThreadId = omitThreadKey( + environmentState.turnDiffSummaryByThreadId, + threadId, + )!; + const agentRequestsByThreadId = omitThreadKey( + environmentState.agentRequestsByThreadId, + threadId, + )!; + const pagesByThreadId = omitThreadKey(environmentState.pagesByThreadId, threadId); + const workflowRunsByThreadId = omitThreadKey(environmentState.workflowRunsByThreadId, threadId); + const subagentsByThreadId = omitThreadKey(environmentState.subagentsByThreadId, threadId); + const commandRequestsByThreadId = omitThreadKey( + environmentState.commandRequestsByThreadId, + threadId, + ); + const commandRunsByThreadId = omitThreadKey(environmentState.commandRunsByThreadId, threadId); + const childRequestsByThreadId = omitThreadKey( + environmentState.childRequestsByThreadId, + threadId, + )!; + const settingsRequestsByThreadId = omitThreadKey( + environmentState.settingsRequestsByThreadId, + threadId, + ); + const secretRequestsByThreadId = omitThreadKey( + environmentState.secretRequestsByThreadId, + threadId, + ); + + invalidateThreadDerivationCache(environmentState.threadShellById[threadId]); + clearThreadDerivationMemos(scopedThreadKey(threadRef)); + + if ( + threadDetailLoadedById === environmentState.threadDetailLoadedById && + messagesByThreadId === environmentState.messagesByThreadId && + activitiesByThreadId === environmentState.activitiesByThreadId && + proposedPlanIdsByThreadId === environmentState.proposedPlanIdsByThreadId && + proposedPlanByThreadId === environmentState.proposedPlanByThreadId && + turnDiffIdsByThreadId === environmentState.turnDiffIdsByThreadId && + turnDiffSummaryByThreadId === environmentState.turnDiffSummaryByThreadId && + agentRequestsByThreadId === environmentState.agentRequestsByThreadId && + pagesByThreadId === environmentState.pagesByThreadId && + workflowRunsByThreadId === environmentState.workflowRunsByThreadId && + subagentsByThreadId === environmentState.subagentsByThreadId && + commandRequestsByThreadId === environmentState.commandRequestsByThreadId && + commandRunsByThreadId === environmentState.commandRunsByThreadId && + childRequestsByThreadId === environmentState.childRequestsByThreadId && + settingsRequestsByThreadId === environmentState.settingsRequestsByThreadId && + secretRequestsByThreadId === environmentState.secretRequestsByThreadId + ) { return state; } - const { [threadRef.threadId]: _unloaded, ...threadDetailLoadedById } = - environmentState.threadDetailLoadedById; + return commitEnvironmentState(state, threadRef.environmentId, { ...environmentState, - threadDetailLoadedById, + messagesByThreadId, + activitiesByThreadId, + proposedPlanIdsByThreadId, + proposedPlanByThreadId, + turnDiffIdsByThreadId, + turnDiffSummaryByThreadId, + agentRequestsByThreadId, + childRequestsByThreadId, + ...(threadDetailLoadedById !== undefined ? { threadDetailLoadedById } : {}), + ...(pagesByThreadId !== undefined ? { pagesByThreadId } : {}), + ...(workflowRunsByThreadId !== undefined ? { workflowRunsByThreadId } : {}), + ...(subagentsByThreadId !== undefined ? { subagentsByThreadId } : {}), + ...(commandRequestsByThreadId !== undefined ? { commandRequestsByThreadId } : {}), + ...(commandRunsByThreadId !== undefined ? { commandRunsByThreadId } : {}), + ...(settingsRequestsByThreadId !== undefined ? { settingsRequestsByThreadId } : {}), + ...(secretRequestsByThreadId !== undefined ? { secretRequestsByThreadId } : {}), }); } diff --git a/apps/web/src/threadDerivation.ts b/apps/web/src/threadDerivation.ts index 93c3a0cb1..ddcbe332c 100644 --- a/apps/web/src/threadDerivation.ts +++ b/apps/web/src/threadDerivation.ts @@ -67,6 +67,12 @@ function collectByIds( return nextValues; } +export function invalidateThreadDerivationCache(shell: ThreadShell | undefined): void { + if (shell) { + threadCache.delete(shell); + } +} + export function selectThreadMessages( state: EnvironmentState, threadId: ThreadId, diff --git a/packages/shared/src/DrainableWorker.test.ts b/packages/shared/src/DrainableWorker.test.ts index 8e4c654e2..0c6fbff35 100644 --- a/packages/shared/src/DrainableWorker.test.ts +++ b/packages/shared/src/DrainableWorker.test.ts @@ -3,7 +3,7 @@ import { describe, expect } from "vite-plus/test"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import { makeDrainableWorker } from "./DrainableWorker.ts"; +import { makeDrainableWorker, makeKeyedDrainableWorker } from "./DrainableWorker.ts"; describe("makeDrainableWorker", () => { it.live("waits for work enqueued during active processing before draining", () => @@ -55,3 +55,59 @@ describe("makeDrainableWorker", () => { ), ); }); + +describe("makeKeyedDrainableWorker", () => { + it.live("runs distinct keys concurrently while keeping each key strictly FIFO", () => + Effect.scoped( + Effect.gen(function* () { + const processed: Array = []; + const a1Started = yield* Deferred.make(); + const b1Started = yield* Deferred.make(); + const releaseA1 = yield* Deferred.make(); + const releaseB1 = yield* Deferred.make(); + + const worker = yield* makeKeyedDrainableWorker( + (item: { readonly key: string; readonly id: string }) => + Effect.gen(function* () { + if (item.id === "a1") { + yield* Deferred.succeed(a1Started, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseA1); + } + if (item.id === "b1") { + yield* Deferred.succeed(b1Started, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseB1); + } + processed.push(item.id); + }), + { + keyOf: (item) => item.key, + maxConcurrency: 2, + }, + ); + + yield* worker.enqueue({ key: "a", id: "a1" }); + yield* worker.enqueue({ key: "a", id: "a2" }); + yield* worker.enqueue({ key: "b", id: "b1" }); + + // Key "b" starts without waiting for key "a" to finish. + yield* Deferred.await(a1Started); + yield* Deferred.await(b1Started); + + const drained = yield* Deferred.make(); + yield* Effect.forkChild( + worker.drain.pipe( + Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie)), + ), + ); + + yield* Deferred.succeed(releaseB1, undefined); + yield* Deferred.succeed(releaseA1, undefined); + yield* Deferred.await(drained); + + expect(processed.indexOf("a1")).toBeLessThan(processed.indexOf("a2")); + expect(processed).toHaveLength(3); + expect(new Set(processed)).toEqual(new Set(["a1", "a2", "b1"])); + }), + ), + ); +}); diff --git a/packages/shared/src/DrainableWorker.ts b/packages/shared/src/DrainableWorker.ts index de40ec5e3..a93a8be49 100644 --- a/packages/shared/src/DrainableWorker.ts +++ b/packages/shared/src/DrainableWorker.ts @@ -8,6 +8,7 @@ * * @module DrainableWorker */ +import * as Cause from "effect/Cause"; import * as Scope from "effect/Scope"; import * as Effect from "effect/Effect"; import * as TxQueue from "effect/TxQueue"; @@ -68,3 +69,170 @@ export const makeDrainableWorker = ( return { enqueue, drain } satisfies DrainableWorker
; }); + +export interface KeyedDrainableWorkerOptions { + readonly keyOf: (item: A) => K; + readonly maxConcurrency: number; +} + +interface QueueNode { + readonly head: A; + readonly tail: QueueNode | null; +} + +/** Persistent FIFO queue (Okasaki banker's queue) with O(1) amortized append and pop, safe under STM retries. */ +interface KeyedLane { + readonly front: QueueNode | null; + readonly back: QueueNode | null; +} + +function laneIsEmpty(lane: KeyedLane | undefined): boolean { + return lane === undefined || (lane.front === null && lane.back === null); +} + +function laneEnqueue(lane: KeyedLane | undefined, item: A): KeyedLane { + if (lane === undefined) { + return { front: { head: item, tail: null }, back: null }; + } + return { front: lane.front, back: { head: item, tail: lane.back } }; +} + +function laneDequeue(lane: KeyedLane): readonly [item: A, rest: KeyedLane | null] | null { + let front = lane.front; + let back = lane.back; + if (front === null) { + if (back === null) { + return null; + } + while (back !== null) { + front = { head: back.head, tail: front }; + back = back.tail; + } + } + const item = front!.head; + const nextFront = front!.tail; + if (nextFront === null && back === null) { + return [item, null] as const; + } + return [item, { front: nextFront, back }] as const; +} + +interface KeyedDrainableWorkerState { + readonly lanesByKey: Map>; + readonly queuedKeys: Set; + readonly activeKeys: Set; + readonly outstanding: number; +} + +/** + * Create a drainable worker sharded by key. + * + * Items sharing a key run strictly FIFO one at a time, while distinct keys run + * concurrently up to `maxConcurrency`. Keys with more queued work rotate to the + * back of the ready queue after each item so one busy key cannot starve others. + */ +export const makeKeyedDrainableWorker = ( + process: (item: A) => Effect.Effect, + options: KeyedDrainableWorkerOptions, +): Effect.Effect, never, Scope.Scope | R> => + Effect.gen(function* () { + const concurrency = Math.max(1, Math.floor(options.maxConcurrency)); + const readyKeys = yield* Effect.acquireRelease(TxQueue.unbounded(), TxQueue.shutdown); + const stateRef = yield* TxRef.make>({ + lanesByKey: new Map(), + queuedKeys: new Set(), + activeKeys: new Set(), + outstanding: 0, + }); + + const releaseKey = (key: K): Effect.Effect => + TxRef.modify(stateRef, (state) => { + const activeKeys = new Set(state.activeKeys); + activeKeys.delete(key); + const outstanding = Math.max(0, state.outstanding - 1); + const lane = state.lanesByKey.get(key); + if (!laneIsEmpty(lane) && !state.queuedKeys.has(key)) { + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.add(key); + return [true, { ...state, activeKeys, queuedKeys, outstanding }] as const; + } + return [false, { ...state, activeKeys, outstanding }] as const; + }).pipe( + Effect.flatMap((shouldRequeue) => + shouldRequeue ? TxQueue.offer(readyKeys, key) : Effect.void, + ), + Effect.tx, + Effect.asVoid, + ); + + const takeNextForKey = (key: K) => + TxRef.modify(stateRef, (state) => { + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.delete(key); + const lane = state.lanesByKey.get(key); + const dequeued = lane === undefined ? null : laneDequeue(lane); + if (dequeued === null) { + const lanesByKey = new Map(state.lanesByKey); + lanesByKey.delete(key); + return [null, { ...state, lanesByKey, queuedKeys }] as const; + } + const [item, rest] = dequeued; + const lanesByKey = new Map(state.lanesByKey); + if (rest === null) { + lanesByKey.delete(key); + } else { + lanesByKey.set(key, rest); + } + const activeKeys = new Set(state.activeKeys); + activeKeys.add(key); + return [{ key, item } as const, { ...state, lanesByKey, queuedKeys, activeKeys }] as const; + }).pipe(Effect.tx); + + const workerLoop = TxQueue.take(readyKeys).pipe( + Effect.flatMap(takeNextForKey), + Effect.flatMap((taken) => + taken === null + ? Effect.void + : process(taken.item).pipe( + Effect.catchCause((cause) => + Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : Effect.void, + ), + Effect.ensuring(releaseKey(taken.key)), + ), + ), + Effect.forever, + ); + + for (let index = 0; index < concurrency; index += 1) { + yield* Effect.forkScoped(workerLoop); + } + + const enqueue: DrainableWorker["enqueue"] = (item) => { + const key = options.keyOf(item); + return TxRef.modify(stateRef, (state) => { + const lanesByKey = new Map(state.lanesByKey); + lanesByKey.set(key, laneEnqueue(lanesByKey.get(key), item)); + const outstanding = state.outstanding + 1; + if (state.queuedKeys.has(key) || state.activeKeys.has(key)) { + return [false, { ...state, lanesByKey, outstanding }] as const; + } + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.add(key); + return [true, { ...state, lanesByKey, queuedKeys, outstanding }] as const; + }).pipe( + Effect.flatMap((shouldOffer) => + shouldOffer ? TxQueue.offer(readyKeys, key) : Effect.void, + ), + Effect.tx, + Effect.asVoid, + ); + }; + + const drain: DrainableWorker["drain"] = TxRef.get(stateRef).pipe( + Effect.tap((state) => (state.outstanding > 0 ? Effect.txRetry : Effect.void)), + Effect.asVoid, + Effect.tx, + ); + + return { enqueue, drain } satisfies DrainableWorker; + }); diff --git a/packages/shared/src/logging.ts b/packages/shared/src/logging.ts index 8e1d1019e..85780392a 100644 --- a/packages/shared/src/logging.ts +++ b/packages/shared/src/logging.ts @@ -1,5 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off import fs from "node:fs"; +import fsp from "node:fs/promises"; import path from "node:path"; export interface RotatingFileSinkOptions { @@ -9,8 +10,35 @@ export interface RotatingFileSinkOptions { readonly throwOnError?: boolean; } +function isFileNotFoundError(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error as { readonly code?: unknown }).code === "ENOENT" + ); +} + +interface SharedPathState { + pendingWrite: Promise; + activeOps: number; + currentSize: number | null; +} + +const sharedPathStates = new Map(); + +function getOrCreateSharedPathState(resolvedPath: string): SharedPathState { + let state = sharedPathStates.get(resolvedPath); + if (state === undefined) { + state = { pendingWrite: Promise.resolve(), activeOps: 0, currentSize: null }; + sharedPathStates.set(resolvedPath, state); + } + return state; +} + export class RotatingFileSink { private readonly filePath: string; + private readonly resolvedPath: string; private readonly maxBytes: number; private readonly maxFiles: number; private readonly throwOnError: boolean; @@ -25,6 +53,7 @@ export class RotatingFileSink { } this.filePath = options.filePath; + this.resolvedPath = path.resolve(options.filePath); this.maxBytes = options.maxBytes; this.maxFiles = options.maxFiles; this.throwOnError = options.throwOnError ?? false; @@ -38,6 +67,11 @@ export class RotatingFileSink { const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk; if (buffer.length === 0) return; + const shared = sharedPathStates.get(this.resolvedPath); + if (shared !== undefined && shared.currentSize !== null) { + this.currentSize = shared.currentSize; + } + try { if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) { this.rotate(); @@ -49,14 +83,117 @@ export class RotatingFileSink { if (this.currentSize > this.maxBytes) { this.rotate(); } + if (shared !== undefined) { + shared.currentSize = this.currentSize; + } } catch { this.currentSize = this.readCurrentSize(); + if (shared !== undefined) { + shared.currentSize = this.currentSize; + } if (this.throwOnError) { throw new Error(`Failed to write log chunk to ${this.filePath}`); } } } + /** + * Appends a chunk without blocking the event loop, serialized per resolved + * destination path so multiple sinks writing to the same log file (such as + * native and canonical provider logs) never interleave appends or rotations. + */ + writeAsync(chunk: string | Buffer): Promise { + const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk; + const shared = getOrCreateSharedPathState(this.resolvedPath); + if (buffer.length === 0) return shared.pendingWrite; + + shared.activeOps += 1; + const next = shared.pendingWrite.then(() => this.writeAsyncUnserialized(shared, buffer)); + shared.pendingWrite = next + .catch(() => undefined) + .finally(() => { + shared.activeOps -= 1; + if (shared.activeOps === 0 && sharedPathStates.get(this.resolvedPath) === shared) { + sharedPathStates.delete(this.resolvedPath); + } + }); + return next; + } + + /** Waits for any in-flight async writes to settle for this path. */ + drain(): Promise { + return sharedPathStates.get(this.resolvedPath)?.pendingWrite ?? Promise.resolve(); + } + + private async writeAsyncUnserialized(shared: SharedPathState, buffer: Buffer): Promise { + if (shared.currentSize === null) { + this.currentSize = await this.readCurrentSizeAsync(); + shared.currentSize = this.currentSize; + } else { + this.currentSize = shared.currentSize; + } + try { + if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) { + await this.rotateAsync(); + } + + await fsp.appendFile(this.filePath, buffer); + this.currentSize += buffer.length; + + if (this.currentSize > this.maxBytes) { + await this.rotateAsync(); + } + shared.currentSize = this.currentSize; + } catch { + this.currentSize = await this.readCurrentSizeAsync(); + shared.currentSize = this.currentSize; + if (this.throwOnError) { + throw new Error(`Failed to write log chunk to ${this.filePath}`); + } + } + } + + private async rotateAsync(): Promise { + try { + await fsp.rm(this.withSuffix(this.maxFiles), { force: true }); + + for (let index = this.maxFiles - 1; index >= 1; index -= 1) { + const source = this.withSuffix(index); + const target = this.withSuffix(index + 1); + try { + await fsp.rename(source, target); + } catch (error) { + if (!isFileNotFoundError(error)) { + throw error; + } + } + } + + try { + await fsp.rename(this.filePath, this.withSuffix(1)); + } catch (error) { + if (!isFileNotFoundError(error)) { + throw error; + } + } + + this.currentSize = 0; + } catch { + this.currentSize = await this.readCurrentSizeAsync(); + if (this.throwOnError) { + throw new Error(`Failed to rotate log file ${this.filePath}`); + } + } + } + + private async readCurrentSizeAsync(): Promise { + try { + return (await fsp.stat(this.filePath)).size; + } catch { + return 0; + } + } + private rotate(): void { try { const oldest = this.withSuffix(this.maxFiles); diff --git a/packages/shared/src/observability.test.ts b/packages/shared/src/observability.test.ts index d0965eef9..2141258cd 100644 --- a/packages/shared/src/observability.test.ts +++ b/packages/shared/src/observability.test.ts @@ -70,6 +70,26 @@ const readTraceRecords = Effect.fn("readTraceRecords")(function* (tracePath: str .map((line) => decodeTraceRecordLine(line)); }); +const waitUntil = (predicate: () => boolean, timeoutMs = 2_000): Effect.Effect => + Effect.promise( + () => + new Promise((resolve, reject) => { + const deadline = Date.now() + timeoutMs; + const check = () => { + if (predicate()) { + resolve(); + return; + } + if (Date.now() >= deadline) { + reject(new Error("Timed out waiting for async trace flush")); + return; + } + setTimeout(check, 5); + }; + check(); + }), + ); + const makeTestLayer = (tracePath: string) => Layer.mergeAll( Layer.effect( @@ -175,13 +195,14 @@ describe("observability", () => { yield* Effect.yieldNow; assert.equal(fs.existsSync(tracePath), false); yield* TestClock.adjust("1 millis"); + yield* waitUntil(() => fs.existsSync(tracePath)); yield* Effect.yieldNow; assert.equal(fs.existsSync(tracePath), true); sink.push(makeRecord("second")); assert.equal(fs.readFileSync(tracePath, "utf8").includes('"name":"second"'), false); yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; + yield* waitUntil(() => fs.readFileSync(tracePath, "utf8").includes('"name":"second"')); const records = yield* readTraceRecords(tracePath); assert.deepStrictEqual( @@ -444,7 +465,11 @@ describe("observability", () => { ); yield* TestClock.adjust("1 second"); - yield* Effect.yieldNow; + yield* waitUntil( + () => + fs.existsSync(`${tracePath}.1`) && + fs.readFileSync(tracePath, "utf8").includes('"name":"third"'), + ); const names = ["shared.trace.ndjson.2", "shared.trace.ndjson.1", "shared.trace.ndjson"] .filter((entry) => fs.existsSync(path.join(tempDir, entry))) @@ -467,16 +492,18 @@ describe("observability", () => { const path = yield* Path.Path; const tempDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-trace-sink-" }); const tracePath = path.join(tempDir, "shared.trace.ndjson"); - const realAppendFileSync = fs.appendFileSync.bind(fs); + const realAppendFile = fs.promises.appendFile.bind(fs.promises); let appendAttempts = 0; let failWrites = true; - const appendSpy = vi.spyOn(fs, "appendFileSync").mockImplementation((...args) => { - appendAttempts += 1; - if (failWrites) { - throw new Error("simulated trace write failure"); - } - Reflect.apply(realAppendFileSync, fs, args); - }); + const appendSpy = vi + .spyOn(fs.promises, "appendFile") + .mockImplementation(async (...args) => { + appendAttempts += 1; + if (failWrites) { + throw new Error("simulated trace write failure"); + } + await Reflect.apply(realAppendFile, fs.promises, args); + }); yield* Effect.addFinalizer(() => Effect.sync(() => appendSpy.mockRestore())); yield* TestClock.setTime(0); @@ -489,31 +516,38 @@ describe("observability", () => { }); sink.push(makeRecord("first")); + yield* waitUntil(() => appendAttempts === 1); + yield* Effect.yieldNow; assert.equal(appendAttempts, 1); sink.push(makeRecord("second")); + yield* Effect.yieldNow; assert.equal(appendAttempts, 1); yield* TestClock.adjust("199 millis"); yield* Effect.yieldNow; assert.equal(appendAttempts, 1); yield* TestClock.adjust("1 millis"); + yield* waitUntil(() => appendAttempts === 2); yield* Effect.yieldNow; assert.equal(appendAttempts, 2); sink.push(makeRecord("third")); + yield* Effect.yieldNow; assert.equal(appendAttempts, 2); yield* TestClock.adjust("399 millis"); yield* Effect.yieldNow; assert.equal(appendAttempts, 2); yield* TestClock.adjust("1 millis"); + yield* waitUntil(() => appendAttempts === 3); yield* Effect.yieldNow; assert.equal(appendAttempts, 3); let expectedAttempts = 3; for (const delayMs of [800, 1_600, 3_200, 6_400, 12_800, 25_600, 30_000]) { yield* TestClock.adjust(`${delayMs} millis`); - yield* Effect.yieldNow; expectedAttempts += 1; + yield* waitUntil(() => appendAttempts === expectedAttempts); + yield* Effect.yieldNow; assert.equal(appendAttempts, expectedAttempts); } assert.equal(appendAttempts, 10); @@ -521,9 +555,11 @@ describe("observability", () => { yield* Effect.yieldNow; assert.equal(appendAttempts, 10); yield* TestClock.adjust("1 millis"); + yield* waitUntil(() => appendAttempts === 11); yield* Effect.yieldNow; assert.equal(appendAttempts, 11); yield* TestClock.adjust("30 seconds"); + yield* waitUntil(() => appendAttempts === 12); yield* Effect.yieldNow; assert.equal(appendAttempts, 12); diff --git a/packages/shared/src/observability.ts b/packages/shared/src/observability.ts index 51aeb7606..62d2b8d78 100644 --- a/packages/shared/src/observability.ts +++ b/packages/shared/src/observability.ts @@ -4,6 +4,7 @@ import type * as Exit from "effect/Exit"; import * as ExitRuntime from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; +import * as Semaphore from "effect/Semaphore"; import * as Tracer from "effect/Tracer"; import { OtlpResource, OtlpTracer } from "effect/observability"; @@ -290,15 +291,18 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac }); const runFork = Effect.runForkWith(yield* Effect.context()); + const flushSemaphore = yield* Semaphore.make(1); let closed = false; let flushFiber: Fiber.Fiber | undefined; + let immediateFlushFiber: Fiber.Fiber | undefined; let flushFailed = false; let nextRetryDelayMs = initialRetryDelayMs; let bufferedBytes = 0; + let inFlightBytes = 0; let buffer: Array<{ readonly line: string; readonly bytes: number }> = []; - const trimRetryBuffer = (): void => { - while (bufferedBytes > maxBufferedBytes && buffer.length > 0) { + const trimBufferedRecords = (): void => { + while (bufferedBytes + inFlightBytes > maxBufferedBytes && buffer.length > 0) { const dropped = buffer.shift(); if (!dropped) { break; @@ -307,61 +311,109 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac } }; - const flushUnsafe = () => { - if (buffer.length === 0) { - return; - } - - const records = buffer; - buffer = []; - bufferedBytes = 0; - let persistedCount = 0; - - while (persistedCount < records.length) { - const firstRecord = records[persistedCount]; - if (!firstRecord) { - break; - } - if (firstRecord.bytes > options.maxBytes) { - persistedCount += 1; - continue; - } + const runFlushOnce = (allowDuringBackoff: boolean) => + flushSemaphore.withPermits(1)( + Effect.gen(function* () { + if (buffer.length === 0 || (!allowDuringBackoff && flushFailed)) { + return; + } - let nextIndex = persistedCount + 1; - let chunkBytes = firstRecord.bytes; - while (nextIndex < records.length) { - const nextRecord = records[nextIndex]; - if (!nextRecord || chunkBytes + nextRecord.bytes > options.maxBytes) { - break; + const records = buffer; + inFlightBytes = bufferedBytes; + buffer = []; + bufferedBytes = 0; + let persistedCount = 0; + + try { + while (persistedCount < records.length) { + const firstRecord = records[persistedCount]; + if (!firstRecord) { + break; + } + if (firstRecord.bytes > options.maxBytes) { + inFlightBytes = Math.max(0, inFlightBytes - firstRecord.bytes); + persistedCount += 1; + continue; + } + + let nextIndex = persistedCount + 1; + let chunkBytes = firstRecord.bytes; + while (nextIndex < records.length) { + const nextRecord = records[nextIndex]; + if (!nextRecord || chunkBytes + nextRecord.bytes > options.maxBytes) { + break; + } + chunkBytes += nextRecord.bytes; + nextIndex += 1; + } + + const chunk = records + .slice(persistedCount, nextIndex) + .map((record) => record.line) + .join(""); + const written = yield* Effect.tryPromise(() => sink.writeAsync(chunk)).pipe( + Effect.as(true), + Effect.catch(() => Effect.succeed(false)), + ); + if (!written) { + inFlightBytes = 0; + buffer = [...records.slice(persistedCount), ...buffer]; + bufferedBytes = buffer.reduce((total, record) => total + record.bytes, 0); + trimBufferedRecords(); + nextRetryDelayMs = flushFailed + ? Math.min(MAX_RETRY_DELAY_MS, nextRetryDelayMs * 2) + : initialRetryDelayMs; + flushFailed = buffer.length > 0; + return; + } + inFlightBytes = Math.max(0, inFlightBytes - chunkBytes); + persistedCount = nextIndex; + } + flushFailed = false; + nextRetryDelayMs = initialRetryDelayMs; + } finally { + inFlightBytes = 0; } - chunkBytes += nextRecord.bytes; - nextIndex += 1; - } + }).pipe(Effect.uninterruptible, Effect.withTracerEnabled(false)), + ); - const chunk = records - .slice(persistedCount, nextIndex) - .map((record) => record.line) - .join(""); - try { - sink.write(chunk); - } catch { - buffer = [...records.slice(persistedCount), ...buffer]; - bufferedBytes = buffer.reduce((total, record) => total + record.bytes, 0); - trimRetryBuffer(); - nextRetryDelayMs = flushFailed - ? Math.min(MAX_RETRY_DELAY_MS, nextRetryDelayMs * 2) - : initialRetryDelayMs; - flushFailed = buffer.length > 0; - return; - } - persistedCount = nextIndex; + const shouldFlushImmediately = (): boolean => + !flushFailed && + (batchWindowMs <= 0 || + buffer.length >= FLUSH_BUFFER_THRESHOLD || + bufferedBytes >= maxBufferedBytes); + + const triggerImmediateFlush = (): void => { + if (closed || immediateFlushFiber !== undefined || buffer.length === 0) { + return; } - flushFailed = false; - nextRetryDelayMs = initialRetryDelayMs; + const scheduled = flushFiber; + flushFiber = undefined; + immediateFlushFiber = runFork( + Effect.gen(function* () { + if (scheduled) { + yield* Fiber.interrupt(scheduled).pipe(Effect.ignore); + } + yield* runFlushOnce(false); + immediateFlushFiber = undefined; + if (!closed && buffer.length > 0) { + if (shouldFlushImmediately()) { + triggerImmediateFlush(); + } else { + scheduleFlush(); + } + } + }).pipe(Effect.withTracerEnabled(false)), + ); }; const scheduleFlush = (): void => { - if (closed || flushFiber !== undefined || buffer.length === 0) { + if ( + closed || + flushFiber !== undefined || + immediateFlushFiber !== undefined || + buffer.length === 0 + ) { return; } @@ -373,10 +425,16 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac flushFiber = runFork( Effect.sleep(`${delayMs} millis`).pipe( Effect.andThen( - Effect.sync(() => { + Effect.gen(function* () { + yield* runFlushOnce(true); flushFiber = undefined; - flushUnsafe(); - scheduleFlush(); + if (!closed && buffer.length > 0) { + if (shouldFlushImmediately()) { + triggerImmediateFlush(); + } else { + scheduleFlush(); + } + } }), ), Effect.withTracerEnabled(false), @@ -390,10 +448,8 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac if (scheduled) { yield* Fiber.interrupt(scheduled).pipe(Effect.ignore); } - yield* Effect.sync(() => { - flushUnsafe(); - scheduleFlush(); - }); + yield* runFlushOnce(true); + scheduleFlush(); }).pipe(Effect.withTracerEnabled(false)); const close = Effect.gen(function* () { @@ -403,7 +459,12 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac if (scheduled) { yield* Fiber.interrupt(scheduled).pipe(Effect.ignore); } - yield* Effect.sync(flushUnsafe); + const immediate = immediateFlushFiber; + if (immediate) { + yield* Fiber.await(immediate).pipe(Effect.ignore); + immediateFlushFiber = undefined; + } + yield* runFlushOnce(true); }).pipe(Effect.withTracerEnabled(false)); yield* Effect.addFinalizer(() => close.pipe(Effect.ignore)); @@ -422,18 +483,14 @@ export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: Trac } buffer.push({ line, bytes }); bufferedBytes += bytes; - if (flushFailed) { - trimRetryBuffer(); + if (flushFailed || inFlightBytes > 0) { + trimBufferedRecords(); } - if ( - !flushFailed && - (batchWindowMs <= 0 || - buffer.length >= FLUSH_BUFFER_THRESHOLD || - bufferedBytes >= maxBufferedBytes) - ) { - flushUnsafe(); + if (shouldFlushImmediately()) { + triggerImmediateFlush(); + } else { + scheduleFlush(); } - scheduleFlush(); } catch { return; } From f55adc23e5a00e7f6f3c0969e9a343904c29c442 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:16:29 -0500 Subject: [PATCH 4/4] perf: cut polling, relay copy, git spawn, and runtime overhead Reduces background polling, process spawns, memory retention, and hot-path work across server, web, desktop, shared, and client-runtime without changing user-visible behavior. - Relay: pass fixed ArrayBuffer views directly to WebCrypto, build header-prefixed records in one allocation, and avoid double-copying single-part frames. - Providers: slow disabled provider scheduled refreshes by 6x, cap refreshAll concurrency to 3, cache scheduled Claude token usage within the same UTC day, and cache claude --version by resolved executable stat metadata. - Git and workspace: skip numstat diffs on clean status checks, reuse status GitConfigSnapshot in GitManager, cap background remote refreshes to 4 with post-permit re-checks, and filter ignored tracked files via git ls-files --cached --ignored. - Pull requests: raise viewer and repository cache capacities to 64, run authored searches in parallel with workspace listings, share worktree listings per sweep with fresh revalidation before auto-merge, and back off confirmed missing worktrees. - Server and client cleanups: cache ProjectFaviconResolver lookups, stop retaining raw SDK messages in ClaudeAdapter turnState.items, tag OpenCode and ACP streaming chunks as stream fragments, cache compiled search regexes, track MJPEG scan cursors, replace Equal.equals on work rows, skip redundant activity sorts, lazy-load DiffWorkerPoolProvider, pause the desktop backdrop CPU watchdog when art is still or hidden, and cache mainFrameId in PreviewAutomation. --- apps/desktop/src/preview/PreviewAutomation.ts | 94 ++++++-- .../src/window/DesktopBackdropMonitor.ts | 73 +++++- apps/server/src/git/GitManager.test.ts | 4 +- apps/server/src/git/GitManager.ts | 8 +- .../Layers/PullRequestAutomationWatcher.ts | 228 +++++++++++++----- .../project/Layers/ProjectFaviconResolver.ts | 34 ++- .../src/provider/Drivers/ClaudeDriver.ts | 208 ++++++++++++---- .../src/provider/Drivers/CodexDriver.ts | 1 + .../server/src/provider/Drivers/MuseDriver.ts | 1 + .../src/provider/Drivers/OpenCodeDriver.ts | 1 + apps/server/src/provider/Drivers/PiDriver.ts | 1 + .../src/provider/Layers/ClaudeAdapter.ts | 5 - .../src/provider/Layers/OpenCodeAdapter.ts | 6 + .../src/provider/Layers/ProviderRegistry.ts | 2 +- apps/server/src/provider/acp/AcpAdapter.ts | 16 +- .../src/provider/acp/AcpNativeLogging.ts | 53 ++++ .../src/provider/acp/AcpProviderDriver.ts | 1 + .../src/provider/makeManagedServerProvider.ts | 23 +- .../src/pullRequest/PullRequestService.ts | 114 +++++---- apps/server/src/relay/securePipe.ts | 4 +- apps/server/src/vcs/GitVcsDriver.ts | 42 ++++ apps/server/src/vcs/GitVcsDriverCore.ts | 14 +- apps/server/src/vcs/VcsDriver.ts | 7 + apps/server/src/vcs/VcsStatusBroadcaster.ts | 41 +++- .../src/workspace/Layers/WorkspaceEntries.ts | 34 ++- .../components/chat/MessagesTimeline.logic.ts | 68 +++++- apps/web/src/diffPanelPreload.ts | 1 + .../routes/_chat.$environmentId.$threadId.tsx | 25 +- apps/web/src/store.ts | 24 +- apps/web/src/theme/ThemeBackdropLayer.tsx | 9 +- packages/client-runtime/src/device/mjpeg.ts | 22 +- packages/shared/src/relaySecure.ts | 85 +++++-- packages/shared/src/searchRanking.ts | 64 ++++- 33 files changed, 1043 insertions(+), 270 deletions(-) diff --git a/apps/desktop/src/preview/PreviewAutomation.ts b/apps/desktop/src/preview/PreviewAutomation.ts index 67add673f..7e91c9f1f 100644 --- a/apps/desktop/src/preview/PreviewAutomation.ts +++ b/apps/desktop/src/preview/PreviewAutomation.ts @@ -272,6 +272,10 @@ interface AttachedTab { * numbers are given. */ framesByOrdinal: Map; + /** True once `Page.enable` has succeeded on this debugger attachment. */ + pageDomainEnabled: boolean; + /** Cached top-level frame id for this debugger attachment; updated on navigation. */ + mainFrameId: string | undefined; dispose: () => void; } @@ -1059,23 +1063,81 @@ export const make = Effect.gen(function* PreviewAutomationMake() { timeout?: Duration.Input, ) { const sessionId = frame?.sessionId; + const tab = frame?.frameId === undefined ? attached.get(contents.id) : undefined; + const startedAt = Date.now(); + const totalBudgetMs = Duration.toMillis( + Duration.fromInputUnsafe(timeout ?? CDP_COMMAND_TIMEOUT), + ); + const remainingTimeout = (): Duration.Input | undefined => { + const remainingMs = totalBudgetMs - (Date.now() - startedAt); + return remainingMs > 0 ? Duration.millis(remainingMs) : undefined; + }; + const readMainFrameId = (stepTimeout?: Duration.Input) => + Effect.gen(function* () { + if (!tab?.pageDomainEnabled) { + yield* sendCommand(contents, "Page.enable", {}, { timeout: stepTimeout }); + if (tab) { + tab.pageDomainEnabled = true; + } + } + const tree = (yield* sendCommand( + contents, + "Page.getFrameTree", + {}, + { timeout: stepTimeout }, + )) as { + frameTree?: { frame?: { id?: string } }; + }; + const resolved = tree.frameTree?.frame?.id; + if (resolved === undefined) { + return yield* failCommand(contents, "Page.getFrameTree", "the page has no main frame"); + } + if (tab) { + tab.mainFrameId = resolved; + } + return resolved; + }); + + const createWorld = (targetFrameId: string, stepTimeout?: Duration.Input) => + sendCommand( + contents, + "Page.createIsolatedWorld", + { frameId: targetFrameId, worldName: INJECTED_WORLD_NAME, grantUniveralAccess: false }, + { sessionId, timeout: stepTimeout }, + ) as Effect.Effect<{ executionContextId?: number }, PreviewCommandError>; + let frameId = frame?.frameId; + let usedCachedMainFrame = false; if (frameId === undefined) { - yield* sendCommand(contents, "Page.enable", {}); - const tree = (yield* sendCommand(contents, "Page.getFrameTree", {})) as { - frameTree?: { frame?: { id?: string } }; - }; - frameId = tree.frameTree?.frame?.id; - if (frameId === undefined) { - return yield* failCommand(contents, "Page.getFrameTree", "the page has no main frame"); + if (tab?.mainFrameId !== undefined) { + frameId = tab.mainFrameId; + usedCachedMainFrame = true; + } else { + frameId = yield* readMainFrameId(timeout); } } - const world = (yield* sendCommand( - contents, - "Page.createIsolatedWorld", - { frameId, worldName: INJECTED_WORLD_NAME, grantUniveralAccess: false }, - { sessionId, timeout }, - )) as { executionContextId?: number }; + const world = usedCachedMainFrame + ? yield* createWorld(frameId, timeout).pipe( + Effect.catch((error) => { + const retryTimeout = remainingTimeout(); + // Do not re-probe a hung page after its timeout expired. + if (error.cause === PAGE_DID_NOT_ANSWER || retryTimeout === undefined) { + return Effect.fail(error); + } + return Effect.gen(function* () { + if (tab) { + tab.mainFrameId = undefined; + } + const refreshedFrameId = yield* readMainFrameId(retryTimeout); + const createTimeout = remainingTimeout(); + if (createTimeout === undefined) { + return yield* Effect.fail(error); + } + return yield* createWorld(refreshedFrameId, createTimeout); + }); + }), + ) + : yield* createWorld(frameId, timeout); const contextId = world.executionContextId; if (contextId === undefined) { return yield* failCommand( @@ -1823,6 +1885,8 @@ export const make = Effect.gen(function* PreviewAutomationMake() { frameSessions: new Map(), sessionOwners: new Map(), framesByOrdinal: new Map(), + pageDomainEnabled: false, + mainFrameId: undefined, dispose: () => {}, }; @@ -1992,10 +2056,11 @@ export const make = Effect.gen(function* PreviewAutomationMake() { return; } if (method === "Page.frameNavigated") { - const frame = params.frame as { parentId?: string } | undefined; + const frame = params.frame as { id?: string; parentId?: string } | undefined; // Only the main frame: an iframe navigating is not a new page, and // clearing on it would discard the diagnostics being asked about. if (frame?.parentId === undefined) { + tab.mainFrameId = typeof frame?.id === "string" ? frame.id : undefined; tab.console.length = 0; tab.networkFailures.length = 0; tab.requestUrls.clear(); @@ -2035,6 +2100,7 @@ export const make = Effect.gen(function* PreviewAutomationMake() { ); yield* sendCommand(contents, "Page.enable"); + tab.pageDomainEnabled = true; // We only record request URLs and failures and never call // `Network.getResponseBody`, so tell Chromium not to buffer response bodies. yield* sendCommand(contents, "Network.enable", { diff --git a/apps/desktop/src/window/DesktopBackdropMonitor.ts b/apps/desktop/src/window/DesktopBackdropMonitor.ts index f98ca3f06..37405f54c 100644 --- a/apps/desktop/src/window/DesktopBackdropMonitor.ts +++ b/apps/desktop/src/window/DesktopBackdropMonitor.ts @@ -66,7 +66,7 @@ const frameKey = (frame: Electron.WebFrameMain) => frame.frameToken; * when there is no backdrop frame or another frame shares its process. */ function sampleBackdropCpu(window: Electron.BrowserWindow): number | null { - if (window.isDestroyed()) return null; + if (window.isDestroyed() || window.isMinimized() || !window.isVisible()) return null; const frames = window.webContents.mainFrame.framesInSubtree; const backdrop = frames.find((frame) => frame.name === BACKDROP_FRAME_NAME); if (!backdrop) return null; @@ -120,7 +120,10 @@ export const layer = Layer.effect( const runFork = Effect.runForkWith(context); let speedLimited = false; let listening = false; + let active = false; let watchdog: ReturnType | null = null; + let watchedWindow: Electron.BrowserWindow | null = null; + let cleanupWindowListeners: (() => void) | null = null; let watchdogState: WatchdogState = { overSince: null }; const broadcastPower = () => { @@ -145,7 +148,31 @@ export const layer = Layer.effect( }); }; + const pauseWatchdogTimer = () => { + if (watchdog !== null) { + clearInterval(watchdog); + watchdog = null; + } + watchdogState = { overSince: null }; + }; + + const stopWatchdog = () => { + active = false; + pauseWatchdogTimer(); + cleanupWindowListeners?.(); + cleanupWindowListeners = null; + watchedWindow = null; + }; + const sample = (window: Electron.BrowserWindow) => { + if (window.isDestroyed()) { + stopWatchdog(); + return; + } + if (window.isMinimized() || !window.isVisible()) { + pauseWatchdogTimer(); + return; + } let cpuPercent: number | null = null; try { cpuPercent = sampleBackdropCpu(window); @@ -162,10 +189,37 @@ export const layer = Layer.effect( } }; - const stopWatchdog = () => { - if (watchdog !== null) clearInterval(watchdog); - watchdog = null; - watchdogState = { overSince: null }; + const ensureWatchdogTimer = (window: Electron.BrowserWindow) => { + if (!active || watchdog !== null) return; + if (window.isDestroyed() || window.isMinimized() || !window.isVisible()) return; + watchdog = setInterval(() => sample(window), WATCHDOG_SAMPLE_MS); + }; + + const watchWindow = (window: Electron.BrowserWindow) => { + if (watchedWindow === window) { + ensureWatchdogTimer(window); + return; + } + cleanupWindowListeners?.(); + watchedWindow = window; + const onPause = () => pauseWatchdogTimer(); + const onResume = () => ensureWatchdogTimer(window); + const onClosed = () => stopWatchdog(); + window.on("minimize", onPause); + window.on("hide", onPause); + window.on("restore", onResume); + window.on("show", onResume); + window.once("closed", onClosed); + cleanupWindowListeners = () => { + if (!window.isDestroyed()) { + window.removeListener("minimize", onPause); + window.removeListener("hide", onPause); + window.removeListener("restore", onResume); + window.removeListener("show", onResume); + window.removeListener("closed", onClosed); + } + }; + ensureWatchdogTimer(window); }; yield* Effect.addFinalizer(() => Effect.sync(stopWatchdog)); @@ -175,18 +229,17 @@ export const layer = Layer.effect( listen(); return readPowerState(speedLimited); }), - setBackdropActive: (active) => + setBackdropActive: (nextActive) => Effect.gen(function* () { listen(); - if (!active) { + if (!nextActive) { stopWatchdog(); return; } - if (watchdog !== null) return; + active = true; const window = yield* electronWindow.main; if (window._tag === "None") return; - const main = window.value; - watchdog = setInterval(() => sample(main), WATCHDOG_SAMPLE_MS); + watchWindow(window.value); }).pipe(Effect.withSpan("desktop.backdropMonitor.setBackdropActive")), }); }), diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index ab428d4fb..18e31fc26 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1203,8 +1203,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => { expect(remote?.aheadCount).toBe(1); expect(remote?.aheadOfDefaultCount).toBe(1); expect({ localProcesses, remoteProcesses }).toEqual({ - localProcesses: 5, - remoteProcesses: 10, + localProcesses: 4, + remoteProcesses: 9, }); }), ); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 065bd7ef2..46800a9f7 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -962,7 +962,10 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); const hosting = details.isRepo - ? resolveHostingContext(yield* readConfigSnapshot(cwd), details.branch) + ? resolveHostingContext( + details.configSnapshot ?? (yield* readConfigSnapshot(cwd)), + details.branch, + ) : null; return { @@ -1347,12 +1350,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () { readonly upstreamRef: string | null; readonly upstreamHeadSha: string | null; readonly isDefaultBranch: boolean; + readonly configSnapshot?: GitConfigSnapshot; }, branch: string, hostContext: SourceControlProviderContext | null, options: RemoteStatusReadOptions | undefined, ) { - const config = yield* readConfigSnapshot(cwd); + const config = details.configSnapshot ?? (yield* readConfigSnapshot(cwd)); const headContext = yield* resolveBranchHeadContext( cwd, { branch, upstreamRef: details.upstreamRef }, diff --git a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts index cedead440..d30c8dfe3 100644 --- a/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts +++ b/apps/server/src/orchestration/Layers/PullRequestAutomationWatcher.ts @@ -1,4 +1,6 @@ import { randomUUID } from "node:crypto"; +// @effect-diagnostics-next-line nodeBuiltinImport:off +import * as fsPromises from "node:fs/promises"; import { CommandId, @@ -134,6 +136,8 @@ interface Resting { /** What the thread looked like then; a change to any of it ends the rest. */ readonly stamp: string; readonly nextLookAt: number; + /** Set when the rest came from a missing worktree; recreating that folder wakes the thread. */ + readonly missingWorktreePath?: string; } /** @@ -358,8 +362,13 @@ interface PullRequestWatch { interface LookReads { /** The status of the checkout at `cwd`; null where it could not be read. */ readonly statusAt: (cwd: string) => Effect.Effect; - /** The repository's checkouts; null where they could not be listed. */ - readonly worktrees: Effect.Effect | null>; + /** The repository's checkouts (possibly reused from earlier in this sweep); null on error. */ + readonly worktrees: Effect.Effect<{ + readonly entries: ReadonlyArray | null; + readonly fromSweepCache: boolean; + }>; + /** Re-reads the repository's checkouts fresh from Git, updating any sweep cache. */ + readonly freshWorktrees: Effect.Effect | null>; } /** The busier of two looks' findings: a turn started, then something left to watch. */ @@ -398,6 +407,34 @@ function threadWorkingCwd({ thread, project }: SweepCandidate): string { }); } +/** + * Confirms a thread's worktree folder is gone on disk while its project root + * still exists. Returns false for synthetic paths in tests whose project root + * does not exist on disk. + */ +async function isConfirmedMissingWorktree(workspaceRoot: string, cwd: string): Promise { + try { + await fsPromises.stat(workspaceRoot); + } catch { + return false; + } + try { + await fsPromises.stat(cwd); + return false; + } catch (error) { + return (error as NodeJS.ErrnoException | undefined)?.code === "ENOENT"; + } +} + +async function doesPathExist(targetPath: string): Promise { + try { + await fsPromises.stat(targetPath); + return true; + } catch { + return false; + } +} + /** * Where a pull request stands after a merge that did not come back merged, * read again rather than taken as a failure. Another environment may have @@ -1426,49 +1463,63 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher if (threadStatus?.pr != null && isSamePullRequest(threadStatus.pr.url, detail.url)) { return { kind: "thread", status: threadStatus }; } - const worktrees = yield* reads.worktrees; - // A repository always lists its main checkout, so an empty list is a - // read that failed. - if (worktrees === null || worktrees.length === 0) { - return null; - } - // The checkout the thread works in is the innermost one around its - // folder: the main checkout can hold the others. - const threadCheckout = worktrees - .filter((entry) => isFilesystemPathWithin(threadCwd, entry.path)) - .reduce( - (innermost, entry) => - innermost === null || entry.path.length > innermost.path.length ? entry : innermost, - null, - ); - // Its own branch name, or the name a pull request from a fork is - // checked out under here. - const forkPrefix = forkPullRequestBranchPrefix(detail.number); - const onBranch = worktrees.filter( - (entry) => - entry.branch !== null && - (entry.branch === detail.headBranch || entry.branch.startsWith(forkPrefix)), - ); - let fallback: BranchCheckout = { kind: "unknown", status: null }; - for (const entry of onBranch) { - const isThreadCheckout = - threadCheckout !== null && areFilesystemPathsEqual(threadCheckout.path, entry.path); - const status = isThreadCheckout ? threadStatus : yield* reads.statusAt(entry.path); - if (status === null) { - return null; - } - if ( - !isThreadCheckout && - status.pr !== null && - isSamePullRequest(status.pr.url, detail.url) - ) { - return { kind: "folder", path: entry.path, status }; - } - if (fallback.status === null) { - fallback = { kind: "unknown", status }; - } + const searchWorktrees = (worktrees: ReadonlyArray | null) => + Effect.gen(function* (): Effect.fn.Return { + // A repository always lists its main checkout, so an empty list is a + // read that failed. + if (worktrees === null || worktrees.length === 0) { + return null; + } + // The checkout the thread works in is the innermost one around its + // folder: the main checkout can hold the others. + const threadCheckout = worktrees + .filter((entry) => isFilesystemPathWithin(threadCwd, entry.path)) + .reduce( + (innermost, entry) => + innermost === null || entry.path.length > innermost.path.length + ? entry + : innermost, + null, + ); + // Its own branch name, or the name a pull request from a fork is + // checked out under here. + const forkPrefix = forkPullRequestBranchPrefix(detail.number); + const onBranch = worktrees.filter( + (entry) => + entry.branch !== null && + (entry.branch === detail.headBranch || entry.branch.startsWith(forkPrefix)), + ); + let fallback: BranchCheckout = { kind: "unknown", status: null }; + for (const entry of onBranch) { + const isThreadCheckout = + threadCheckout !== null && areFilesystemPathsEqual(threadCheckout.path, entry.path); + const status = isThreadCheckout ? threadStatus : yield* reads.statusAt(entry.path); + if (status === null) { + return null; + } + if ( + !isThreadCheckout && + status.pr !== null && + isSamePullRequest(status.pr.url, detail.url) + ) { + return { kind: "folder", path: entry.path, status }; + } + if (fallback.status === null) { + fallback = { kind: "unknown", status }; + } + } + return fallback; + }); + + const initial = yield* reads.worktrees; + const found = yield* searchWorktrees(initial.entries); + // If a sweep-cached worktree list missed this branch, revalidate fresh + // before deciding no local checkout (and therefore zero unpushed commits) + // exists for an open pull request. + if (initial.fromSweepCache && found !== null && found.kind === "unknown") { + return yield* searchWorktrees(yield* reads.freshWorktrees); } - return fallback; + return found; }); /** @@ -1553,6 +1604,7 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher */ const sweepThread = Effect.fn("PullRequestAutomationWatcher.sweepThread")(function* ( candidate: SweepCandidate, + sweepWorktrees?: Map>, ): Effect.fn.Return { const { thread, project } = candidate; // This look decides the pace again: checks it finds in motion put the @@ -1563,6 +1615,19 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher return [since, threads]; }); const statuses = new Map(); + const readFreshWorktrees = attempt( + "worktree-list", + thread.id, + gitWorkflow.listWorktrees({ cwd: project.workspaceRoot }), + ).pipe( + Effect.tap((listed) => + Effect.sync(() => { + if (sweepWorktrees && listed !== null) { + sweepWorktrees.set(project.workspaceRoot, listed); + } + }), + ), + ); const reads: LookReads = { statusAt: (cwd) => Effect.suspend(() => @@ -1573,25 +1638,46 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher ), ), worktrees: yield* Effect.cached( - attempt( - "worktree-list", - thread.id, - gitWorkflow.listWorktrees({ cwd: project.workspaceRoot }), - ), + Effect.suspend(() => { + const cached = sweepWorktrees?.get(project.workspaceRoot); + if (cached !== undefined) { + return Effect.succeed({ + entries: cached as ReadonlyArray | null, + fromSweepCache: true, + }); + } + return readFreshWorktrees.pipe( + Effect.map((entries) => ({ entries, fromSweepCache: false })), + ); + }), ), + freshWorktrees: yield* Effect.cached(readFreshWorktrees), }; // The thread's own switches are for the pull request on its checkout's // branch, so a thread with no branch has only ones held by number. const ownArmed = thread.branch !== null && (thread.pullRequestAutoFix || thread.pullRequestAutoMerge !== null); - const ownStatus = ownArmed ? yield* reads.statusAt(threadWorkingCwd(candidate)) : null; + const threadCwd = threadWorkingCwd(candidate); + const ownStatus = ownArmed ? yield* reads.statusAt(threadCwd) : null; const ownUrl = ownStatus?.pr?.url ?? null; const ownHeld = ownUrl !== null && thread.linkedPullRequests.some((linked) => isSamePullRequest(linked.url, ownUrl)); + const missingOwnWorktree = + ownArmed && + !ownHeld && + ownStatus === null && + thread.worktreePath !== null && + !areFilesystemPathsEqual(threadCwd, project.workspaceRoot) + ? yield* Effect.promise(() => + isConfirmedMissingWorktree(project.workspaceRoot, threadCwd), + ) + : false; const own = - ownArmed && !ownHeld ? yield* sweepOwnPullRequest(candidate, ownStatus) : "nothing"; + ownArmed && !ownHeld && !missingOwnWorktree + ? yield* sweepOwnPullRequest(candidate, ownStatus) + : "nothing"; const outcome = own === "started" ? own @@ -1612,7 +1698,11 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher const restMs = Number.isFinite(idleMs) ? Math.min(Math.max(idleMs / REST_SHARE_OF_IDLE_TIME, sweepIntervalMs), MAX_REST_MS) : sweepIntervalMs; - return threads.set(thread.id, { stamp: restStamp(thread), nextLookAt: now + restMs }); + return threads.set(thread.id, { + stamp: restStamp(thread), + nextLookAt: now + restMs, + ...(missingOwnWorktree ? { missingWorktreePath: threadCwd } : {}), + }); }); return outcome; }); @@ -1629,7 +1719,10 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher * no longer watched or is on a host this cannot read. Run under the look * permit. */ - const lookAt = Effect.fn("PullRequestAutomationWatcher.lookAt")(function* (threadId: ThreadId) { + const lookAt = Effect.fn("PullRequestAutomationWatcher.lookAt")(function* ( + threadId: ThreadId, + sweepWorktrees?: Map>, + ) { const thread = yield* attempt( "thread-read", threadId, @@ -1657,7 +1750,7 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher if (candidate === null) { return null; } - const outcome = yield* sweepThread(candidate); + const outcome = yield* sweepThread(candidate, sweepWorktrees); return background ? "background" : outcome; }); @@ -1780,20 +1873,34 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher return waits; }); - return snapshot.threads.flatMap((thread): ThreadId[] => { + const selectedThreads: ThreadId[] = []; + for (const thread of snapshot.threads) { if ( !lookableThreadIds.has(thread.id) || (scope === "in-motion" && !inMotion.has(thread.id)) ) { - return []; + continue; } const rest = resting.get(thread.id); if (rest !== undefined && rest.stamp === restStamp(thread) && now < rest.nextLookAt) { - return []; + if (rest.missingWorktreePath === undefined) { + continue; + } + const recreated = yield* Effect.promise(() => doesPathExist(rest.missingWorktreePath!)); + if (!recreated) { + continue; + } + yield* Ref.update(restingRef, (threads) => { + threads.delete(thread.id); + return threads; + }); } const project = projectsById.get(thread.projectId); - return project !== undefined && candidateOf(thread, project) !== null ? [thread.id] : []; - }); + if (project !== undefined && candidateOf(thread, project) !== null) { + selectedThreads.push(thread.id); + } + } + return selectedThreads; }); /** @@ -1804,10 +1911,11 @@ const makePullRequestAutomationWatcher = (options?: PullRequestAutomationWatcher scope: "all" | "in-motion", ) { const threadIds = yield* lookSemaphore.withPermits(1)(listThreads(scope)); + const sweepWorktrees = new Map>(); let startedCount = 0; for (const threadId of threadIds) { yield* noLookAskedFor.await; - const outcome = yield* lookSemaphore.withPermits(1)(lookAt(threadId)); + const outcome = yield* lookSemaphore.withPermits(1)(lookAt(threadId, sweepWorktrees)); if (outcome === "started") { startedCount += 1; } diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.ts index 4ce407651..6df65f89d 100644 --- a/apps/server/src/project/Layers/ProjectFaviconResolver.ts +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.ts @@ -1,4 +1,7 @@ +import * as Cache from "effect/Cache"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; @@ -8,6 +11,10 @@ import { type ProjectFaviconResolverShape, } from "../Services/ProjectFaviconResolver.ts"; +const FAVICON_CACHE_CAPACITY = 64; +const FAVICON_FOUND_TTL = Duration.seconds(30); +const FAVICON_MISSING_TTL = Duration.seconds(15); + // Well-known favicon paths checked in order. const FAVICON_CANDIDATES = [ "favicon.svg", @@ -102,9 +109,9 @@ export const makeProjectFaviconResolver = Effect.gen(function* () { return null; }); - const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn( - "ProjectFaviconResolver.resolvePath", - )(function* (cwd: string): Effect.fn.Return { + const resolvePathUncached = Effect.fn("ProjectFaviconResolver.resolvePathUncached")(function* ( + cwd: string, + ): Effect.fn.Return { for (const candidate of FAVICON_CANDIDATES) { const resolved = path.join(cwd, candidate); const existing = yield* findExistingFile(cwd, [resolved]); @@ -134,6 +141,27 @@ export const makeProjectFaviconResolver = Effect.gen(function* () { return null; }); + const resolvedPathCache = yield* Cache.makeWith(resolvePathUncached, { + capacity: FAVICON_CACHE_CAPACITY, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value !== null ? FAVICON_FOUND_TTL : FAVICON_MISSING_TTL, + }); + + const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn( + "ProjectFaviconResolver.resolvePath", + )(function* (cwd: string): Effect.fn.Return { + const cached = yield* Cache.get(resolvedPathCache, cwd); + if (cached === null) { + return null; + } + const stats = yield* fileSystem.stat(cached).pipe(Effect.catch(() => Effect.succeed(null))); + if (stats?.type === "File") { + return cached; + } + yield* Cache.invalidate(resolvedPathCache, cwd); + return yield* Cache.get(resolvedPathCache, cwd); + }); + return { resolvePath, } satisfies ProjectFaviconResolverShape; diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.ts index 099eebc0d..f2a44e4d1 100644 --- a/apps/server/src/provider/Drivers/ClaudeDriver.ts +++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts @@ -12,10 +12,13 @@ * * @module provider/Drivers/ClaudeDriver */ +// @effect-diagnostics-next-line nodeBuiltinImport:off +import * as fsPromises from "node:fs/promises"; import { ClaudeSettings, ProviderDriverKind, type ServerProvider, + type ServerProviderAccountTokenUsage, type ServerProviderSignInEnds, } from "@threadlines/contracts"; import * as Cache from "effect/Cache"; @@ -293,6 +296,49 @@ export const ClaudeDriver: ProviderDriver = { : yield* makeClaudeTokenUsageHistoryReader(effectiveConfig, processEnv, { stateDir: serverConfig.stateDir, }); + // Scheduled 5-minute health ticks reuse a recent 30-day transcript walk + // for 15 minutes within the same UTC calendar day; startup and explicit + // refreshes always scan fresh. + const TOKEN_USAGE_SCHEDULED_TTL_MS = 15 * 60 * 1000; + const lastTokenUsageRef = yield* Ref.make< + | { + readonly checkedAtMs: number; + readonly utcDay: string; + readonly value: ServerProviderAccountTokenUsage; + } + | undefined + >(undefined); + const readFreshTokenUsage = readTokenUsage + ? Effect.gen(function* () { + const value = yield* readTokenUsage; + if (value !== undefined) { + const now = yield* DateTime.now; + yield* Ref.set(lastTokenUsageRef, { + checkedAtMs: DateTime.toEpochMillis(now), + utcDay: DateTime.formatIso(now).slice(0, 10), + value, + }); + } + return value; + }) + : undefined; + const readScheduledTokenUsage = readFreshTokenUsage + ? Effect.gen(function* () { + const cached = yield* Ref.get(lastTokenUsageRef); + if (cached !== undefined) { + const now = yield* DateTime.now; + const nowMs = DateTime.toEpochMillis(now); + const utcDay = DateTime.formatIso(now).slice(0, 10); + if ( + cached.utcDay === utcDay && + nowMs - cached.checkedAtMs < TOKEN_USAGE_SCHEDULED_TTL_MS + ) { + return cached.value; + } + } + return yield* readFreshTokenUsage; + }) + : undefined; const stampIdentity = withInstanceIdentity({ instanceId, displayName, @@ -406,50 +452,57 @@ export const ClaudeDriver: ProviderDriver = { const lastReportedModelsRef = yield* Ref.make( claudeReportedModelsFromCache(cachedSnapshot, { instanceId, driver: DRIVER_KIND }), ); - const checkProvider = Effect.gen(function* () { - const provider = yield* checkClaudeProviderStatus( - effectiveConfig, - () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey), - processEnv, - () => - (hasClaudeChatOnlyToken(processEnv) - ? Cache.get(normalSignInUsageCache, "usage") - : Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe( - Effect.map((probe) => probe?.usage ?? claudeUsageUnavailable("unreachable")), - ) - ).pipe(Effect.flatMap(settleScopedWindows)), - (settings) => - readClaudeNormalAuthEmail(settings, processEnv).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - ), - readTokenUsage ? () => readTokenUsage : undefined, - () => isSignInRenewalDue, - { - get: Ref.get(lastReportedModelsRef), - set: (reported) => Ref.set(lastReportedModelsRef, reported), - }, - ); - // Only the sign-in chat runs on has an end worth a warning; its date - // is read from the stored sign-in, as Claude Code itself reads it. - if (!claudeChatUsesStoredSignIn(provider)) { - yield* Ref.set(lastSignInEndsRef, undefined); - return withClaudeSignInEnds(provider, undefined); - } - const window = claudeSignInEndsWindow( - yield* readStoredSignIn, - DateTime.toEpochMillis(yield* DateTime.now), - ); - if (window !== "unknown") yield* Ref.set(lastSignInEndsRef, window); - return withClaudeSignInEnds( - provider, - window === "unknown" ? yield* Ref.get(lastSignInEndsRef) : window, + const makeCheckProvider = ( + tokenUsageReader: Effect.Effect | undefined, + ) => + Effect.gen(function* () { + const provider = yield* checkClaudeProviderStatus( + effectiveConfig, + () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey), + processEnv, + () => + (hasClaudeChatOnlyToken(processEnv) + ? Cache.get(normalSignInUsageCache, "usage") + : Cache.get(capabilitiesProbeCache, capabilitiesCacheKey).pipe( + Effect.map((probe) => probe?.usage ?? claudeUsageUnavailable("unreachable")), + ) + ).pipe(Effect.flatMap(settleScopedWindows)), + (settings) => + readClaudeNormalAuthEmail(settings, processEnv).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + tokenUsageReader ? () => tokenUsageReader : undefined, + () => isSignInRenewalDue, + { + get: Ref.get(lastReportedModelsRef), + set: (reported) => Ref.set(lastReportedModelsRef, reported), + }, + ); + // Only the sign-in chat runs on has an end worth a warning; its date + // is read from the stored sign-in, as Claude Code itself reads it. + if (!claudeChatUsesStoredSignIn(provider)) { + yield* Ref.set(lastSignInEndsRef, undefined); + return withClaudeSignInEnds(provider, undefined); + } + const window = claudeSignInEndsWindow( + yield* readStoredSignIn, + DateTime.toEpochMillis(yield* DateTime.now), + ); + if (window !== "unknown") yield* Ref.set(lastSignInEndsRef, window); + return withClaudeSignInEnds( + provider, + window === "unknown" ? yield* Ref.get(lastSignInEndsRef) : window, + ); + }).pipe( + Effect.map(stampIdentity), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provideService(Path.Path, path), ); - }).pipe( - Effect.map(stampIdentity), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.provideService(Path.Path, path), - ); + const checkProvider = makeCheckProvider(readFreshTokenUsage); + const scheduledCheckProvider = readScheduledTokenUsage + ? makeCheckProvider(readScheduledTokenUsage) + : checkProvider; const snapshot = yield* makeManagedServerProvider({ get maintenanceCapabilities() { @@ -478,6 +531,7 @@ export const ClaudeDriver: ProviderDriver = { ), ), checkProvider, + scheduledCheckProvider, reconcileSnapshot: (previous, next) => carryClaudeUsageAcrossChecks(previous, next, { keepsTokenCalendar: readTokenUsage !== undefined, @@ -492,6 +546,7 @@ export const ClaudeDriver: ProviderDriver = { ), ), refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + shouldScheduleRefresh: (settings) => settings.enabled, shouldRetrySnapshot: (provider) => provider.statusReason === "provider_probe_timeout", retryDelay: Duration.minutes(1), }).pipe( @@ -528,6 +583,54 @@ export const ClaudeDriver: ProviderDriver = { resolveModelMetadata(model).pipe(Effect.map((listed) => listed?.capabilities)), }); + // Cache `claude --version` keyed by the resolved executable's inode/mtime/size + // so consecutive session starts reuse the probed version while any in-place + // upgrade, downgrade, or symlink retarget invalidates immediately. + const resolveExecutableStatKey = async ( + launch: Parameters[0], + ): Promise => { + const candidates: string[] = []; + const hasSeparator = launch.executable.includes("/") || launch.executable.includes("\\"); + if (hasSeparator) { + candidates.push( + launch.cwd ? path.resolve(launch.cwd, launch.executable) : launch.executable, + ); + } else { + const pathEnv = launch.environment.PATH ?? launch.environment.Path ?? ""; + for (const dir of pathEnv.split(path.sep === "\\" ? ";" : ":")) { + if (dir.length > 0) { + candidates.push(path.join(dir, launch.executable)); + } + } + } + for (const candidate of candidates) { + try { + const stat = await fsPromises.stat(candidate); + if (stat.isFile()) { + return `${candidate}\0${stat.ino}\0${stat.size}\0${stat.mtimeMs}`; + } + } catch { + // Try next PATH entry. + } + } + return null; + }; + const launchTargetsByKey = new Map[0]>(); + const launchVersionCache = yield* Cache.makeWith( + (key: string) => { + const launch = launchTargetsByKey.get(key); + if (!launch) return Effect.succeed(undefined); + return readClaudeLaunchVersion(launch).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + }, + { + capacity: 16, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value !== undefined ? Duration.minutes(5) : Duration.zero, + }, + ); + // The adapter is built after the snapshot so mid-turn `rate_limit_event` // messages can be folded straight into the live provider snapshot — // account usage then updates in real time instead of waiting for the @@ -553,9 +656,22 @@ export const ClaudeDriver: ProviderDriver = { Effect.map((provider) => provider.version ?? undefined), ), readLaunchVersion: (launch) => - readClaudeLaunchVersion(launch).pipe( - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - ), + Effect.gen(function* () { + const statKey = yield* Effect.promise(() => resolveExecutableStatKey(launch)); + if (statKey === null) { + return yield* readClaudeLaunchVersion(launch).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + } + launchTargetsByKey.set(statKey, launch); + if (launchTargetsByKey.size > 32) { + const oldest = launchTargetsByKey.keys().next().value; + if (oldest !== undefined && oldest !== statKey) { + launchTargetsByKey.delete(oldest); + } + } + return yield* Cache.get(launchVersionCache, statKey); + }), // Read live as well. Unreadable settings leave Claude's own rule. suggestionsWhenUsageRunsFast: serverSettings.getSettings.pipe( Effect.map((settings) => settings.claudeSuggestionsWhenUsageRunsFast), diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.ts index f6eb741c3..79e57c902 100644 --- a/apps/server/src/provider/Drivers/CodexDriver.ts +++ b/apps/server/src/provider/Drivers/CodexDriver.ts @@ -281,6 +281,7 @@ export const CodexDriver: ProviderDriver = { Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)), ), refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + shouldScheduleRefresh: (settings) => settings.enabled, shouldRetrySnapshot: (provider) => provider.statusReason === "provider_probe_timeout", retryDelay: Duration.minutes(1), }).pipe( diff --git a/apps/server/src/provider/Drivers/MuseDriver.ts b/apps/server/src/provider/Drivers/MuseDriver.ts index b970604c1..6be068ef4 100644 --- a/apps/server/src/provider/Drivers/MuseDriver.ts +++ b/apps/server/src/provider/Drivers/MuseDriver.ts @@ -242,6 +242,7 @@ export const MuseDriver: ProviderDriver = { yield* updateSnapshot((now) => ({ ...now, versionAdvisory })); }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)), refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + shouldScheduleRefresh: (current) => current.enabled, }).pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.ts index 0b5eef4dc..4610cbf13 100644 --- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts +++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts @@ -260,6 +260,7 @@ export const OpenCodeDriver: ProviderDriver ); }, refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + shouldScheduleRefresh: (current) => current.enabled, }).pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/Drivers/PiDriver.ts b/apps/server/src/provider/Drivers/PiDriver.ts index 05e952d94..fee572ea5 100644 --- a/apps/server/src/provider/Drivers/PiDriver.ts +++ b/apps/server/src/provider/Drivers/PiDriver.ts @@ -292,6 +292,7 @@ export const PiDriver: ProviderDriver = { Effect.flatMap(publishSnapshot), ), refreshInterval: SNAPSHOT_REFRESH_INTERVAL, + shouldScheduleRefresh: (current) => current.enabled, }).pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index d4786b7c1..9403cb156 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -6363,10 +6363,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( return; } - if (context.turnState) { - context.turnState.items.push(message.message); - } - const toolResults = toolResultBlocksFromUserMessage(message); // SDKUserMessage.tool_use_result describes the matching Agent/Task output // but does not carry its tool_use_id. Current SDK messages contain one @@ -7080,7 +7076,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( } if (context.turnState) { - context.turnState.items.push(message.message); if (isApiError) { // Kept out of the transcript: it would read as Claude's answer. If the // turn ends here, the result reports it as the turn's error. diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts index 811910940..c965df505 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts @@ -475,12 +475,18 @@ export function makeOpenCodeAdapter(options: OpenCodeAdapterOptions) { : {}), })); + const OPENCODE_STREAM_FRAGMENT_EVENT_TYPES = new Set([ + "session.text.delta", + "session.reasoning.delta", + ]); + const logNative = (ctx: SessionContext, event: OpenCodeEvent) => nativeEventLogger ? Effect.flatMap(nowIso, (observedAt) => nativeEventLogger.write( { observedAt, event: { provider: PROVIDER, method: event.type, payload: event } }, ctx.threadId, + { streamFragment: OPENCODE_STREAM_FRAGMENT_EVENT_TYPES.has(event.type) }, ), ).pipe(Effect.ignore) : Effect.void; diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index cc4350ec2..2d400e55b 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -691,7 +691,7 @@ export const ProviderRegistryLive = Layer.effect( const refreshAll = Effect.fn("refreshAll")(function* () { const sources = yield* getLiveSources; return yield* Effect.forEach(sources, (source) => refreshOneSource(source), { - concurrency: "unbounded", + concurrency: 3, discard: true, }).pipe(Effect.andThen(Ref.get(providersRef))); }); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index d3684154b..266857fc6 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -1006,7 +1006,12 @@ export function makeAcpAdapter( const withThreadLock = (threadId: string, effect: Effect.Effect) => Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); - const logNative = (threadId: ThreadId, method: string, payload: unknown) => + const logNative = ( + threadId: ThreadId, + method: string, + payload: unknown, + logOptions?: { readonly streamFragment?: boolean }, + ) => Effect.gen(function* () { if (!nativeEventLogger) return; const observedAt = yield* nowIso; @@ -1024,6 +1029,7 @@ export function makeAcpAdapter( }, }, threadId, + logOptions, ); }); @@ -2917,7 +2923,9 @@ export function makeAcpAdapter( return; } case "ReasoningDelta": - yield* logNative(ctx.threadId, "session/update", event.rawPayload); + yield* logNative(ctx.threadId, "session/update", event.rawPayload, { + streamFragment: true, + }); yield* turnForOutput(ctx); yield* appendReasoning(ctx, event.text, event.rawPayload); return; @@ -3009,7 +3017,9 @@ export function makeAcpAdapter( event.text, PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE, ); - yield* logNative(ctx.threadId, "session/update", event.rawPayload); + yield* logNative(ctx.threadId, "session/update", event.rawPayload, { + streamFragment: true, + }); yield* offerRuntimeEvent( makeAcpContentDeltaEvent({ stamp: yield* makeEventStamp(), diff --git a/apps/server/src/provider/acp/AcpNativeLogging.ts b/apps/server/src/provider/acp/AcpNativeLogging.ts index 68676f429..160e0b9d9 100644 --- a/apps/server/src/provider/acp/AcpNativeLogging.ts +++ b/apps/server/src/provider/acp/AcpNativeLogging.ts @@ -8,12 +8,63 @@ import type * as EffectAcpProtocol from "effect-acp/protocol"; import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts"; import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpSessionRuntime.ts"; +const ACP_STREAM_FRAGMENT_SESSION_UPDATES = new Set([ + "agent_message_chunk", + "agent_thought_chunk", +]); + +function isAcpStreamFragmentRecord(value: unknown): boolean { + if (typeof value !== "object" || value === null || Array.isArray(value)) return false; + const record = value as { + readonly method?: unknown; + readonly params?: { readonly update?: { readonly sessionUpdate?: unknown } }; + }; + if (record.method !== "session/update") return false; + const sessionUpdate = record.params?.update?.sessionUpdate; + return ( + typeof sessionUpdate === "string" && ACP_STREAM_FRAGMENT_SESSION_UPDATES.has(sessionUpdate) + ); +} + +function isAcpProtocolStreamFragment(event: EffectAcpProtocol.AcpProtocolLogEvent): boolean { + if (event.direction !== "incoming") return false; + const payload = event.payload; + if (event.stage === "raw" && typeof payload === "string") { + if (!payload.includes('"agent_message_chunk"') && !payload.includes('"agent_thought_chunk"')) { + return false; + } + const lines = payload.split("\n"); + let sawLine = false; + for (const rawLine of lines) { + const line = rawLine.trim(); + if (line.length === 0) continue; + sawLine = true; + try { + if (!isAcpStreamFragmentRecord(JSON.parse(line) as unknown)) { + return false; + } + } catch { + return false; + } + } + return sawLine; + } + if (event.stage === "decoded") { + if (Array.isArray(payload)) { + return payload.length > 0 && payload.every(isAcpStreamFragmentRecord); + } + return isAcpStreamFragmentRecord(payload); + } + return false; +} + function writeNativeAcpLog(input: { readonly nativeEventLogger: EventNdjsonLogger | undefined; readonly provider: ProviderDriverKind; readonly threadId: ThreadId; readonly kind: "request" | "protocol"; readonly payload: unknown; + readonly streamFragment?: boolean; }): Effect.Effect { return Effect.gen(function* () { if (!input.nativeEventLogger) return; @@ -31,6 +82,7 @@ function writeNativeAcpLog(input: { }, }, input.threadId, + input.streamFragment === true ? { streamFragment: true } : undefined, ); }); } @@ -108,6 +160,7 @@ export function makeAcpNativeLoggers(input: { event.direction === "outgoing" ? { ...event, payload: redactAcpLogCredentials(event.payload) } : event, + streamFragment: isAcpProtocolStreamFragment(event), }), } satisfies NonNullable, } diff --git a/apps/server/src/provider/acp/AcpProviderDriver.ts b/apps/server/src/provider/acp/AcpProviderDriver.ts index 337631ded..38b179718 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.ts @@ -395,6 +395,7 @@ export function makeAcpProviderDriver settings.enabled, }).pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/makeManagedServerProvider.ts b/apps/server/src/provider/makeManagedServerProvider.ts index 15468fe20..1d6201186 100644 --- a/apps/server/src/provider/makeManagedServerProvider.ts +++ b/apps/server/src/provider/makeManagedServerProvider.ts @@ -61,6 +61,8 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( ) => Effect.Effect; }) => Effect.Effect; readonly refreshInterval?: Duration.Input; + /** Skip periodic background refreshes while false (e.g. disabled providers). */ + readonly shouldScheduleRefresh?: (settings: Settings) => boolean; /** Retry one transient snapshot sooner than the normal maintenance cadence. */ readonly shouldRetrySnapshot?: (snapshot: ServerProvider) => boolean; readonly retryDelay?: Duration.Input; @@ -283,9 +285,28 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")( Effect.asVoid(applySnapshot(nextSettings)), ).pipe(Effect.forkScoped); + const DISABLED_SCHEDULED_TICK_STRIDE = 6; + let skippedDisabledTicks = 0; + yield* Effect.forever( Effect.sleep(input.refreshInterval ?? "60 seconds").pipe( - Effect.flatMap(() => refreshSnapshot({ scheduled: true })), + Effect.flatMap(() => + Effect.gen(function* () { + if (input.shouldScheduleRefresh) { + const currentSettings = yield* Ref.get(settingsRef); + if (!input.shouldScheduleRefresh(currentSettings)) { + skippedDisabledTicks += 1; + if (skippedDisabledTicks < DISABLED_SCHEDULED_TICK_STRIDE) { + return; + } + skippedDisabledTicks = 0; + } else { + skippedDisabledTicks = 0; + } + } + yield* refreshSnapshot({ scheduled: true }); + }), + ), Effect.ignoreCause({ log: true }), ), ).pipe(Effect.forkScoped); diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts index 27afee9a3..a04dcf931 100644 --- a/apps/server/src/pullRequest/PullRequestService.ts +++ b/apps/server/src/pullRequest/PullRequestService.ts @@ -77,7 +77,7 @@ const LIST_CACHE_TTL = Duration.seconds(30); const LIST_CACHE_CAPACITY = 32; /** The signed-in account changes far more rarely than the listings do. */ const VIEWER_CACHE_TTL = Duration.minutes(10); -const VIEWER_CACHE_CAPACITY = 4; +const VIEWER_CACHE_CAPACITY = 64; /** One open pull request is read far more often than it changes. */ const DETAIL_CACHE_TTL = Duration.seconds(15); const ACTIVITY_CACHE_TTL = Duration.seconds(15); @@ -86,7 +86,7 @@ const DIFF_CACHE_TTL = Duration.seconds(60); const PULL_REQUEST_CACHE_CAPACITY = 32; /** Repository settings and access change far more rarely than a pull request. */ const REPOSITORY_CACHE_TTL = Duration.minutes(10); -const REPOSITORY_CACHE_CAPACITY = 16; +const REPOSITORY_CACHE_CAPACITY = 64; /** * How long a lookup answer serves every surface that asks at once. A merged * pull request never changes again and is kept until room runs out; anything @@ -786,23 +786,34 @@ export const make = Effect.fn("makePullRequestService")(function* () { ); }); + interface RawAuthoredRead { + readonly anchor: PullRequestProject; + readonly viewer: string | null; + readonly rows: ReadonlyArray; + readonly observedAt?: string; + readonly error: PullRequestListProjectError | null; + } + /** * The viewer's own pull requests anywhere on one host, whether or not the * workspace points at the repository they are on. The anchor project is only * the checkout the host's tool runs in; a row it finds keeps that project so * a later read has somewhere to run, and names its own repository. * - * Anything the workspace already read is dropped: the same pull request twice - * would be two rows of one thing, one of them without its project. + * Anything the workspace already read is filtered out by the caller once + * workspace rows arrive, so both reads can run in parallel. */ - const readAuthored = (input: { + const fetchAuthored = (input: { readonly anchor: PullRequestProject; readonly state: PullRequestListState; - readonly covered: ReadonlySet; - readonly seen: ReadonlySet; - }) => + }): Effect.Effect => Effect.suspend(() => { - const empty: PullRequestProjectRead = { entries: [], error: null }; + const empty: RawAuthoredRead = { + anchor: input.anchor, + viewer: null, + rows: [], + error: null, + }; const host = registry.get(input.anchor.provider); const search = host?.listAuthoredChangeRequests; if (search === undefined) { @@ -826,34 +837,18 @@ export const make = Effect.fn("makePullRequestService")(function* () { (rows) => rows.map((row) => rowRead(input.anchor.provider, row.repository, row)), ) .pipe( - Effect.map(({ result: rows, observedAt }): PullRequestProjectRead => ({ - entries: rows.flatMap((row) => - keepAuthoredRow({ - row, - anchor: input.anchor, - covered: input.covered, - seen: input.seen, - }) - ? [ - toEntry({ - project: input.anchor, - row, - viewer, - origin: "authored", - repository: row.repository, - ...(row.viewerCanWrite === undefined - ? {} - : { viewerCanWrite: row.viewerCanWrite }), - observedAt, - }), - ] - : [], - ), + Effect.map(({ result: rows, observedAt }): RawAuthoredRead => ({ + anchor: input.anchor, + viewer, + rows, + observedAt, error: null, })), Effect.catch((error) => - Effect.succeed({ - entries: [], + Effect.succeed({ + anchor: input.anchor, + viewer, + rows: [], error: { projectId: input.anchor.projectId, projectTitle: input.anchor.title, @@ -972,15 +967,12 @@ export const make = Effect.fn("makePullRequestService")(function* () { return { viewer: null, entries: [], errors: [] } satisfies PullRequestListResult; } - // The viewer is read per project, because each host signs in on its own and - // a workspace can hold projects on several. The cache is keyed by host and - // checkout, so projects that share one share the read. - const viewer = yield* readViewer(first); - // The rows and what the viewer may do with them are asked for at once: the - // access read is per repository, not per row, and waiting for the rows - // first would only make the listing slower. - const [results, writeAccess] = yield* Effect.all( + // The rows, write access, and account-wide authored search run together: + // the viewer cache deduplicates the login lookup across all three. + const authoredAnchors = key.includeAuthored ? firstProjectPerProvider(projects) : []; + const [viewer, results, writeAccess, rawAuthored] = yield* Effect.all( [ + readViewer(first), Effect.forEach( projects, (project) => @@ -992,8 +984,15 @@ export const make = Effect.fn("makePullRequestService")(function* () { { concurrency: PROJECT_CONCURRENCY }, ), readWorkspaceWriteAccess(projects), + authoredAnchors.length === 0 + ? Effect.succeed>([]) + : Effect.forEach( + authoredAnchors, + (anchor) => fetchAuthored({ anchor, state: key.state }), + { concurrency: PROJECT_CONCURRENCY }, + ), ], - { concurrency: 2 }, + { concurrency: 4 }, ); const entries = results.flatMap((result) => @@ -1010,18 +1009,35 @@ export const make = Effect.fn("makePullRequestService")(function* () { const seen = new Set( entries.map((entry) => listRowKey(entry.provider, entry.repository, entry.number)), ); - const authored = yield* Effect.forEach( - firstProjectPerProvider(projects), - (anchor) => readAuthored({ anchor, state: key.state, covered, seen }), - { concurrency: PROJECT_CONCURRENCY }, + const authoredEntries = rawAuthored.flatMap((result) => + result.rows.flatMap((row) => + keepAuthoredRow({ + row, + anchor: result.anchor, + covered, + seen, + }) + ? [ + toEntry({ + project: result.anchor, + row, + viewer: result.viewer, + origin: "authored", + repository: row.repository, + ...(row.viewerCanWrite === undefined ? {} : { viewerCanWrite: row.viewerCanWrite }), + ...(result.observedAt === undefined ? {} : { observedAt: result.observedAt }), + }), + ] + : [], + ), ); return { viewer, - entries: [...entries, ...authored.flatMap((result) => result.entries)], + entries: [...entries, ...authoredEntries], errors: [ ...errors, - ...authored.flatMap((result) => (result.error === null ? [] : [result.error])), + ...rawAuthored.flatMap((result) => (result.error === null ? [] : [result.error])), ], } satisfies PullRequestListResult; }); diff --git a/apps/server/src/relay/securePipe.ts b/apps/server/src/relay/securePipe.ts index e362ea5c0..c2cf323c9 100644 --- a/apps/server/src/relay/securePipe.ts +++ b/apps/server/src/relay/securePipe.ts @@ -237,7 +237,9 @@ export function openSecurePipe(input: { } if (!sawHandshake) { sawHandshake = true; - void handleHandshake(frame); + // Copy before crossing the async `responderReady` boundary in case the + // underlying transport reuses its receive buffer. + void handleHandshake(frame.slice()); return; } if (!stream) { diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 11f7a0c6b..1242b6b42 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -102,6 +102,7 @@ export interface GitLocalStatusDetails { upstreamRef: string | null; hasWorkingTreeChanges: boolean; workingTree: VcsStatusResult["workingTree"]; + configSnapshot?: GitConfigSnapshot; } export interface GitStatusDetails extends GitLocalStatusDetails { @@ -122,6 +123,7 @@ export interface GitRemoteStatusDetails { aheadCount: number; behindCount: number; aheadOfDefaultCount: number; + configSnapshot?: GitConfigSnapshot; } /** Start point for a new worktree: a local branch or a remote-tracking ref. */ @@ -808,6 +810,45 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( ), ); + const listIgnoredTrackedPaths: NonNullable< + VcsDriver.VcsDriverShape["listIgnoredTrackedPaths"] + > = (cwd) => + gitCommand( + vcsProcess, + "GitVcsDriver.listIgnoredTrackedPaths", + cwd, + [ + ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, + "ls-files", + "--cached", + "--ignored", + "--exclude-standard", + "-z", + ], + { + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + appendTruncationMarker: true, + }, + ).pipe( + Effect.flatMap((result) => + result.exitCode === 0 && !result.stdoutTruncated + ? Effect.succeed(splitNullSeparatedPaths(result.stdout, false)) + : Effect.fail( + new VcsProcessExitError({ + operation: "GitVcsDriver.listIgnoredTrackedPaths", + command: "git ls-files --cached --ignored", + cwd, + exitCode: result.exitCode, + detail: result.stdoutTruncated + ? "git ls-files --cached --ignored output truncated" + : result.stderr.trim() || "git ls-files --cached --ignored failed", + }), + ), + ), + ); + const listRemotes: VcsDriver.VcsDriverShape["listRemotes"] = Effect.fn("listRemotes")( function* (cwd) { const result = yield* gitCommand( @@ -1926,6 +1967,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* ( detectRepository, isInsideWorkTree, listWorkspaceFiles, + listIgnoredTrackedPaths, listRemotes, filterIgnoredPaths, initRepository, diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 96e1f3013..665d38996 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2275,6 +2275,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) : 0; + const configSnapshot = yield* reads.config.pipe(Effect.orElseSucceed(() => undefined)); + return { isRepo: true, isDefaultBranch, @@ -2285,6 +2287,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* aheadCount, behindCount, aheadOfDefaultCount, + ...(configSnapshot ? { configSnapshot } : {}), } satisfies GitVcsDriver.GitRemoteStatusDetails; }); @@ -2324,6 +2327,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* let behindCount = 0; let aheadOfDefaultCount = 0; let hasWorkingTreeChanges = false; + let sawStatusEntry = false; const changedFilesByPath = new Map(); for (const line of statusStdout.split(/\r?\n/g)) { @@ -2350,6 +2354,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* continue; } if (line.trim().length > 0 && !line.startsWith("#")) { + sawStatusEntry = true; const change = parsePorcelainChange(line); if (change) { hasWorkingTreeChanges = true; @@ -2373,8 +2378,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* parseNumstatEntries(stdout).filter( (entry) => !entry.binary || changedFilesByPath.has(entry.path), ); - const numstatDetails = - headSha !== null && !hasMixedIndexAndWorktreeChanges + const numstatDetails = !sawStatusEntry + ? Effect.succeed({ mode: "combined", entries: [] as ReadonlyArray } as const) + : headSha !== null && !hasMixedIndexAndWorktreeChanges ? runGitStdout("GitVcsDriver.statusDetails.combinedNumstat", cwd, [ ...DIFF_WITHOUT_INDEX_REFRESH, "HEAD", @@ -2412,11 +2418,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ), ); const reads = yield* makeStatusReads(cwd); - const [workingTreeNumstat, defaultBranch, hasPrimaryRemote] = yield* Effect.all( + const [workingTreeNumstat, defaultBranch, hasPrimaryRemote, configSnapshot] = yield* Effect.all( [ numstatDetails, reads.defaultBranch("origin").pipe(Effect.catch(() => Effect.succeed(null))), reads.hasOriginRemote, + reads.config.pipe(Effect.orElseSucceed(() => undefined)), ], { concurrency: "unbounded" }, ); @@ -2613,6 +2620,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* aheadCount, behindCount, aheadOfDefaultCount, + ...(configSnapshot ? { configSnapshot } : {}), }; }); diff --git a/apps/server/src/vcs/VcsDriver.ts b/apps/server/src/vcs/VcsDriver.ts index 5a6047940..f664dcf8d 100644 --- a/apps/server/src/vcs/VcsDriver.ts +++ b/apps/server/src/vcs/VcsDriver.ts @@ -217,6 +217,13 @@ export interface VcsDriverShape { readonly listWorkspaceFiles: ( cwd: string, ) => Effect.Effect; + /** + * Tracked paths that still match ignore rules (optional fast path for drivers + * whose `listWorkspaceFiles` already excludes ignored untracked files). + */ + readonly listIgnoredTrackedPaths?: ( + cwd: string, + ) => Effect.Effect, VcsError>; readonly listRemotes: (cwd: string) => Effect.Effect; readonly filterIgnoredPaths: ( cwd: string, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 8372a2afe..d8507cf6d 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -11,6 +11,7 @@ import * as PubSub from "effect/PubSub"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; +import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; import type { @@ -28,6 +29,7 @@ import { checkoutPresence } from "./CheckoutPresence.ts"; import { isScratchIndexFileName } from "./scratchIndex.ts"; const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.minutes(2); +const REMOTE_REFRESH_CONCURRENCY = 4; const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.minutes(2); const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15); const VCS_STATUS_REFRESH_UNCHANGED_MAX_DELAY = Duration.minutes(10); @@ -605,6 +607,7 @@ export const layer = Layer.effect( } }); + const remoteRefreshSemaphore = yield* Semaphore.make(REMOTE_REFRESH_CONCURRENCY); const makeRemoteRefreshLoop = ( cwd: string, automaticRemoteRefreshInterval: Effect.Effect, @@ -632,20 +635,52 @@ export const layer = Layer.effect( } } - const exit = yield* refreshRemoteStatus(cwd).pipe(Effect.exit); + const outcome = yield* remoteRefreshSemaphore.withPermits(1)( + Effect.gen(function* () { + // Re-check setting and cache freshness after acquiring the permit so + // disabling auto-fetch or a manual refresh cancels the queued poll. + const recheckedInterval = yield* automaticRemoteRefreshInterval; + if (Duration.isZero(recheckedInterval)) { + return { + _tag: "skip" as const, + delay: DEFAULT_VCS_STATUS_REFRESH_INTERVAL, + }; + } + const latestCached = yield* getCachedStatus(cwd); + const latestUpdatedAtMs = latestCached?.remote?.updatedAtMs ?? null; + if (latestUpdatedAtMs !== null) { + const nowMs = yield* Clock.currentTimeMillis; + const recheckedMs = Duration.toMillis(recheckedInterval); + const ageMs = Math.max(0, nowMs - latestUpdatedAtMs); + if (ageMs < recheckedMs) { + return { + _tag: "skip" as const, + delay: Duration.millis(Math.max(1, recheckedMs - ageMs)), + }; + } + } + const refreshExit = yield* refreshRemoteStatus(cwd).pipe(Effect.exit); + return { _tag: "ran" as const, exit: refreshExit, interval: recheckedInterval }; + }), + ); + if (outcome._tag === "skip") { + return outcome.delay; + } + const exit = outcome.exit; + const runInterval = outcome.interval; if (Exit.isSuccess(exit)) { yield* Ref.set(consecutiveFailuresRef, 0); const consecutiveUnchangedRefreshes = exit.value.changed ? yield* Ref.set(consecutiveUnchangedRefreshesRef, 0).pipe(Effect.as(0)) : yield* Ref.updateAndGet(consecutiveUnchangedRefreshesRef, (count) => count + 1); - return remoteRefreshSuccessDelay(consecutiveUnchangedRefreshes, activeInterval); + return remoteRefreshSuccessDelay(consecutiveUnchangedRefreshes, runInterval); } const consecutiveFailures = yield* Ref.updateAndGet( consecutiveFailuresRef, (count) => count + 1, ); - const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval); + const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, runInterval); yield* Effect.logWarning("VCS remote status refresh failed", { cwd, detail: exit.cause.toString(), diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.ts index b34e4ccff..24452760d 100644 --- a/apps/server/src/workspace/Layers/WorkspaceEntries.ts +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.ts @@ -490,21 +490,39 @@ export const makeWorkspaceEntries = Effect.gen(function* () { return null; } - const listedFiles = yield* vcs.driver - .listWorkspaceFiles(cwd) - .pipe(Effect.catch(() => Effect.succeed(null))); + const [listedFiles, ignoredTracked] = yield* Effect.all( + [ + vcs.driver.listWorkspaceFiles(cwd).pipe(Effect.catch(() => Effect.succeed(null))), + vcs.driver.listIgnoredTrackedPaths + ? vcs.driver + .listIgnoredTrackedPaths(cwd) + .pipe(Effect.catch(() => Effect.succeed | null>(null))) + : Effect.succeed | null>(null), + ], + { concurrency: 2 }, + ); if (!listedFiles) { return null; } - const listedPaths = [...listedFiles.paths] + const rawPaths = + ignoredTracked !== null && ignoredTracked.length > 0 + ? (() => { + const ignoredSet = new Set(ignoredTracked); + return listedFiles.paths.filter((entry) => !ignoredSet.has(entry)); + })() + : listedFiles.paths; + const listedPaths = [...rawPaths] .map((entry) => toPosixPath(entry)) .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); - const filePaths = yield* vcs.driver.filterIgnoredPaths(cwd, listedPaths).pipe( - Effect.map((paths) => [...paths]), - Effect.catch(() => filterVcsIgnoredPaths(cwd, listedPaths)), - ); + const filePaths = + ignoredTracked !== null + ? listedPaths + : yield* vcs.driver.filterIgnoredPaths(cwd, listedPaths).pipe( + Effect.map((paths) => [...paths]), + Effect.catch(() => filterVcsIgnoredPaths(cwd, listedPaths)), + ); const directorySet = new Set(); for (const filePath of filePaths) { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 8d57372bf..4e253d5a4 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1,4 +1,3 @@ -import * as Equal from "effect/Equal"; import { estimateWorkflowRunCardHeight } from "./workflowRunView"; import { MCP_APP_CARD_ESTIMATED_PX } from "./mcpAppClient"; import { nextCheckBack } from "./checkBacks"; @@ -2416,8 +2415,8 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean a.folded === bw.folded && sameIds(a.trackerTurnIds, bw.trackerTurnIds) && sameIds(a.trackerAgentSpawnIds, bw.trackerAgentSpawnIds) && - Equal.equals(a.groupedEntries, bw.groupedEntries) && - Equal.equals(a.agentAnchorEntries, bw.agentAnchorEntries) + sameWorkLogEntries(a.groupedEntries, bw.groupedEntries) && + sameWorkLogEntries(a.agentAnchorEntries, bw.agentAnchorEntries) ); } @@ -2455,7 +2454,68 @@ function isTurnSummaryUnchanged(a: TurnSummary | null, b: TurnSummary | null): b } function sameIds(a: ReadonlyArray, b: ReadonlyArray): boolean { - return a.length === b.length && a.every((id, index) => id === b[index]); + if (a === b) return true; + if (a.length !== b.length) return false; + for (let index = 0; index < a.length; index += 1) { + if (a[index] !== b[index]) return false; + } + return true; +} + +function samePlainValue(a: unknown, b: unknown): boolean { + if (Object.is(a, b)) return true; + if (a === null || b === null || typeof a !== "object" || typeof b !== "object") { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b) || a.length !== b.length) return false; + for (let index = 0; index < a.length; index += 1) { + if (!samePlainValue(a[index], b[index])) return false; + } + return true; + } + if (Array.isArray(b)) return false; + const aRecord = a as Record; + const bRecord = b as Record; + const aKeys = Object.keys(aRecord); + const bKeys = Object.keys(bRecord); + if (aKeys.length !== bKeys.length) return false; + for (let index = 0; index < aKeys.length; index += 1) { + const key = aKeys[index]!; + if (!Object.prototype.hasOwnProperty.call(bRecord, key)) return false; + if (!samePlainValue(aRecord[key], bRecord[key])) return false; + } + return true; +} + +function sameWorkLogEntries( + a: ReadonlyArray, + b: ReadonlyArray, +): boolean { + if (a === b) return true; + if (a.length !== b.length) return false; + for (let index = 0; index < a.length; index += 1) { + const left = a[index]; + const right = b[index]; + if (left === right) continue; + if ( + !left || + !right || + left.id !== right.id || + left.createdAt !== right.createdAt || + left.completedAt !== right.completedAt || + left.label !== right.label || + left.detail !== right.detail || + left.tone !== right.tone || + left.executionState !== right.executionState || + left.outputPreview !== right.outputPreview || + left.eventSequence !== right.eventSequence || + !samePlainValue(left, right) + ) { + return false; + } + } + return true; } const MAX_COLLAPSED_USER_MESSAGE_LINES = 8; diff --git a/apps/web/src/diffPanelPreload.ts b/apps/web/src/diffPanelPreload.ts index 7de26eea5..cb8f66e42 100644 --- a/apps/web/src/diffPanelPreload.ts +++ b/apps/web/src/diffPanelPreload.ts @@ -10,6 +10,7 @@ export function preloadDiffPanel(): void { return; } diffPanelPreloadRequested = true; + void import("./components/DiffWorkerPoolProvider"); void import("./components/DiffPanel"); } diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx index a9d36a4de..164041eb2 100644 --- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx +++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx @@ -13,7 +13,6 @@ import { HostedStaticLinkNotPairedState, HostedStaticLoadingState, } from "../components/ConnectionStatusStates"; -import { DiffWorkerPoolProvider } from "../components/DiffWorkerPoolProvider"; import { DiffPanelLoadingState, DiffPanelShell, @@ -153,7 +152,21 @@ interface ThreadPullRequestTarget { readonly own: boolean; } -const DiffPanel = lazy(() => import("../components/DiffPanel")); +const DiffPanelWithWorkers = lazy(async () => { + const [{ DiffWorkerPoolProvider }, { default: DiffPanelComponent }] = await Promise.all([ + import("../components/DiffWorkerPoolProvider"), + import("../components/DiffPanel"), + ]); + return { + default: function LazyDiffPanelWithWorkers(props: { mode: DiffPanelMode }) { + return ( + + + + ); + }, + }; +}); const MediaPanel = lazy(() => import("../components/media/MediaPanel").then((module) => ({ default: module.MediaPanel })), ); @@ -193,11 +206,9 @@ const DiffLoadingFallback = (props: { mode: DiffPanelMode }) => { const LazyDiffPanel = (props: { mode: DiffPanelMode }) => { return ( - - }> - - - + }> + + ); }; diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 5dd5690fd..32128f647 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -2366,14 +2366,22 @@ function upsertThreadActivity( return retainThreadActivities([...activities, nextActivity], MAX_THREAD_ACTIVITIES); } - const nextActivities = - existingIndex === -1 - ? [...activities, nextActivity] - : [ - ...activities.slice(0, existingIndex), - nextActivity, - ...activities.slice(existingIndex + 1), - ]; + if (existingIndex !== -1) { + const previous = existingIndex > 0 ? activities[existingIndex - 1] : undefined; + const following = + existingIndex + 1 < activities.length ? activities[existingIndex + 1] : undefined; + const inOrder = + (previous === undefined || compareActivities(previous, nextActivity) <= 0) && + (following === undefined || compareActivities(nextActivity, following) <= 0); + const nextActivities = activities.slice(); + nextActivities[existingIndex] = nextActivity; + return retainThreadActivities( + inOrder ? nextActivities : nextActivities.toSorted(compareActivities), + MAX_THREAD_ACTIVITIES, + ); + } + + const nextActivities = [...activities, nextActivity]; return retainThreadActivities(nextActivities.toSorted(compareActivities), MAX_THREAD_ACTIVITIES); } diff --git a/apps/web/src/theme/ThemeBackdropLayer.tsx b/apps/web/src/theme/ThemeBackdropLayer.tsx index f65ec820d..a6448ae4d 100644 --- a/apps/web/src/theme/ThemeBackdropLayer.tsx +++ b/apps/web/src/theme/ThemeBackdropLayer.tsx @@ -118,14 +118,17 @@ export function ThemeBackdropLayer(props: { phone, }); + const liveArtActive = conditions.motion === "live" && conditions.visible; useEffect(() => { const bridge = window.desktopBridge; if (!bridge?.setBackdropActive) return; - void bridge.setBackdropActive(true).catch(() => {}); + void bridge.setBackdropActive(liveArtActive).catch(() => {}); return () => { - void bridge.setBackdropActive?.(false).catch(() => {}); + if (liveArtActive) { + void bridge.setBackdropActive?.(false).catch(() => {}); + } }; - }, []); + }, [liveArtActive]); const hostRef = useRef(null); useEffect(() => { diff --git a/packages/client-runtime/src/device/mjpeg.ts b/packages/client-runtime/src/device/mjpeg.ts index f83b616e8..95c857cde 100644 --- a/packages/client-runtime/src/device/mjpeg.ts +++ b/packages/client-runtime/src/device/mjpeg.ts @@ -6,7 +6,8 @@ */ import { DEVICE_MAX_FRAME_BYTES, DeviceFrameTooLargeError } from "./frameLimit.ts"; -const HEADER_END = [13, 10, 13, 10]; +const HEADER_END = [13, 10, 13, 10] as const; +const JPEG_EOI = [0xff, 0xd9] as const; const MAX_HEADER_BYTES = 8 * 1024; const latin1 = new TextDecoder("latin1"); @@ -28,6 +29,9 @@ export class MultipartJpegParser { private length = 0; /** Bytes of the current part's body, once its headers are read; null for "until EOI". */ private expected: number | null | undefined = undefined; + /** Offset from the start of the current header/body to resume scanning on the next chunk. */ + private headerScanFrom = 0; + private eoiScanFrom = 2; push(bytes: Uint8Array): Uint8Array[] { // A part at the limit plus the chunk that completes it; more is never a valid stream. @@ -49,11 +53,14 @@ export class MultipartJpegParser { let offset = 0; for (;;) { if (this.expected === undefined) { - const end = indexOfSequence(view, HEADER_END, offset); + const end = indexOfSequence(view, HEADER_END, offset + this.headerScanFrom); if (end < 0) { // A runaway header block is not a stream we can read; keep only a split CRLFCRLF tail. if (this.length - offset > MAX_HEADER_BYTES) { offset = Math.max(offset, this.length - (HEADER_END.length - 1)); + this.headerScanFrom = 0; + } else { + this.headerScanFrom = Math.max(0, this.length - offset - (HEADER_END.length - 1)); } break; } @@ -64,12 +71,17 @@ export class MultipartJpegParser { throw new DeviceFrameTooLargeError("still frame", this.expected); } offset = end + HEADER_END.length; + this.headerScanFrom = 0; + this.eoiScanFrom = 2; continue; } let frameEnd: number; if (this.expected === null) { - const eoi = indexOfSequence(view, [0xff, 0xd9], offset + 2); - if (eoi < 0) break; + const eoi = indexOfSequence(view, JPEG_EOI, offset + this.eoiScanFrom); + if (eoi < 0) { + this.eoiScanFrom = Math.max(2, this.length - offset - (JPEG_EOI.length - 1)); + break; + } frameEnd = eoi + 2; } else { if (this.length - offset < this.expected) break; @@ -79,6 +91,8 @@ export class MultipartJpegParser { if (frame[0] === 0xff && frame[1] === 0xd8) frames.push(frame); offset = frameEnd; this.expected = undefined; + this.headerScanFrom = 0; + this.eoiScanFrom = 2; } if (offset > 0) { this.buffer.copyWithin(0, offset, this.length); diff --git a/packages/shared/src/relaySecure.ts b/packages/shared/src/relaySecure.ts index a8ab25b71..e7beb4fba 100644 --- a/packages/shared/src/relaySecure.ts +++ b/packages/shared/src/relaySecure.ts @@ -35,10 +35,7 @@ const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder("utf-8", { fatal: true }); export function utf8(text: string): Bytes { - const encoded = textEncoder.encode(text); - const bytes = new Uint8Array(encoded.length); - bytes.set(encoded); - return bytes; + return asOwnedBytes(textEncoder.encode(text)); } export function fromUtf8(bytes: Uint8Array): string { @@ -46,7 +43,9 @@ export function fromUtf8(bytes: Uint8Array): string { } export function concatBytes(...parts: ReadonlyArray): Bytes { - const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)); + let total = 0; + for (const part of parts) total += part.length; + const out = new Uint8Array(total); let offset = 0; for (const part of parts) { out.set(part, offset); @@ -55,6 +54,13 @@ export function concatBytes(...parts: ReadonlyArray): Bytes { return out; } +function prependByte(byte: number, body: Uint8Array): Bytes { + const out = new Uint8Array(1 + body.length); + out[0] = byte; + out.set(body, 1); + return out; +} + /** Concatenation that can't be read two ways: each field is length-prefixed. */ function framed(...fields: ReadonlyArray): Bytes { const parts: Array = []; @@ -72,6 +78,29 @@ function copyBytes(view: Uint8Array): Bytes { return out; } +function isFixedArrayBuffer(buffer: ArrayBufferLike): buffer is ArrayBuffer { + return ( + buffer instanceof ArrayBuffer && (buffer as { readonly resizable?: boolean }).resizable !== true + ); +} + +/** Avoids copying when the view already owns its entire non-resizable ArrayBuffer. */ +function asOwnedBytes(view: Uint8Array): Bytes { + if ( + isFixedArrayBuffer(view.buffer) && + view.byteOffset === 0 && + view.byteLength === view.buffer.byteLength + ) { + return view as Bytes; + } + return copyBytes(view); +} + +/** WebCrypto accepts non-resizable ArrayBuffer-backed views directly; resizable/SharedArrayBuffer views need a copy. */ +function asBufferSource(view: Uint8Array): Bytes { + return isFixedArrayBuffer(view.buffer) ? (view as Bytes) : copyBytes(view); +} + export function randomBytes(length: number): Bytes { const bytes = new Uint8Array(length); globalThis.crypto.getRandomValues(bytes); @@ -110,18 +139,18 @@ export function bytesEqual(left: Uint8Array, right: Uint8Array): boolean { // ----- primitives --------------------------------------------------------------- export async function sha256(data: Uint8Array): Promise { - return new Uint8Array(await subtle().digest("SHA-256", copyBytes(data))); + return new Uint8Array(await subtle().digest("SHA-256", asBufferSource(data))); } export async function hmacSha256(key: Uint8Array, data: Uint8Array): Promise { const imported = await subtle().importKey( "raw", - copyBytes(key), + asBufferSource(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"], ); - return new Uint8Array(await subtle().sign("HMAC", imported, copyBytes(data))); + return new Uint8Array(await subtle().sign("HMAC", imported, asBufferSource(data))); } /** Noise's HKDF: two outputs keyed by the chaining key. */ @@ -166,7 +195,7 @@ function makeDh(input: { if (raw.length !== input.publicKeyLength || !input.isValidRawPublicKey(raw)) { throw new Error("Invalid public key."); } - return subtle().importKey("raw", copyBytes(raw), algorithm, true, []); + return subtle().importKey("raw", asBufferSource(raw), algorithm, true, []); }; return { name: input.name, @@ -185,7 +214,7 @@ function makeDh(input: { await importPublicKey(publicKey); const privateKey = await subtle().importKey( "pkcs8", - copyBytes(privatePkcs8), + asBufferSource(privatePkcs8), algorithm, true, ["deriveBits"], @@ -236,7 +265,7 @@ export class CipherState { } async initializeKey(raw: Uint8Array): Promise { - this.key = await subtle().importKey("raw", copyBytes(raw), "AES-GCM", false, [ + this.key = await subtle().importKey("raw", asBufferSource(raw), "AES-GCM", false, [ "encrypt", "decrypt", ]); @@ -260,9 +289,9 @@ export class CipherState { if (!this.key) return copyBytes(plaintext); const ciphertext = new Uint8Array( await subtle().encrypt( - { name: "AES-GCM", iv: this.iv(), additionalData: copyBytes(ad), tagLength: 128 }, + { name: "AES-GCM", iv: this.iv(), additionalData: asBufferSource(ad), tagLength: 128 }, this.key, - copyBytes(plaintext), + asBufferSource(plaintext), ), ); this.nonce += 1; @@ -273,9 +302,9 @@ export class CipherState { if (!this.key) return copyBytes(ciphertext); const plaintext = new Uint8Array( await subtle().decrypt( - { name: "AES-GCM", iv: this.iv(), additionalData: copyBytes(ad), tagLength: 128 }, + { name: "AES-GCM", iv: this.iv(), additionalData: asBufferSource(ad), tagLength: 128 }, this.key, - copyBytes(ciphertext), + asBufferSource(ciphertext), ), ); this.nonce += 1; @@ -461,7 +490,7 @@ export const SECURE_CONFIRM_SESSION = 0x01; export const SECURE_CONFIRM_PROBE = 0x02; export function handshakeFrame(message: Uint8Array): Bytes { - return concatBytes(new Uint8Array([SECURE_FRAME_HANDSHAKE]), message); + return prependByte(SECURE_FRAME_HANDSHAKE, message); } /** The handshake message in a frame, or null unless it's exactly the expected size. */ @@ -472,7 +501,12 @@ export function readHandshakeFrame(frame: Uint8Array, expectedLength: number): B /** Turns WebSocket message data into bytes; null for text frames. */ export function binaryFrameBytes(data: unknown): Bytes | null { - if (data instanceof ArrayBuffer) return new Uint8Array(data); + if (data instanceof ArrayBuffer) { + return isFixedArrayBuffer(data) ? new Uint8Array(data) : copyBytes(new Uint8Array(data)); + } + if (data instanceof Uint8Array) { + return asOwnedBytes(data); + } if (ArrayBuffer.isView(data)) { return copyBytes(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); } @@ -539,7 +573,7 @@ export class SecureStream { } sendRecord(type: number, body: Uint8Array = EMPTY): void { - const record = concatBytes(new Uint8Array([type]), body); + const record = prependByte(type, body); this.sendQueue = this.sendQueue.then(async () => { if (this.stopped) return; let ciphertext: Bytes; @@ -552,8 +586,9 @@ export class SecureStream { if (this.stopped) return; for (let offset = 0; offset < ciphertext.length; offset += SECURE_PART_BYTES) { const end = Math.min(offset + SECURE_PART_BYTES, ciphertext.length); - const type = end === ciphertext.length ? SECURE_FRAME_DATA_FINAL : SECURE_FRAME_DATA_PART; - this.sendFrame(concatBytes(new Uint8Array([type]), ciphertext.subarray(offset, end))); + const frameType = + end === ciphertext.length ? SECURE_FRAME_DATA_FINAL : SECURE_FRAME_DATA_PART; + this.sendFrame(prependByte(frameType, ciphertext.subarray(offset, end))); } }); } @@ -599,9 +634,13 @@ export class SecureStream { this.fail("Message too large."); return; } - this.parts.push(copyBytes(frame.subarray(1))); - if (type === SECURE_FRAME_DATA_PART) return; - const ciphertext = concatBytes(...this.parts); + if (type === SECURE_FRAME_DATA_PART) { + this.parts.push(copyBytes(frame.subarray(1))); + return; + } + const payload = frame.subarray(1); + const ciphertext = + this.parts.length === 0 ? copyBytes(payload) : concatBytes(...this.parts, payload); this.parts = []; this.partBytes = 0; this.messagesAssembled += 1; diff --git a/packages/shared/src/searchRanking.ts b/packages/shared/src/searchRanking.ts index f6ddd4aaa..179cdf3b8 100644 --- a/packages/shared/src/searchRanking.ts +++ b/packages/shared/src/searchRanking.ts @@ -30,8 +30,10 @@ export interface SearchTextMatchAnalysis { } const MAX_SEARCH_OCCURRENCES_PER_CLAUSE = 64; +const MAX_SEARCH_PATTERN_CACHE_ENTRIES = 256; const ORDERED_SEARCH_SCORE_BASE = 100_000_000; const UNORDERED_SEARCH_SCORE_BASE = 200_000_000; +const searchClauseRegexCache = new Map(); function normalizeSearchClause(value: string): string { return value.normalize("NFKC").trim().toLowerCase().replace(/\s+/gu, " "); @@ -116,21 +118,45 @@ function searchClausePattern(value: string): string { return value.split(" ").map(escapeSearchRegularExpression).join("\\s+"); } +function getSearchClauseRegex(value: string): RegExp { + let cached = searchClauseRegexCache.get(value); + if (cached !== undefined) { + return cached; + } + cached = new RegExp(searchClausePattern(value), "giu"); + if (searchClauseRegexCache.size >= MAX_SEARCH_PATTERN_CACHE_ENTRIES) { + const oldestKey = searchClauseRegexCache.keys().next().value; + if (oldestKey !== undefined) { + searchClauseRegexCache.delete(oldestKey); + } + } + searchClauseRegexCache.set(value, cached); + return cached; +} + function findSearchTextOccurrences( text: string, value: string, clauseIndex: number, + maxOccurrences = MAX_SEARCH_OCCURRENCES_PER_CLAUSE, ): SearchTextMatchRange[] { - const pattern = new RegExp(searchClausePattern(value), "giu"); + if (!value) { + return []; + } + const pattern = getSearchClauseRegex(value); + pattern.lastIndex = 0; const ranges: SearchTextMatchRange[] = []; - for (const match of text.matchAll(pattern)) { + let match: RegExpExecArray | null; + while ((match = pattern.exec(text)) !== null) { const start = match.index; const matchedText = match[0]; - if (start === undefined || matchedText.length === 0) { + if (matchedText.length === 0) { + const codePoint = text.codePointAt(pattern.lastIndex); + pattern.lastIndex += codePoint !== undefined && codePoint > 0xffff ? 2 : 1; continue; } ranges.push({ clauseIndex, start, end: start + matchedText.length }); - if (ranges.length >= MAX_SEARCH_OCCURRENCES_PER_CLAUSE) { + if (ranges.length >= maxOccurrences) { break; } } @@ -264,14 +290,32 @@ export function analyzeSearchText( return null; } - const occurrencesByClause = parsed.clauses.map((clause, clauseIndex) => - findSearchTextOccurrences(text, clause.value, clauseIndex), - ); - if (occurrencesByClause.some((occurrences) => occurrences.length === 0)) { - return null; + if (parsed.clauses.length === 1) { + const firstMatch = findSearchTextOccurrences(text, parsed.clauses[0]!.value, -1, 1)[0]; + if (!firstMatch) { + return null; + } + return { + score: Math.min(99_999_999, firstMatch.start), + kind: "exact-phrase", + ranges: [firstMatch], + }; + } + + const occurrencesByClause: SearchTextMatchRange[][] = []; + for (let clauseIndex = 0; clauseIndex < parsed.clauses.length; clauseIndex += 1) { + const occurrences = findSearchTextOccurrences( + text, + parsed.clauses[clauseIndex]!.value, + clauseIndex, + ); + if (occurrences.length === 0) { + return null; + } + occurrencesByClause.push(occurrences); } - const phraseRange = findSearchTextOccurrences(text, parsed.phrase, -1)[0]; + const phraseRange = findSearchTextOccurrences(text, parsed.phrase, -1, 1)[0]; if (phraseRange) { return { score: Math.min(99_999_999, phraseRange.start),