From 959b4597a750f85156316294f4b7ca2f951c2196 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:47:03 +0000 Subject: [PATCH 1/3] fix(server): spend guard only warns by default and no longer refuses a founder's resumed turn The session spend guard defaulted to enforce, so an idle thread over $50 refused every automated turn. It is an alert, so the default is now flag; enforce stays available as a setting. Two bugs made the refusals wrong. Other-agent input (subagents, compaction) was priced as fully uncached input although the process ledger adds cache reads into that number, so one 24-lane turn read $89 instead of about $14 and tripped the idle limit even on threads with a linked pull request. The refusal text also said no pull request was linked when one was. And a restart continuation is created by the server, so a founder's own "continue anyway" turn, interrupted by a restart, was refused as automated. The guard now follows the continuation chain back to the message that started it. Co-Authored-By: Claude Sonnet 5.5 --- .../ProviderTurnStartService.test.ts | 49 ++++++- .../ProviderTurnStartService.ts | 11 +- .../SessionSpendGuard.test.ts | 132 +++++++++++++++--- .../src/orchestration-v2/SessionSpendGuard.ts | 34 ++++- packages/contracts/src/settings.test.ts | 8 +- packages/contracts/src/settings.ts | 2 +- 6 files changed, 206 insertions(+), 30 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 8e8c1123cab94..173ea07b8a0b2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -295,7 +295,8 @@ it.each([ function startWithSpendGuard(input: { readonly title: string; - readonly creationSource: "web" | "mcp"; + readonly creationSource: "web" | "mcp" | "server"; + readonly restartContinuationOf?: "web" | "mcp"; readonly pullRequestLinkedAt?: string; readonly providerTurns: ReadonlyArray<{ readonly startedAt: string; @@ -308,6 +309,8 @@ function startWithSpendGuard(input: { const rootNodeId = NodeId.make("node_provider_turn_start_spend_guard"); const providerThreadId = ProviderThreadId.make("provider_thread_provider_turn_start_spend_guard"); const messageId = MessageId.make("message_provider_turn_start_spend_guard"); + const sourceRunId = RunId.make("run_provider_turn_start_spend_guard_source"); + const sourceMessageId = MessageId.make("message_provider_turn_start_spend_guard_source"); const projection = { thread: { id: threadId, @@ -323,8 +326,14 @@ function startWithSpendGuard(input: { }, runs: [ { id: RunId.make("run_provider_turn_start_spend_guard_first"), ordinal: 1 }, + ...(input.restartContinuationOf === undefined + ? [] + : [{ id: sourceRunId, userMessageId: sourceMessageId, ordinal: 1 }]), { id: runId, + ...(input.restartContinuationOf === undefined + ? {} + : { restartContinuationOfRunId: sourceRunId }), status: "starting", rootNodeId, activeAttemptId: attemptId, @@ -349,6 +358,17 @@ function startWithSpendGuard(input: { attachments: [], creationSource: input.creationSource, }, + ...(input.restartContinuationOf === undefined + ? [] + : [ + { + id: sourceMessageId, + role: "user", + text: "continue anyway", + attachments: [], + creationSource: input.restartContinuationOf, + }, + ]), ], checkpointScopes: [{ id: CheckpointScopeId.make("scope_spend_guard") }], checkpoints: [], @@ -458,6 +478,33 @@ effectIt.effect("lets a founder's own turn through at the session ceiling", () = }), ); +effectIt.effect("lets a restart continuation of a founder's own turn through at the ceiling", () => + Effect.gen(function* () { + const harness = startWithSpendGuard({ + title: "Manager work", + creationSource: "server", + restartContinuationOf: "web", + providerTurns: [{ startedAt: "2099-01-01T00:00:01.000Z", inputTokens: 1 }], + }); + yield* Effect.exit(harness.start); + expect(harness.refusal()?.title).not.toBe("Turn refused by the session spend guard"); + }), +); + +effectIt.effect("still refuses a restart continuation of an automated turn at the ceiling", () => + Effect.gen(function* () { + const harness = startWithSpendGuard({ + title: "Manager work", + creationSource: "server", + restartContinuationOf: "mcp", + providerTurns: [{ startedAt: "2099-01-01T00:00:01.000Z", inputTokens: 1 }], + }); + yield* harness.start; + expect(harness.refusal()?.failure.message).toContain("session ceiling"); + expect(harness.startRootRun).not.toHaveBeenCalled(); + }), +); + effectIt.effect("counts every provider turn in the thread toward the session ceiling", () => Effect.gen(function* () { const harness = startWithSpendGuard({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 6645673dbc846..ba488f2c89f54 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -69,6 +69,7 @@ import * as RunExecutionService from "./RunExecutionService.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; import { checkLaunch, + originCreationSource, refusesAutomatedTurn, describeSpendStop, evaluateThreadSpend, @@ -563,11 +564,17 @@ export const layer: Layer.Layer< }, ); const guardSettings = yield* serverSettings.getSettings; + const guardCreationSource = + originCreationSource({ + run, + runs: projection.runs, + messages: projection.messages, + }) ?? message.creationSource; const launchRefusal = checkLaunch({ title: projection.thread.title, titlePending: projection.thread.titleRegeneration != null, hasOtherUserMessages: projection.runs.some((candidate) => candidate.ordinal < run.ordinal), - creationSource: message.creationSource, + creationSource: guardCreationSource, mode: guardSettings.sessionSpendGuard.mode, }); if (launchRefusal !== null) { @@ -579,7 +586,7 @@ export const layer: Layer.Layer< }); return; } - if (refusesAutomatedTurn(guardSettings.sessionSpendGuard.mode, message.creationSource)) { + if (refusesAutomatedTurn(guardSettings.sessionSpendGuard.mode, guardCreationSource)) { const { checkpoints } = yield* projectionStore.getThreadRecords(input.threadId, [ "checkpoints", ]); diff --git a/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts b/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts index eae258d366f13..77848e2c71cf3 100644 --- a/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts +++ b/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts @@ -8,6 +8,7 @@ import { describeSpendStop, evaluateSpendGuard, evaluateThreadSpend, + originCreationSource, priceProviderTurns, rateForModel, spendGuardMarkers, @@ -30,6 +31,7 @@ const rate = { const settings = { ...decodeSettings({}).sessionSpendGuard, + mode: "enforce" as const, idleFlagUsd: 3, idleStopUsd: 5, sessionCeilingUsd: 10, @@ -56,26 +58,69 @@ const evaluate = (overrides: Partial = {}) => describe("priceProviderTurns", () => { it("prices uncached input, cache read, output, and other usage", () => { - expect( - priceProviderTurns( - [ - { - startedAt: at("2026-01-01T00:00:00.000Z"), - completedAt: at("2026-01-01T00:05:00.000Z"), - turnTokenUsage: { - usageScope: "main_agent", - usageStatus: "complete", - hasSubagents: true, - inputTokens: 10, - cachedInputTokens: 4, - outputTokens: 2, - otherUsage: { inputTokens: 1, outputTokens: 1 }, - }, + const [entry] = priceProviderTurns( + [ + { + startedAt: at("2026-01-01T00:00:00.000Z"), + completedAt: at("2026-01-01T00:05:00.000Z"), + turnTokenUsage: { + usageScope: "main_agent", + usageStatus: "complete", + hasSubagents: true, + inputTokens: 10, + cachedInputTokens: 4, + outputTokens: 2, + otherUsage: { inputTokens: 1, outputTokens: 1 }, }, - ], - rate, - ), - ).toEqual([{ createdAt: "2026-01-01T00:00:00.000Z", usd: 13.4 }]); + }, + ], + rate, + ); + expect(entry?.createdAt).toBe("2026-01-01T00:00:00.000Z"); + expect(entry?.usd).toBeCloseTo(13.04, 6); + }); + + it("prices other-agent input at the main agent's cache mix", () => { + const [entry] = priceProviderTurns( + [ + { + startedAt: at("2026-01-01T00:00:00.000Z"), + completedAt: at("2026-01-01T00:05:00.000Z"), + turnTokenUsage: { + usageScope: "main_agent", + usageStatus: "complete", + hasSubagents: true, + inputTokens: 1000, + cachedInputTokens: 980, + outputTokens: 0, + otherUsage: { inputTokens: 1_000_000, outputTokens: 0 }, + }, + }, + ], + rate, + ); + expect(entry?.usd).toBeCloseTo(20 + 98 + 1_000_000 * (0.02 + 0.98 * 0.1), 3); + }); + + it("prices other-agent input as uncached when the main agent reports no cache reads", () => { + const [entry] = priceProviderTurns( + [ + { + startedAt: at("2026-01-01T00:00:00.000Z"), + completedAt: null, + turnTokenUsage: { + usageScope: "main_agent", + usageStatus: "complete", + hasSubagents: true, + inputTokens: 0, + outputTokens: 0, + otherUsage: { inputTokens: 10, outputTokens: 0 }, + }, + }, + ], + rate, + ); + expect(entry?.usd).toBe(10); }); it("falls back to the context snapshot and skips a turn with no counts", () => { @@ -283,14 +328,25 @@ describe("launch and stop copy", () => { const evaluation = evaluate({ spend: [priced("2026-01-01T00:01:00.000Z", 6)] }); expect(describeSpendStop(evaluation, settings)).toContain("$6.00"); expect(describeSpendStop(evaluation, settings)).toContain("$5.00"); + expect(describeSpendStop(evaluation, settings)).toContain("with no linked pull request"); expect(UNTITLED_LAUNCH_REFUSAL).toContain("default title"); }); + + it("does not say no pull request is linked when one is", () => { + const evaluation = evaluate({ + spend: [priced("2026-01-01T00:02:00.000Z", 6)], + workSignalAts: ["2026-01-01T00:01:00.000Z"], + }); + const detail = describeSpendStop(evaluation, settings); + expect(detail).toContain("since its last linked pull request or file-changing turn"); + expect(detail).not.toContain("with no linked pull request"); + }); }); describe("evaluateThreadSpend", () => { it("uses the model override and otherwise the fallback rate", () => { const decoded = decodeSettings({ - sessionSpendGuard: { idleStopUsd: 1, sessionCeilingUsd: 100 }, + sessionSpendGuard: { mode: "enforce", idleStopUsd: 1, sessionCeilingUsd: 100 }, usagePriceOverrides: { "custom-model": { inputCostPerMillionTokens: 1_000_000, @@ -323,3 +379,39 @@ describe("evaluateThreadSpend", () => { ).toBe(10 / 1_000_000); }); }); + +describe("originCreationSource", () => { + const messages = [ + { id: "m-web", creationSource: "web" as const }, + { id: "m-mcp", creationSource: "mcp" as const }, + { id: "m-server", creationSource: "server" as const }, + ] as never; + const runs = [ + { id: "r1", userMessageId: "m-web" }, + { id: "r2", userMessageId: "m-server", restartContinuationOfRunId: "r1" }, + { id: "r3", userMessageId: "m-server", restartContinuationOfRunId: "r2" }, + { id: "r4", userMessageId: "m-mcp" }, + { id: "r5", userMessageId: "m-server", restartContinuationOfRunId: "r4" }, + { id: "r6", userMessageId: "m-server", restartContinuationOfRunId: "missing" }, + ] as never; + const origin = (id: string) => + originCreationSource({ + run: (runs as ReadonlyArray<{ id: string }>).find((run) => run.id === id) as never, + runs, + messages, + }); + + it("follows restart continuations back to the founder's message", () => { + expect(origin("r1")).toBe("web"); + expect(origin("r2")).toBe("web"); + expect(origin("r3")).toBe("web"); + }); + + it("keeps an automated origin automated", () => { + expect(origin("r5")).toBe("mcp"); + }); + + it("falls back to the run's own message when the source run is gone", () => { + expect(origin("r6")).toBe("server"); + }); +}); diff --git a/apps/server/src/orchestration-v2/SessionSpendGuard.ts b/apps/server/src/orchestration-v2/SessionSpendGuard.ts index f3772ce2c48ab..d86e7c069e3c0 100644 --- a/apps/server/src/orchestration-v2/SessionSpendGuard.ts +++ b/apps/server/src/orchestration-v2/SessionSpendGuard.ts @@ -3,6 +3,7 @@ import type { OrchestrationV2Checkpoint, OrchestrationV2ConversationMessage, OrchestrationV2ProviderTurn, + OrchestrationV2Run, OrchestrationV2TurnItem, ServerSettings, SessionSpendGuardSettings, @@ -97,11 +98,14 @@ export function priceProviderTurns( const input = usage.inputTokens ?? 0; const cached = Math.min(usage.cachedInputTokens ?? 0, input); const other = turn.turnTokenUsage?.otherUsage; + const cachedShare = input > 0 ? cached / input : 0; + const otherInputRate = + (1 - cachedShare) * rate.inputCostPerToken + cachedShare * rate.cacheReadCostPerToken; const usd = (input - cached) * rate.inputCostPerToken + cached * rate.cacheReadCostPerToken + (usage.outputTokens ?? 0) * rate.outputCostPerToken + - (other?.inputTokens ?? 0) * rate.inputCostPerToken + + (other?.inputTokens ?? 0) * otherInputRate + (other?.outputTokens ?? 0) * rate.outputCostPerToken; const at = turn.startedAt ?? turn.completedAt; const createdAt = at === null ? (turn.tokenUsage?.updatedAt ?? null) : DateTime.formatIso(at); @@ -219,7 +223,11 @@ export function describeSpendStop( const usd = (value: number) => `$${value.toFixed(2)}`; return evaluation.stopReason === "ceiling" ? `This thread has spent about ${usd(evaluation.sessionUsd)}, past its ${usd(settings.sessionCeilingUsd)} session ceiling. Raise sessionSpendGuard.sessionCeilingUsd to continue.` - : `This thread has spent about ${usd(evaluation.idleUsd)} with no linked pull request or file-changing turn, past the ${usd(settings.idleStopUsd)} idle limit. Link a pull request or change files to continue.`; + : `This thread has spent about ${usd(evaluation.idleUsd)} ${ + evaluation.idleSince === null + ? "with no linked pull request or file-changing turn" + : "since its last linked pull request or file-changing turn" + }, past the ${usd(settings.idleStopUsd)} idle limit. Link a pull request or change files to continue.`; } export interface LaunchCheckInput { @@ -240,6 +248,28 @@ export function refusesAutomatedTurn( return mode === "enforce" && !INTERACTIVE_SOURCES.has(creationSource); } +const MAX_ORIGIN_CHAIN = 50; + +export function originCreationSource(input: { + readonly run: Pick; + readonly runs: ReadonlyArray< + Pick + >; + readonly messages: ReadonlyArray< + Pick + >; +}): OrchestrationV2ConversationMessage["creationSource"] | undefined { + let current = input.run; + for (let depth = 0; depth < MAX_ORIGIN_CHAIN; depth += 1) { + const sourceRunId = current.restartContinuationOfRunId; + if (sourceRunId === undefined) break; + const source = input.runs.find((candidate) => candidate.id === sourceRunId); + if (source === undefined) break; + current = source; + } + return input.messages.find((message) => message.id === current.userMessageId)?.creationSource; +} + export function checkLaunch(input: LaunchCheckInput): "untitled" | null { if (!refusesAutomatedTurn(input.mode, input.creationSource)) return null; const untitled = input.title.trim() === "" || input.title.trim() === "New thread"; diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts index baa4703410748..edf3e89a6daa2 100644 --- a/packages/contracts/src/settings.test.ts +++ b/packages/contracts/src/settings.test.ts @@ -411,9 +411,9 @@ describe("ServerSettings.sourceControlWritingStyle", () => { }); describe("session spend guard", () => { - it("enforces the idle and session ceilings by default", () => { + it("only flags idle and session spend by default", () => { expect(decodeServerSettings({}).sessionSpendGuard).toMatchObject({ - mode: "enforce", + mode: "flag", idleFlagUsd: 25, idleStopUsd: 50, sessionCeilingUsd: 200, @@ -427,8 +427,8 @@ describe("session spend guard", () => { }); it("patches one field and rejects a non-positive amount", () => { - expect(decodeServerSettingsPatch({ sessionSpendGuard: { mode: "flag" } })).toEqual({ - sessionSpendGuard: { mode: "flag" }, + expect(decodeServerSettingsPatch({ sessionSpendGuard: { mode: "enforce" } })).toEqual({ + sessionSpendGuard: { mode: "enforce" }, }); expect(() => decodeServerSettings({ sessionSpendGuard: { idleStopUsd: 0 } })).toThrow(); expect(() => diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 8e08976ff6b7a..678013efa299d 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -732,7 +732,7 @@ export type SessionSpendGuardMode = typeof SessionSpendGuardMode.Type; const SpendGuardUsd = Schema.Number.check(Schema.isFinite(), Schema.isGreaterThan(0)); export const SessionSpendGuardSettings = Schema.Struct({ - mode: SessionSpendGuardMode.pipe(Schema.withDecodingDefault(Effect.succeed("enforce" as const))), + mode: SessionSpendGuardMode.pipe(Schema.withDecodingDefault(Effect.succeed("flag" as const))), idleFlagUsd: SpendGuardUsd.pipe(Schema.withDecodingDefault(Effect.succeed(25))), idleStopUsd: SpendGuardUsd.pipe(Schema.withDecodingDefault(Effect.succeed(50))), sessionCeilingUsd: SpendGuardUsd.pipe(Schema.withDecodingDefault(Effect.succeed(200))), From c3e79318e9cf23e721a440da88c8e645446261a5 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:47:04 +0000 Subject: [PATCH 2/3] fix(web): server-linked threads show why they cannot open and can be marked unread A thread listed only through a server link (omarcy-desktop on the laptop) has no connection in this device's catalog. Opening it left the route waiting on a shell that never loads, so the pane stayed blank and the route also started thread loads against an environment the device cannot reach. Mark unread looked the thread up among catalog shells only, found nothing, and silently did nothing. The route now shows which host owns the thread and links to connection settings, and skips the unlisted-thread load for such environments. Mark unread falls back to the sidebar's linked shell so the local unread marker is set. Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/components/ThreadRouteView.tsx | 39 +++++++++++- apps/web/src/hooks/useThreadActions.ts | 3 +- apps/web/src/state/linkedSidebar.test.ts | 69 +++++++++++++++++++++ apps/web/src/state/linkedSidebar.ts | 20 +++++- 4 files changed, 126 insertions(+), 5 deletions(-) create mode 100644 apps/web/src/state/linkedSidebar.test.ts diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index a7b7da0a6b53b..37b5aa0c84c9c 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -4,7 +4,7 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitie import { visibilityParentKey } from "@t3tools/client-runtime/state/threads"; import type { ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; -import { Navigate, useNavigate } from "@tanstack/react-router"; +import { Link, Navigate, useNavigate } from "@tanstack/react-router"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; @@ -18,6 +18,7 @@ import { useQuietThreadShell, } from "../state/entities"; import { appAtomRegistry } from "../rpc/atomRegistry"; +import { readLinkedSidebarThreadShell, useLinkedOnlyEnvironment } from "../state/linkedSidebar"; import { useEnvironmentShellStatus } from "../state/shell"; import { environmentThreadShells, threadFamilies, useEnvironmentThread } from "../state/threads"; import { @@ -45,6 +46,27 @@ function useOpenThreadFamily(threadRef: ScopedThreadRef | null, missing: boolean }, [mountedKey]); } +function LinkedOnlyThreadNotice({ hostLabel, title }: { hostLabel: string; title: string | null }) { + return ( +
+

{title ?? "Thread"}

+

+ This thread lives on {hostLabel}, which this device sees through a server link but is not + connected to. Add {hostLabel} as a connection to open it here. +

+ + Open connection settings + +
+ ); +} + /** * Unkeyed so navigating between server threads reuses one ChatView. Rendered by the `_chat` * layout, since an element only survives a route swap when the same parent renders it. Draft @@ -67,6 +89,7 @@ export function ThreadRouteView({ draftId === null ? null : store.getPromotedDraftRedirect(draftId), ); const serverThreadRef = target.kind === "server" ? target.threadRef : null; + const linkedOnlyEnvironment = useLinkedOnlyEnvironment(serverThreadRef?.environmentId ?? null); const serverThreadShell = useQuietThreadShell(serverThreadRef); const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null); const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null); @@ -101,7 +124,10 @@ export function ThreadRouteView({ // decides whether it exists. Read only then: once listed, ChatView keeps // this stream open and its updates need not re-render the route. const unlistedThreadRef = - target.kind === "server" && serverThreadShell === null && draftThread === null + target.kind === "server" && + serverThreadShell === null && + draftThread === null && + linkedOnlyEnvironment === null ? target.threadRef : null; const unlistedThreadDetail = useEnvironmentThread( @@ -156,7 +182,14 @@ export function ThreadRouteView({ let view: React.ReactNode = null; let redirect: React.ReactNode = null; - if (target.kind === "draft") { + if (target.kind === "server" && linkedOnlyEnvironment !== null) { + view = ( + + ); + } else if (target.kind === "draft") { if ( draftSession && hiddenKeys.has( diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 3ce663e759dcf..d1b6389ffe8e5 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -48,6 +48,7 @@ import { readThreadShell, readThreadShells, } from "../state/entities"; +import { readLinkedSidebarThreadShell } from "../state/linkedSidebar"; import { useUiStateStore } from "../uiStateStore"; import { useDiffPanelStore } from "../diffPanelStore"; import { usePreviewMiniPlayerStore } from "../previewMiniPlayerStore"; @@ -228,7 +229,7 @@ function useMarkThreadUnread() { }); return; } - const thread = readThreadShell(target); + const thread = readThreadShell(target) ?? readLinkedSidebarThreadShell(target); markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt); }; } diff --git a/apps/web/src/state/linkedSidebar.test.ts b/apps/web/src/state/linkedSidebar.test.ts new file mode 100644 index 0000000000000..2743fe7959914 --- /dev/null +++ b/apps/web/src/state/linkedSidebar.test.ts @@ -0,0 +1,69 @@ +import { + EnvironmentId, + makeThreadInbox, + ProjectId, + ProviderInstanceId, + RunId, + ThreadId, + type LinkedSidebarResult, + type LinkedSidebarThread, +} from "@t3tools/contracts"; +import { afterEach, describe, expect, it } from "vite-plus/test"; + +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { linkedSidebarByHostAtom, readLinkedSidebarThreadShell } from "./linkedSidebar"; + +const laptop = EnvironmentId.make("primary-mac-laptop"); +const omarcy = EnvironmentId.make("omarcy-desktop"); +const threadId = ThreadId.make("mcp:7757a75b-0495-468c-a4ae-318012336419"); + +const linkedThread = { + inbox: makeThreadInbox({ actor: { kind: "human", id: "jeff" } }), + threadId, + projectId: ProjectId.make("project-dns"), + title: "Fleet naming + local DNS", + createdBy: "user", + creationSource: "mcp", + status: "idle", + latestRunId: RunId.make("run-1"), + providerInstanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + runtimeMode: "full-access", + interactionMode: "default", + settled: false, + settledAt: null, + snoozed: false, + snoozedUntil: null, + parentThreadId: null, + relationshipToParent: null, + itemCount: 4, + createdAt: "2026-11-19T12:00:00.000Z", + updatedAt: "2026-11-20T04:00:00.000Z", +} satisfies LinkedSidebarThread; + +const hostResult = { + environments: [ + { environmentId: omarcy, label: "omarcy-desktop", projects: [], threads: [linkedThread] }, + ], +} satisfies LinkedSidebarResult; + +afterEach(() => { + appAtomRegistry.set(linkedSidebarByHostAtom, new Map()); +}); + +describe("readLinkedSidebarThreadShell", () => { + it("finds a thread that only a server link lists, with a completion time to rewind", () => { + appAtomRegistry.set(linkedSidebarByHostAtom, new Map([[laptop, hostResult]])); + const shell = readLinkedSidebarThreadShell({ environmentId: omarcy, threadId }); + expect(shell?.title).toBe("Fleet naming + local DNS"); + expect(shell?.latestRun?.completedAt).toBe("2026-11-20T04:00:00.000Z"); + }); + + it("returns null for a thread no link lists", () => { + appAtomRegistry.set(linkedSidebarByHostAtom, new Map([[laptop, hostResult]])); + expect( + readLinkedSidebarThreadShell({ environmentId: omarcy, threadId: ThreadId.make("other") }), + ).toBeNull(); + expect(readLinkedSidebarThreadShell({ environmentId: laptop, threadId })).toBeNull(); + }); +}); diff --git a/apps/web/src/state/linkedSidebar.ts b/apps/web/src/state/linkedSidebar.ts index b71b290a39b9f..f7711b5611ba3 100644 --- a/apps/web/src/state/linkedSidebar.ts +++ b/apps/web/src/state/linkedSidebar.ts @@ -3,11 +3,12 @@ import type { EnvironmentProject, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; -import type { EnvironmentId, LinkedSidebarResult } from "@t3tools/contracts"; +import type { EnvironmentId, LinkedSidebarResult, ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; +import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentSummaries } from "./presentation"; import { environmentProjects } from "./projects"; import { environmentThreadShells } from "./threads"; @@ -105,6 +106,23 @@ export const sidebarThreadShellsAtom = Atom.make((get) => { : next; }).pipe(Atom.withLabel("linked-sidebar:threads")); +export function readLinkedSidebarThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | null { + return ( + appAtomRegistry + .get(linkedSidebarSupplementAtom) + .threads.find( + (thread) => thread.environmentId === ref.environmentId && thread.id === ref.threadId, + ) ?? null + ); +} + +export function useLinkedOnlyEnvironment(environmentId: EnvironmentId | null) { + const identities = useAtomValue(linkedSidebarSupplementAtom).identities; + return environmentId === null + ? null + : (identities.find((identity) => identity.environmentId === environmentId) ?? null); +} + export function useSidebarEnvironmentIdentities() { return useAtomValue(sidebarEnvironmentIdentitiesAtom); } From 3b8ea709fd68b1b72ce05cda1c37c1646142de55 Mon Sep 17 00:00:00 2001 From: nullStack65 <112618179+nullStack65@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:12:11 +0000 Subject: [PATCH 3/3] fix: spend guard origin walk also follows usage limit continuations Review finding: a founder's turn that hit a usage limit and was then continued by a restart was still read as automated, because the walk only followed restart continuation links. The walk now follows either link, and the restart-continuation test asserts that no refusal was recorded. Co-Authored-By: Claude Sonnet 5.5 --- .../ProviderTurnStartService.test.ts | 2 +- .../src/orchestration-v2/SessionSpendGuard.test.ts | 7 +++++++ .../server/src/orchestration-v2/SessionSpendGuard.ts | 12 +++++++++--- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 173ea07b8a0b2..e9a76796dcce6 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -487,7 +487,7 @@ effectIt.effect("lets a restart continuation of a founder's own turn through at providerTurns: [{ startedAt: "2099-01-01T00:00:01.000Z", inputTokens: 1 }], }); yield* Effect.exit(harness.start); - expect(harness.refusal()?.title).not.toBe("Turn refused by the session spend guard"); + expect(harness.refusal()).toBeUndefined(); }), ); diff --git a/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts b/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts index 77848e2c71cf3..4690b45648876 100644 --- a/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts +++ b/apps/server/src/orchestration-v2/SessionSpendGuard.test.ts @@ -393,6 +393,8 @@ describe("originCreationSource", () => { { id: "r4", userMessageId: "m-mcp" }, { id: "r5", userMessageId: "m-server", restartContinuationOfRunId: "r4" }, { id: "r6", userMessageId: "m-server", restartContinuationOfRunId: "missing" }, + { id: "r7", userMessageId: "m-server", usageLimitContinuationOfRunId: "r1" }, + { id: "r8", userMessageId: "m-server", restartContinuationOfRunId: "r7" }, ] as never; const origin = (id: string) => originCreationSource({ @@ -407,6 +409,11 @@ describe("originCreationSource", () => { expect(origin("r3")).toBe("web"); }); + it("follows usage limit continuations and mixed chains", () => { + expect(origin("r7")).toBe("web"); + expect(origin("r8")).toBe("web"); + }); + it("keeps an automated origin automated", () => { expect(origin("r5")).toBe("mcp"); }); diff --git a/apps/server/src/orchestration-v2/SessionSpendGuard.ts b/apps/server/src/orchestration-v2/SessionSpendGuard.ts index d86e7c069e3c0..ebd32450e4b5d 100644 --- a/apps/server/src/orchestration-v2/SessionSpendGuard.ts +++ b/apps/server/src/orchestration-v2/SessionSpendGuard.ts @@ -251,9 +251,15 @@ export function refusesAutomatedTurn( const MAX_ORIGIN_CHAIN = 50; export function originCreationSource(input: { - readonly run: Pick; + readonly run: Pick< + OrchestrationV2Run, + "userMessageId" | "restartContinuationOfRunId" | "usageLimitContinuationOfRunId" + >; readonly runs: ReadonlyArray< - Pick + Pick< + OrchestrationV2Run, + "id" | "userMessageId" | "restartContinuationOfRunId" | "usageLimitContinuationOfRunId" + > >; readonly messages: ReadonlyArray< Pick @@ -261,7 +267,7 @@ export function originCreationSource(input: { }): OrchestrationV2ConversationMessage["creationSource"] | undefined { let current = input.run; for (let depth = 0; depth < MAX_ORIGIN_CHAIN; depth += 1) { - const sourceRunId = current.restartContinuationOfRunId; + const sourceRunId = current.restartContinuationOfRunId ?? current.usageLimitContinuationOfRunId; if (sourceRunId === undefined) break; const source = input.runs.find((candidate) => candidate.id === sourceRunId); if (source === undefined) break;