Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Sign-in: a message an AI's sign-out stopped runs again once that AI is signed in, and its notice says so
laijsg1a8e42cacf6a8
diff --git a/packages/phone-protocol/src/runtime-events.ts b/packages/phone-protocol/src/runtime-events.tsindex 625c6b782c..ccfde4896f 100644--- a/packages/phone-protocol/src/runtime-events.ts+++ b/packages/phone-protocol/src/runtime-events.ts@@ -62,6 +62,9 @@ export type RuntimeEvent = RuntimeEventBase &type: "turn.completed";ok: boolean;stopReason?: string | null;+ /** With stopReason "auth_required": the driver proves the prompt never reached the model, so sending it+ * again repeats nothing. */+ unsent?: true;cost?: number | null;denials?: string[];/** THIS turn's token total, as the provider reports it at the end: thediff --git a/server/chat-notices.ts b/server/chat-notices.tsindex ea7ed5a380..c57c157628 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -128,6 +128,7 @@ export const CHAT_NOTICE = {"chat.notice.engineSignedOut": "{name} is signed out.","chat.notice.failoverSignedInAgain": "{engine} is signed in again, so this conversation is back on {engine}.","chat.notice.failoverSignedOut": "{from} is signed out, so {to} took over.",+ "chat.notice.signedInAgain": "{engine} is signed in again.","chat.notice.backupCardWaiting": "switched to {name}. Your request waits on a card above and continues on {name} once you act on it.","chat.notice.backupRequestUnderWay": "switched to {name}. Your request is still under way here and continues on {name}.","chat.notice.backupConversationBusy": "switched to {name}. This conversation is working, so your message was not sent again.",diff --git a/server/drivers/acp/acp.test.ts b/server/drivers/acp/acp.test.tsindex db90a45553..779ce36d76 100644--- a/server/drivers/acp/acp.test.ts+++ b/server/drivers/acp/acp.test.ts@@ -2550,7 +2550,7 @@ describe("ACP turns (fake CLI)", () => {await instance.adapter.sendTurn({ threadId: "t-auth-required", text: "go" });const done = await recorder.until((e) => e.type === "turn.completed");- expect(done).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(done, "refused at session/new: the prompt never went out").toMatchObject({ ok: false, stopReason: "auth_required", unsent: true });expect(recorder.events.find((e) => e.type === "runtime.error")).toMatchObject({ setup: true });});@@ -3092,6 +3092,7 @@ describe("ACP turns (fake CLI)", () => {setup: true,})]);expect(completed).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(completed, "refused after the prompt went out").not.toHaveProperty("unsent");});it("names any other ACP engine out of credits the same way", async () => {diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex 9fc44e07ba..3920d2ae3c 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -511,7 +511,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>active.delete(threadId); if (current.state.stopped) endBackground(threadId, session);const end = endTurn(current, ok, stopReason, support.displayName);if (end.error) emit({ ...base(threadId, current.turnId), type: "runtime.error", ...end.error });- emit({ ...base(threadId, current.turnId), type: "turn.completed", ok: end.ok, stopReason: end.stopReason, cost: null });+ emit({ ...base(threadId, current.turnId), type: "turn.completed", ok: end.ok, stopReason: end.stopReason, cost: null, ...(end.stopReason === "auth_required" && !current.state.promptSent ? { unsent: true as const } : {}) });if (session.child.exitCode === null && !session.closing && !session.dead) {armIdle(threadId);recycleWhenIdle(session.host);@@ -889,7 +889,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>if (!authenticated) {emit({ ...base(threadId, turnId), type: "turn.started" });emit({ ...base(threadId, turnId), type: "runtime.error", message: support.loginNote, setup: true });- emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "auth_required", cost: null });+ emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "auth_required", cost: null, unsent: true });return { turnId };}}diff --git a/server/drivers/antigravity-native-signin.test.ts b/server/drivers/antigravity-native-signin.test.tsindex 5d14240b8e..3f925c0c8e 100644--- a/server/drivers/antigravity-native-signin.test.ts+++ b/server/drivers/antigravity-native-signin.test.ts@@ -96,7 +96,7 @@ describe.skipIf(WINDOWS)("signing in to the native Antigravity CLI", () => {expect(await instance.snapshot()).toMatchObject({ authenticated: false });const after = await turn(instance, "native-loop-again", fixture.directory);expect(after.events).toContainEqual(expect.objectContaining({ type: "runtime.error", message: expect.stringContaining(LOGIN_NOTE), setup: true }));- expect(after.done).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(after.done).toMatchObject({ ok: false, stopReason: "auth_required", unsent: true });expect(fixture.methods()).not.toContain("authenticate");}, 120_000);diff --git a/server/drivers/claude-auth-recovery.ts b/server/drivers/claude-auth-recovery.tsindex 01132c0d43..e03af8d898 100644--- a/server/drivers/claude-auth-recovery.ts+++ b/server/drivers/claude-auth-recovery.ts@@ -7,7 +7,9 @@ type Frame = {message?: { model?: unknown; content?: unknown };};type Refusal = { text: string; kind: "auth" | "limit"; said?: string; resetsAt?: number; scope?: "engine" | "model" | "credits" };-type Pending = { refusal?: Refusal; refused?: boolean; buffered: RuntimeEvent[]; settle: (error?: Error) => void };+/** One turn's frames, read in order: a refusal before any model activity, and whether the error result ending it cost nothing. */+export interface RefusalRead { refusal?: Refusal; refused?: boolean; active?: boolean }+type Pending = RefusalRead & { buffered: RuntimeEvent[]; settle: (error?: Error) => void };/** Claude's saved sign-in ran out and could not refresh, in the CLI's own words ("OAuth session expired"). */export const claudeOAuthExpired = (text: string): boolean => /\boauth\b(?!.{0,40}\bnot\b).{0,40}\b(?:expired|revoked)\b/i.test(text);@@ -38,6 +40,18 @@ const preamble = (frame: Frame) =>const refusedStop = { auth: "auth_required", limit: "quota" } as const;+export function readRefusalFrame(read: RefusalRead, frame: Frame, priorCost?: number | null): void {+ if (read.active || preamble(frame)) return;+ const refusal = syntheticRefusal(frame);+ if (refusal) read.refusal = refusal;+ else if (read.refusal && frame.type === "result" && frame.is_error === true &&+ (frame.total_cost_usd === undefined || frame.total_cost_usd === 0 || frame.total_cost_usd === priorCost)) read.refused = true;+ else read.active = true;+}++/** The CLI refused the turn as signed out before the model saw any of it. */+export const refusedSignedOut = (read: RefusalRead): boolean => read.refused === true && read.refusal?.kind === "auth" && read.active !== true;+/** Holds a recoverable turn's ACK and events until its first model activity, so a signed-out or usage-limit refusal* rejects it once its process has stopped. */export function claudeAuthRecovery(@@ -55,12 +69,9 @@ export function claudeAuthRecovery(return {frame(threadId: string, frame: Frame, priorCost?: number | null) {const held = pending.get(threadId);- if (!held || preamble(frame)) return;- const refusal = syntheticRefusal(frame);- if (refusal) held.refusal = refusal;- else if (held.refusal && frame.type === "result" && frame.is_error === true &&- (frame.total_cost_usd === undefined || frame.total_cost_usd === 0 || frame.total_cost_usd === priorCost)) held.refused = true;- else accept(threadId, held);+ if (!held) return;+ readRefusalFrame(held, frame, priorCost);+ if (held.active) accept(threadId, held);},emit(event: RuntimeEvent) {const held = pending.get(event.threadId);diff --git a/server/drivers/claude-turn-result.ts b/server/drivers/claude-turn-result.tsnew file mode 100644index 0000000000..732a1ab668--- /dev/null+++ b/server/drivers/claude-turn-result.ts@@ -0,0 +1,32 @@+/** One native `result` frame. A steer sent after the turn's last model call runs as the CLI's next+ * native turn, so one logical turn can span several. */+export interface NativeTurnResult {+ ok: boolean;+ stopReason: string | null;+ cost: number | null;+ usage?: { input: number; output: number; cachedInput?: number };+ unsent?: true;+}++/** Merges native turns into one logical turn. Cost takes the latest figure: total_cost_usd is+ * "cumulative across turns in streaming-input sessions … read the latest result rather than+ * summing" (2.1.282). */+export function sumNativeTurnResults(earlier: NativeTurnResult | null, latest: NativeTurnResult): NativeTurnResult {+ if (!earlier) return latest;+ const usage = earlier.usage && latest.usage+ ? {+ input: earlier.usage.input + latest.usage.input,+ output: earlier.usage.output + latest.usage.output,+ ...(earlier.usage.cachedInput !== undefined || latest.usage.cachedInput !== undefined+ ? { cachedInput: (earlier.usage.cachedInput ?? 0) + (latest.usage.cachedInput ?? 0) }+ : {}),+ }+ : latest.usage ?? earlier.usage;+ return {+ ok: earlier.ok && latest.ok,+ stopReason: latest.stopReason ?? earlier.stopReason,+ cost: latest.cost ?? earlier.cost,+ ...(usage ? { usage } : {}),+ ...(earlier.unsent && latest.unsent ? { unsent: true as const } : {}),+ };+}diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex 8ec9a874f7..a9fd457a70 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -27,11 +27,11 @@ import {claudeCostSnapshot,restoredCostBase,STEERED_CONTINUATION_GRACE_MS,- sumNativeTurnResults,turnCostFromRunningTotal,type ClaudeConfig,} from "./claude.ts";import { spawnContractDiff } from "./claude-spawn-contract.ts";+import { sumNativeTurnResults } from "./claude-turn-result.ts";import { TEAM_TOOLS_FAILED } from "./team-tools.ts";import { claudeLimitMessage } from "./claude-limits.ts";import { flushNativeLog } from "./native.ts";@@ -720,7 +720,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {expect(failure).toMatchObject({ message: "Not logged in \u00b7 Please run /login", setup: true });expect(recorder.events.some((e: any) => e.type === "item.completed" && e.itemType === "assistant_text")).toBe(false);expect(recorder.events.some((e: any) => e.type === "content.delta")).toBe(false);- expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: false, stopReason: "auth_required" });+ expect(recorder.events.at(-1), "refused before the model saw it").toMatchObject({ type: "turn.completed", ok: false, stopReason: "auth_required", unsent: true });const pid = dumpedPid(dump);await expect.poll(() => {try { process.kill(pid, 0); return false; } catch { return true; }@@ -730,7 +730,9 @@ describe("ClaudeDriver turns (fake CLI)", () => {it("reads an error result saying the OAuth session expired as a sign-out", async () => {await create("oauth-expired-result");await instance.adapter.sendTurn({ threadId: "t-oauth", text: "hi" });- expect(await recorder.until((e) => e.type === "turn.completed")).toMatchObject({ ok: false, stopReason: "auth_required" });+ const done = await recorder.until((e) => e.type === "turn.completed");+ expect(done).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(done, "an error result alone does not prove the model never saw the turn").not.toHaveProperty("unsent");expect(recorder.events.find((e: any) => e.type === "runtime.error")).toMatchObject({ message: "OAuth session expired. Please sign in again.", setup: true });});@@ -747,8 +749,9 @@ describe("ClaudeDriver turns (fake CLI)", () => {it("keeps a sign-out after model activity as an ordinary failed turn", async () => {await create("not-logged-in", { FAKE_CLAUDE_AUTH_AFTER_WORK: "1" });await expect(instance.adapter.sendTurn({ threadId: "t-auth-work", text: "hi", startupRecovery: true })).resolves.toHaveProperty("turnId");- expect(await recorder.until(event => event.type === "turn.completed"))- .toMatchObject({ ok: false, stopReason: "auth_required" });+ const done = await recorder.until(event => event.type === "turn.completed");+ expect(done).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(done, "the model had already worked on it").not.toHaveProperty("unsent");expect(recorder.events.find(event => event.type === "runtime.error")).toMatchObject({ message: "Not logged in · Please run /login", setup: true });});diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 0179be3d14..2b6b42da48 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -16,7 +16,7 @@ import { claudeAuthStatus } from "./claude-auth-status.ts";import { projectMcpServers } from "./claude-project-mcp.ts";import { botSettingsFor, folderSettingsEnv, withBotSettings } from "./claude-bot-settings.ts"; import { claudeHookSettings } from "./claude-hooks.ts";import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";-import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";+import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired, readRefusalFrame, refusedSignedOut, type RefusalRead } from "./claude-auth-recovery.ts"; import { sumNativeTurnResults, type NativeTurnResult } from "./claude-turn-result.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";import { claudeOwnMcpOverHttp, withLoopbackNoProxy } from "./own-mcp-http.ts"; import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { shellOff } from "./shell-off.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";import { claudeElicitations } from "./claude-elicitation.ts"; import { claudePrestartTools, type ClaudePrestartTools } from "./claude-prestart.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts"; import { claudeContextUsage, liveContextBreakdown, writeControlFrame } from "./claude-context-usage.ts";@@ -361,37 +361,6 @@ function askSummary(ask: Ask): string {return askInputSummary(ask.input) ?? ask.tool ?? "tool";}-/** One native `result` frame. A steer sent after the turn's last model call runs as the CLI's next- * native turn, so one logical turn can span several. */-export interface NativeTurnResult {- ok: boolean;- stopReason: string | null;- cost: number | null;- usage?: { input: number; output: number; cachedInput?: number };-}--/** Merges native turns into one logical turn. Cost takes the latest figure: total_cost_usd is- * "cumulative across turns in streaming-input sessions … read the latest result rather than- * summing" (2.1.282). */-export function sumNativeTurnResults(earlier: NativeTurnResult | null, latest: NativeTurnResult): NativeTurnResult {- if (!earlier) return latest;- const usage = earlier.usage && latest.usage- ? {- input: earlier.usage.input + latest.usage.input,- output: earlier.usage.output + latest.usage.output,- ...(earlier.usage.cachedInput !== undefined || latest.usage.cachedInput !== undefined- ? { cachedInput: (earlier.usage.cachedInput ?? 0) + (latest.usage.cachedInput ?? 0) }- : {}),- }- : latest.usage ?? earlier.usage;- return {- ok: earlier.ok && latest.ok,- stopReason: latest.stopReason ?? earlier.stopReason,- cost: latest.cost ?? earlier.cost,- ...(usage ? { usage } : {}),- };-}-/** How long after a `result` the CLI may announce, with `init`, the native turn for a steer sent* after the last model call (about 60 ms on 2.1.282). */export const STEERED_CONTINUATION_GRACE_MS = 2_000;@@ -795,6 +764,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {* never took the prompt */awaitingInit?: boolean;authFailed?: boolean;+ refusalRead?: RefusalRead;updateRequired?: boolean;limit?: ClaudeLimit | null;limitReached?: boolean;@@ -1335,6 +1305,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {stopReason: string | null,total: number | null = null,usage?: { input: number; output: number; cachedInput?: number },+ unsent?: true,) => {const t = session.turn;if (!t || t.settled) return;@@ -1360,10 +1331,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {else if (session.teamToolsFailed) closeSession(threadId, "team tools did not connect");const cost = turnCostFromRunningTotal(total, session.costTotal ?? null);if (total !== null) session.costTotal = total;- emit({ ...base(threadId, t.turnId), type: "turn.completed", ok, stopReason, cost, ...(usage ? { usage } : {}) });+ emit({ ...base(threadId, t.turnId), type: "turn.completed", ok, stopReason, cost, ...(usage ? { usage } : {}), ...(unsent ? { unsent } : {}) });if (session.child.exitCode === null && !session.closing) armIdle(threadId);};- const settleResult = (result: NativeTurnResult) => settle(result.ok, result.stopReason, result.cost, result.usage);+ const settleResult = (result: NativeTurnResult) => settle(result.ok, result.stopReason, result.cost, result.usage, result.unsent);const currentTurnId = () => session.turn?.turnId ?? turnId;const unconfirmedStopWarning = () => { if (session.unconfirmedStopWarned) return; session.unconfirmedStopWarned = true; emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: "Claude could not be confirmed stopped; its helper processes may still be running." }); };session.releaseInterrupted = () => { if (session.turn?.stopRequested) { unconfirmedStopWarning(); settle(false, "interrupted"); } };@@ -1396,6 +1367,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {}if (session.context.frame(o) || session.tools?.frame(o) || session.spare) return;authRecovery.frame(threadId, o, session.costTotal);+ if (session.turn) readRefusalFrame(session.turn.refusalRead ??= {}, o, session.costTotal);// A replayed stdin message carries its images again: keep their bytes out of the log.appendNative(threadId, { dir: "in", source: "claude.sdk.message", msg: o?.type === "user" && o.isReplay === true && o.message ? diagnosticClaudeUserMessage(o) : o });if (session.elicit.frame(o)) return;@@ -1573,6 +1545,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {? o.terminal_reason ?? (typeof o.subtype === "string" && o.subtype !== "success" ? o.subtype : null) ?? o.stop_reason ?? null: o.stop_reason ?? o.terminal_reason ?? null,cost: o.total_cost_usd ?? null,+ ...(session.turn?.authFailed && session.turn.refusalRead && refusedSignedOut(session.turn.refusalRead) ? { unsent: true as const } : {}),...(o.usage? {usage: {diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex be5fa343d2..5eb83c1284 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -4278,7 +4278,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)const { done, errors } = await runTurn("t-no-login");expect(errors).toEqual([expect.objectContaining({ message: codexNotSignedIn(), setup: true })]);expect(codexNotSignedIn().includes("Sign-ins don't copy over when you move to My Cloud.")).toBe(Boolean(role));- expect(done).toMatchObject({ ok: false, stopReason: "auth_required" });+ expect(done).toMatchObject({ ok: false, stopReason: "auth_required", unsent: true });expect(spawn).not.toHaveBeenCalled();});diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex b9d78ef647..8fca263836 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -410,7 +410,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {if (signedOut) {emit({ ...base(threadId, turnId), type: "turn.started" });emit({ ...base(threadId, turnId), type: "runtime.error", message: codexNotSignedIn(), setup: true });- emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "auth_required", cost: null });+ emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "auth_required", cost: null, unsent: true });return { turnId };}const retryScale = Number(process.env.FAKE_CODEX_RETRY_SCALE ?? "1");diff --git a/server/harness/registry.test.ts b/server/harness/registry.test.tsindex 23ead893fe..ffdce4b868 100644--- a/server/harness/registry.test.ts+++ b/server/harness/registry.test.ts@@ -231,6 +231,26 @@ describe("ProviderRegistry", () => {expect(heard, "signed in all along: nothing new to tell").toEqual(["a"]);});+ it("tells its listeners of a sign-in when a read between said nothing about the sign-in", async () => {+ let authenticated: boolean | undefined = false;+ const fake = makeFakeDriver({ get answer() { return { state: "available" as const, version: "1.0.0", ...(authenticated === undefined ? {} : { authenticated }) }; } });+ const registry = new ProviderRegistry([fake.driver]);+ await registry.load({ a: { driver: "fake" } });+ const heard: string[] = [];+ registry.onSignedIn((instanceId) => heard.push(instanceId));+ const read = async () => {+ registry.forgetSnapshots();+ await registry.describe();+ };+ await read();+ authenticated = undefined;+ await read();+ expect(heard).toEqual([]);+ authenticated = true;+ await read();+ expect(heard).toEqual(["a"]);+ });+it("describe() reports a snapshot() failure as unavailable rather than throwing", async () => {const fake = makeFakeDriver({ failSnapshot: "provider probe exploded" });const registry = new ProviderRegistry([fake.driver]);diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex a9e107a121..455ad601c1 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -147,6 +147,8 @@ export class ProviderRegistry {private snapshotGeneration = 0;private manifestWatched = false;private readonly signedInListeners = new Set<(instanceId: InstanceId) => void>();+ /** The last read that said plainly whether each engine is signed in: a read that does not say keeps it. */+ private readonly lastAuth = new Map<InstanceId, boolean>();/** Per instance object: settings that reload an engine make a new one, so its status is read afresh. */private readsOf = new WeakMap<ProviderInstance, { snapshot: ProviderSnapshot; at: number; generation: number }>();private driversByKind: Map<string, AnyProviderDriver>;@@ -635,7 +637,9 @@ export class ProviderRegistry {this.unread?.delete(instance.instanceId);this.saveStatus();if (!inconclusive) this.healWrongCli(instance.instanceId, snapshot);- if (before?.authenticated === false && snapshot.state === "available" && snapshot.authenticated === true) {+ const knew = this.lastAuth.get(instance.instanceId) ?? before?.authenticated;+ if (!inconclusive && snapshot.state === "available" && typeof snapshot.authenticated === "boolean") this.lastAuth.set(instance.instanceId, snapshot.authenticated);+ if (knew === false && snapshot.state === "available" && snapshot.authenticated === true) {for (const listener of this.signedInListeners) listener(instance.instanceId);}}diff --git a/server/host/quota-switch.ts b/server/host/quota-switch.tsindex 17cc7c7a9e..374026126b 100644--- a/server/host/quota-switch.ts+++ b/server/host/quota-switch.ts@@ -8,7 +8,7 @@ import type { BotRecord, Message } from "../store.ts";import type { UsageTrigger } from "../usage-ledger.ts";import { resolveYourComputerAsk } from "../your-computer-consent.ts";-export interface QuotaSwitchHostDeps extends Pick<QuotaSwitchDeps, "store" | "coordinator" | "turnStops" | "takeover"> {+export interface QuotaSwitchHostDeps extends Pick<QuotaSwitchDeps, "store" | "coordinator" | "turnStops" | "takeover" | "signedOutNotice"> {registry: Pick<ProviderRegistry, "instances" | "access">;hostedModels: ReturnType<typeof hostedModelPolicy>;providerConfigs(): InstanceConfigMap;@@ -41,6 +41,7 @@ export function createQuotaSwitchHost(deps: QuotaSwitchHostDeps) {busy: threadBusy,request: threadId => directRequestOwners.get(threadId),resend: (botId, threadId, message, replyTo, spoken) => startOrQueueDirectMessage(botId, threadId, message.text ?? "", replyTo, undefined, message.sender, undefined, spoken.via, spoken.callId, message.dataContext),+ signedOutNotice: deps.signedOutNotice,});/** Settles a card the harness raised itself (a use-your-computer ask or a quota-switch offer); undefined for any other card. */diff --git a/server/host/sign-in-resume.test.ts b/server/host/sign-in-resume.test.tsnew file mode 100644index 0000000000..45459a5bba--- /dev/null+++ b/server/host/sign-in-resume.test.ts@@ -0,0 +1,424 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { ModelSelection } from "../../shared/wire.ts";+import type { Message } from "../store.ts";+import { createSignInResume, RECHECK_MS, RECHECKS_UNANSWERED, RESUME_WINDOW_MS, SAME_SIGN_IN_MS, type SignInResumeDeps, type SignInWait } from "./sign-in-resume.ts";++const claude: ModelSelection = { instanceId: "claude", model: "sonnet" };+const scratch: string[] = [];+afterEach(() => { while (scratch.length) rmSync(scratch.pop()!, { recursive: true, force: true }); });++function world(options: { file?: string } = {}) {+ let clock = 1_000;+ const paths = new Map<string, Message[]>();+ const offBranch = new Map<string, Message[]>();+ const models = new Map<string, ModelSelection>();+ const busy = new Set<string>();+ let full = false;+ let signedIn = true;+ let probe: Promise<boolean> | null = null;+ const timers: Array<() => void> = [];+ const sent: Array<{ wait: SignInWait; message: Message }> = [];+ let nextId = 0;+ const row = (threadId: string, fields: Partial<Message>): Message => {+ const path = paths.get(threadId) ?? [];+ const message = { id: `m${nextId++}`, role: "bot", kind: "activity", at: clock, parentId: path.at(-1)?.id ?? null, ...fields } as Message;+ paths.set(threadId, [...path, message]);+ return message;+ };+ const deps: SignInResumeDeps = {+ ...(options.file ? { file: options.file } : {}),+ store: {+ activePath: (threadId: string) => paths.get(threadId) ?? [],+ messagesFor: (threadId: string) => [...(paths.get(threadId) ?? []), ...(offBranch.get(threadId) ?? [])],+ taskByThread: (_botId: string, threadId: string) => (paths.has(threadId) ? { threadId } : undefined),+ projectBotForTask: (_botId: string, threadId: string) => (paths.has(threadId) ? { modelSelection: models.get(threadId) ?? claude } : null),+ patchMessage: (threadId: string, id: string, patch: Partial<Message>) => {+ const path = paths.get(threadId)!;+ const at = path.findIndex((message) => message.id === id);+ path[at] = { ...path[at]!, ...patch };+ return path[at]!;+ },+ } as unknown as SignInResumeDeps["store"],+ signedInNow: async () => (probe ? await probe : signedIn) ? () => true : null,+ engineName: () => "Claude",+ busy: (_botId, threadId) => busy.has(threadId),+ atCapacity: () => full,+ retry: async (wait, message) => {+ sent.push({ wait, message });+ return row(wait.threadId, { role: "user", kind: "text", text: message.text });+ },+ now: () => clock,+ after: (_ms, run) => { timers.push(run); },+ log: () => {},+ };+ /** A conversation whose last message met the AI signed out: the failed row, its notice, the digest. */+ const stuck = (threadId: string, text = "Draft the plan") => {+ row(threadId, { role: "bot", kind: "text", text: "Hi, I'm Kai." });+ const asked = row(threadId, { role: "user", kind: "text", text });+ row(threadId, { tool: { name: "error: Not logged in · Please run /login", ok: false, setup: true } });+ const notice = row(threadId, { tool: { name: "notice: Claude is signed out on this computer.", ok: true, setup: true } });+ row(threadId, { kind: "digest", text: "turn failed" });+ const wait: SignInWait = { botId: "kai", threadId, messageId: asked.id, selection: claude, failedAt: clock };+ return { asked, notice, wait, noticed: { instanceId: "claude", threadId, messageId: notice.id, at: notice.at } };+ };+ return {+ deps, sent, paths, offBranch, models, busy, row, stuck, timers,+ tick: (ms: number) => { clock += ms; },+ set full(value: boolean) { full = value; },+ set signedIn(value: boolean) { signedIn = value; },+ hold: () => { let release!: (value: boolean) => void; probe = new Promise((resolve) => { release = resolve; }); return (value: boolean) => { probe = null; release(value); }; },+ noticeTool: (threadId: string, id: string) => paths.get(threadId)!.find((message) => message.id === id)!.tool,+ };+}++describe("createSignInResume", () => {+ it("sends each waiting message again once its AI is signed in, and says so on its notice", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai"), rosa = w.stuck("t-rosa", "Draft the budget");+ resume.waiting(kai.wait); resume.noticed(kai.noticed);+ resume.waiting({ ...rosa.wait, botId: "rosa" }); resume.noticed(rosa.noticed);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent.map(({ message }) => message.text)).toEqual(["Draft the plan", "Draft the budget"]);+ expect(w.noticeTool("t-kai", kai.notice.id)).toEqual({ name: "notice: Claude is signed in again.", nameCode: "chat.notice.signedInAgain", nameParams: { engine: "Claude" }, ok: true });+ await resume.signedIn("claude");+ expect(w.sent, "a second sign-in event has nothing left to send").toHaveLength(2);+ });++ it("does nothing while the AI itself does not say it is signed in, and acts on the next sign-in", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait); resume.noticed(kai.noticed);+ w.signedIn = false;+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ expect(w.noticeTool("t-kai", kai.notice.id)?.setup).toBe(true);+ w.signedIn = true;+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toHaveLength(1);+ });++ it.each([+ ["the conversation is working", (w: ReturnType<typeof world>) => { w.busy.add("t-kai"); }],+ ["the person wrote again", (w: ReturnType<typeof world>) => { w.row("t-kai", { role: "user", kind: "text", text: "never mind" }); }],+ ["the bot already answered", (w: ReturnType<typeof world>) => { w.row("t-kai", { role: "bot", kind: "text", text: "Here is the plan." }); }],+ ["the person started fresh", (w: ReturnType<typeof world>) => { w.row("t-kai", { kind: "compaction", compaction: { fresh: true } } as Partial<Message>); }],+ ["the conversation moved to another model of the same AI", (w: ReturnType<typeof world>) => { w.models.set("t-kai", { ...claude, model: "opus" }); }],+ ["the conversation moved to another AI", (w: ReturnType<typeof world>) => { w.models.set("t-kai", { instanceId: "codex", model: "gpt" }); }],+ ])("leaves the message alone when %s, and still says the AI is signed in again", async (_why, change) => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait); resume.noticed(kai.noticed);+ change(w);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ expect(w.noticeTool("t-kai", kai.notice.id)?.nameCode).toBe("chat.notice.signedInAgain");+ });++ it("never sends a spoken line again", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ w.paths.get("t-kai")!.find((message) => message.id === kai.asked.id)!.via = "call";+ resume.waiting(kai.wait);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ });++ it("a message sent again that meets a sign-out again waits for the next sign-in, not the one that sent it", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toHaveLength(1);+ w.tick(5);+ w.row("t-kai", { tool: { name: "error: Not logged in · Please run /login", ok: false, setup: true } });+ const resent = w.paths.get("t-kai")!.findLast((message) => message.role === "user")!;+ await resume.waiting({ ...kai.wait, messageId: resent.id, failedAt: 1_015 });+ w.tick(SAME_SIGN_IN_MS);+ await resume.signedIn("claude");+ expect(w.sent.map(({ message }) => message.id), "a sign-in after the second refusal takes it up").toEqual([kai.asked.id, resent.id]);+ });++ it("leaves a message the person sent again on another version meanwhile", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait);+ w.tick(5);+ w.offBranch.set("t-kai", [{ id: "retried", role: "user", kind: "text", text: "Draft the plan", at: 1_005, parentId: null } as Message]);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ });++ it("leaves a message whose conversation was started fresh on another version meanwhile", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait);+ w.offBranch.set("t-kai", [{ id: "fresh", role: "bot", kind: "compaction", compaction: { fresh: true }, at: 1_005, parentId: null } as Message]);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ });++ it.each([+ ["a reaction", (_w: ReturnType<typeof world>, asked: Message) => { asked.reaction = "👍"; }],+ ["a press on a widget", (w: ReturnType<typeof world>, asked: Message) => {+ const widget = w.paths.get("t-kai")!.find((message) => message.role === "bot" && message.kind === "text")!;+ widget.widget = { kind: "buttons" } as never;+ asked.replyToId = widget.id;+ }],+ ])("never sends %s again as plain words", async (_what, mark) => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ mark(w, w.paths.get("t-kai")!.find((message) => message.id === kai.asked.id)!);+ resume.waiting(kai.wait);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ });++ it("asks again for a notice alone, when the status read does not say signed in", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.noticed(kai.noticed);+ w.signedIn = false;+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.timers).toHaveLength(1);+ w.signedIn = true;+ w.timers.shift()!();+ await vi.waitFor(() => expect(w.noticeTool("t-kai", kai.notice.id)?.nameCode).toBe("chat.notice.signedInAgain"));+ });++ it("keeps one recheck for an AI however many sign-in events come", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ resume.waiting(w.stuck("t-kai").wait);+ w.signedIn = false;+ w.tick(10);+ await resume.signedIn("claude");+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.timers).toHaveLength(1);+ });++ it("never sends a line an app wrote", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ w.paths.get("t-kai")!.find((message) => message.id === kai.asked.id)!.fromApp = { title: "Planner" } as never;+ resume.waiting(kai.wait);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ });++ it("asks again a few times when the AI's status does not say it is signed in, then waits for the next sign-in", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ resume.waiting(w.stuck("t-kai").wait);+ w.signedIn = false;+ w.tick(10);+ await resume.signedIn("claude");+ let reads = 1;+ while (w.timers.length) {+ expect(w.timers).toHaveLength(1);+ w.timers.shift()!();+ reads += 1;+ await new Promise((resolve) => setImmediate(resolve));+ }+ expect(reads, "five reads in all, then it waits for a sign-in").toBe(RECHECKS_UNANSWERED);+ w.signedIn = true;+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toHaveLength(1);+ });++ it("answers a sign-in only with what was left before it: a sign-out met after it waits for the next one", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const release = w.hold();+ w.tick(10);+ const pass = resume.signedIn("claude");+ w.tick(10);+ const later = w.stuck("t-kai");+ resume.waiting(later.wait); resume.noticed(later.noticed);+ release(true);+ await pass;+ expect(w.sent).toEqual([]);+ expect(w.noticeTool("t-kai", later.notice.id)?.setup, "the new notice still offers Sign in").toBe(true);+ w.tick(SAME_SIGN_IN_MS);+ await resume.signedIn("claude");+ expect(w.sent).toHaveLength(1);+ });++ it("stops sending when the AI's instance is replaced partway through a pass, and reads the new one", async () => {+ const w = world();+ let current = true;+ const resume = createSignInResume({ ...w.deps, signedInNow: async () => () => current, retry: async (wait, message) => { w.sent.push({ wait, message }); current = false; } });+ resume.waiting(w.stuck("t-kai").wait);+ resume.waiting({ ...w.stuck("t-rosa", "Draft the budget").wait, botId: "rosa" });+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toHaveLength(1);+ expect(w.timers, "a new pass reads the instance now there").toHaveLength(1);+ current = true;+ w.timers.shift()!();+ await vi.waitFor(() => expect(w.sent.map(({ message }) => message.text)).toEqual(["Draft the plan", "Draft the budget"]));+ });++ it("takes a second sign-in event soon after the first for the same sign-in", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait);+ w.tick(10);+ await resume.signedIn("claude");+ w.tick(5);+ const resent = w.paths.get("t-kai")!.findLast((message) => message.role === "user")!;+ w.row("t-kai", { tool: { name: "error: Not logged in · Please run /login", ok: false, setup: true } });+ await resume.waiting({ ...kai.wait, messageId: resent.id, failedAt: 1_015 });+ w.tick(1_000);+ await resume.signedIn("claude");+ expect(w.sent, "the status read that sees the same sign-in sends nothing again").toHaveLength(1);+ w.tick(SAME_SIGN_IN_MS);+ await resume.signedIn("claude");+ expect(w.sent).toHaveLength(2);+ });++ it("leaves a refusal told in the same millisecond as a sign-in for the next sign-in", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ const pass = resume.signedIn("claude");+ resume.waiting(kai.wait);+ await pass;+ expect(w.sent).toEqual([]);+ });++ it("takes up a message the sign-in came before, once its turn has settled", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ w.tick(10);+ await resume.signedIn("claude");+ await resume.waiting(kai.wait);+ expect(w.sent).toHaveLength(1);+ });++ it("keeps the newer of two messages of one conversation, whichever is told last", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const first = w.stuck("t-kai", "first");+ w.tick(5);+ const second = w.stuck("t-kai", "second");+ resume.waiting(second.wait);+ resume.waiting(first.wait);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent.map(({ message }) => message.text)).toEqual(["second"]);+ expect(w.noticeTool("t-kai", first.notice.id)?.setup, "unrecorded notices are left as they are").toBe(true);+ });++ it("waits for room when its bot has none, and sends it once there is", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait);+ w.full = true;+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ expect(w.timers).toHaveLength(1);+ w.full = false;+ w.tick(RECHECK_MS);+ w.timers.shift()!();+ await vi.waitFor(() => expect(w.sent).toHaveLength(1));+ });++ it("forgets a message left longer than the resume window, but still rewrites its notice", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.waiting(kai.wait); resume.noticed(kai.noticed);+ w.tick(RESUME_WINDOW_MS + 1);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ expect(w.noticeTool("t-kai", kai.notice.id)?.nameCode).toBe("chat.notice.signedInAgain");+ });++ it("rewrites a notice on another version of the conversation too", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ resume.noticed(kai.noticed);+ const path = w.paths.get("t-kai")!;+ w.offBranch.set("t-kai", path.filter((message) => message.id === kai.notice.id));+ w.paths.set("t-kai", path.filter((message) => message.id !== kai.notice.id));+ w.deps.store.patchMessage = (threadId, _id, patch) => {+ const rows = w.offBranch.get(threadId)!;+ rows[0] = { ...rows[0]!, ...patch };+ return rows[0]!;+ };+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.offBranch.get("t-kai")![0]!.tool?.nameCode).toBe("chat.notice.signedInAgain");+ });++ it("checks less often while its bot stays full", async () => {+ const w = world();+ const delays: number[] = [];+ const resume = createSignInResume({ ...w.deps, after: (ms, run) => { delays.push(ms); w.timers.push(run); } });+ resume.waiting(w.stuck("t-kai").wait);+ w.full = true;+ w.tick(10);+ await resume.signedIn("claude");+ for (let round = 0; round < 3; round += 1) {+ w.timers.shift()!();+ await vi.waitFor(() => expect(delays).toHaveLength(round + 2));+ }+ expect(delays).toEqual([RECHECK_MS, RECHECK_MS * 2, RECHECK_MS * 4, RECHECK_MS * 8]);+ });++ it("never sends a line a bot relayed in the person's name", async () => {+ const w = world();+ const resume = createSignInResume(w.deps);+ const kai = w.stuck("t-kai");+ w.paths.get("t-kai")!.find((message) => message.id === kai.asked.id)!.relayed = true as never;+ resume.waiting(kai.wait);+ w.tick(10);+ await resume.signedIn("claude");+ expect(w.sent).toEqual([]);+ });++ it("after a restart, asks the AI once and sends what was left waiting", async () => {+ const directory = mkdtempSync(join(tmpdir(), "omb-sign-in-resume-"));+ scratch.push(directory);+ const file = join(directory, "sign-in-resume.json");+ const w = world({ file });+ const kai = w.stuck("t-kai");+ createSignInResume(w.deps).waiting(kai.wait);+ w.tick(10);+ const restarted = createSignInResume(w.deps);+ await restarted.resumeSaved();+ expect(w.sent.map(({ message }) => message.id)).toEqual([kai.asked.id]);+ });+});diff --git a/server/host/sign-in-resume.ts b/server/host/sign-in-resume.tsnew file mode 100644index 0000000000..eac6cc4da9--- /dev/null+++ b/server/host/sign-in-resume.ts@@ -0,0 +1,274 @@+// A pass sends nothing again and rewrites no notice until the AI's status, read afresh, says it is signed in, and it+// acts only on what was left before the sign-in it answers. Only refusals the driver proves never reached the model are+// kept, so sending one again repeats no work.+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { SIGNED_IN_AGAIN, signInNotice } from "../../shared/sign-in-notice.ts";+import { sameModelSelection } from "../../shared/thread-model.ts";+import type { ModelSelection } from "../../shared/wire.ts";+import { writeFileAtomic } from "../atomic.ts";+import { chatNotice } from "../chat-notices.ts";+import { isFreshStart } from "../fresh-start.ts";+import type { ProviderRegistry } from "../harness/registry.ts";+import type { Message, Store } from "../store.ts";+import { nothingRan } from "../turn-outcome.ts";+import type { UsageTrigger } from "../usage-ledger.ts";++export const RESUME_WINDOW_MS = 24 * 60 * 60_000;+const NOTICE_TTL_MS = 30 * 24 * 60 * 60_000;+export const RECHECK_MS = 15_000;+const RECHECK_MAX_MS = 5 * 60_000;+/** Sign-in events this close together are one sign-in: the app's own, then the status read that sees it. */+export const SAME_SIGN_IN_MS = 60_000;+/** Status reads that did not say signed in, in a row, before an AI's waiting messages wait for its next sign-in. */+export const RECHECKS_UNANSWERED = 5;++export interface SignInWait {+ botId: string;+ threadId: string;+ messageId: string;+ selection: ModelSelection;+ trigger?: UsageTrigger;+ failedAt: number;+}++export interface SignedOutNotice { instanceId: string; threadId: string; messageId: string; at: number }++interface Saved { waiting?: SignInWait[]; notices?: SignedOutNotice[] }++export interface SignInResumeDeps {+ file?: string;+ store: Pick<Store, "activePath" | "messagesFor" | "taskByThread" | "projectBotForTask" | "patchMessage">;+ /** The AI's status, read afresh: null unless it says it is signed in, else whether the instance read still stands. */+ signedInNow(instanceId: string): Promise<(() => boolean) | null>;+ engineName(instanceId: string): string;+ /** The conversation is working or has messages queued. */+ busy(botId: string, threadId: string): boolean;+ atCapacity(botId: string, threadId: string): boolean;+ /** Sends `message` again as its conversation's Retry does. */+ retry(wait: SignInWait, message: Message): Promise<unknown>;+ now?: () => number;+ after?: (ms: number, run: () => void) => void;+ log?: (line: string) => void;+}++/** What waits on a person's own message that `selection`'s sign-out stopped at `failedAt`, before the model saw it. */+export function signInWait(store: Pick<Store, "projectBotForTask">, botId: string, threadId: string, messageId: string | undefined, trigger: UsageTrigger | undefined, failedAt: number): SignInWait | null {+ const selection = store.projectBotForTask(botId, threadId)?.modelSelection;+ return messageId && selection ? { botId, threadId, messageId, selection, failedAt, ...(trigger ? { trigger } : {}) } : null;+}++export function createSignInResume(deps: SignInResumeDeps) {+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((line: string) => console.warn(line));+ const after = deps.after ?? ((ms: number, run: () => void) => { setTimeout(run, ms).unref?.(); });+ let waiting: SignInWait[] = [];+ let notices: SignedOutNotice[] = [];+ const sending = new Set<SignInWait>();+ const signedInAt = new Map<string, number>();+ const chains = new Map<string, Promise<void>>();+ const scheduled = new Map<string, Promise<void>>();+ const rechecks = new Map<string, { ms: number; armed: boolean; unanswered: number }>();++ const prune = (): void => {+ const at = now();+ waiting = waiting.filter((wait) => at - wait.failedAt < RESUME_WINDOW_MS);+ notices = notices.filter((notice) => at - notice.at < NOTICE_TTL_MS);+ };++ if (deps.file) {+ try {+ const saved = JSON.parse(readFileSync(deps.file, "utf8")) as Saved;+ waiting = Array.isArray(saved.waiting) ? saved.waiting : [];+ notices = Array.isArray(saved.notices) ? saved.notices : [];+ } catch {}+ prune();+ }++ const save = (): void => {+ if (!deps.file) return;+ try {+ writeFileAtomic(deps.file, JSON.stringify({ waiting, notices } satisfies Saved), { mode: 0o600 });+ } catch (error) {+ log(`sign-in resume: could not save: ${error instanceof Error ? error.message : String(error)}`);+ }+ };++ /** The message to send again, "park" while its bot has no room, or null when it no longer stands as it was left. */+ const resumable = (wait: SignInWait): Message | "park" | null => {+ const { store } = deps;+ if (!store.taskByThread(wait.botId, wait.threadId) || deps.busy(wait.botId, wait.threadId)) return null;+ const all = store.messagesFor(wait.threadId);+ if (all.some((row) => row.id !== wait.messageId && (row.role === "user" || isFreshStart(row)) && row.at >= wait.failedAt)) return null;+ const path = store.activePath(wait.threadId);+ const at = path.findIndex((message) => message.id === wait.messageId);+ const message = path[at];+ if (!message || message.role !== "user" || message.kind !== "text" || !message.text || message.peerAsk || message.relayed || message.via || message.fromApp || message.reaction) return null;+ const answered = message.replyToId ? all.find((row) => row.id === message.replyToId) : undefined;+ if (answered?.widget || answered?.app) return null;+ const since = path.slice(at + 1);+ if (since.some((row) => row.role === "user" || isFreshStart(row)) || !nothingRan(since, 0, undefined)) return null;+ if (!sameModelSelection(store.projectBotForTask(wait.botId, wait.threadId)?.modelSelection, wait.selection)) return null;+ return deps.atCapacity(wait.botId, wait.threadId) ? "park" : message;+ };++ const signedInAgainTool = (instanceId: string): NonNullable<Message["tool"]> => {+ const engine = deps.engineName(instanceId);+ return { name: `notice: ${chatNotice(SIGNED_IN_AGAIN, { engine })}`, nameCode: SIGNED_IN_AGAIN, nameParams: { engine }, ok: true };+ };++ const recheckState = (instanceId: string) => {+ const state = rechecks.get(instanceId) ?? { ms: RECHECK_MS, armed: false, unanswered: 0 };+ rechecks.set(instanceId, state);+ return state;+ };+ const resetRecheck = (instanceId: string): void => {+ const state = recheckState(instanceId);+ state.ms = RECHECK_MS;+ state.unanswered = 0;+ };++ /** Another pass after a wait that grows each time, while `instanceId` has rows it could not deal with yet. */+ const recheck = (instanceId: string, unanswered: boolean): void => {+ const state = recheckState(instanceId);+ state.unanswered = unanswered ? state.unanswered + 1 : 0;+ if (state.armed || state.unanswered >= RECHECKS_UNANSWERED) return;+ state.armed = true;+ after(state.ms, () => {+ state.armed = false;+ void pass(instanceId);+ });+ state.ms = Math.min(state.ms * 2, RECHECK_MAX_MS);+ };++ const run = async (instanceId: string): Promise<void> => {+ const signedInWhen = signedInAt.get(instanceId) ?? now();+ const mine = (row: { selection?: ModelSelection; instanceId?: string; failedAt?: number; at?: number }) =>+ (row.selection?.instanceId ?? row.instanceId) === instanceId && (row.failedAt ?? row.at ?? 0) < signedInWhen;+ const stands = await deps.signedInNow(instanceId).catch(() => null);+ if (!stands) {+ if (waiting.some(mine) || notices.some(mine)) recheck(instanceId, true);+ return;+ }+ prune();+ let parked = false;+ for (const wait of waiting.filter((one) => mine(one) && !sending.has(one))) {+ if (!stands()) break;+ const message = resumable(wait);+ if (message === "park") {+ parked = true;+ continue;+ }+ if (message) {+ sending.add(wait);+ try {+ await deps.retry(wait, message);+ } catch (error) {+ log(`sign-in resume: could not send ${wait.threadId}'s message again: ${error instanceof Error ? error.message : String(error)}`);+ } finally {+ sending.delete(wait);+ }+ }+ waiting = waiting.filter((other) => other !== wait);+ save();+ }+ if (!stands()) {+ save();+ recheck(instanceId, true);+ return;+ }+ for (const notice of notices.filter(mine)) {+ const row = deps.store.messagesFor(notice.threadId).find((message) => message.id === notice.messageId);+ if (row?.tool?.setup && signInNotice(row)) deps.store.patchMessage(notice.threadId, notice.messageId, { tool: signedInAgainTool(instanceId) });+ notices = notices.filter((other) => other !== notice);+ }+ save();+ if (parked) recheck(instanceId, false);+ else resetRecheck(instanceId);+ };++ /** One pass at a time for each AI; a pass asked for while another waits to start is that same pass. */+ const pass = (instanceId: string): Promise<void> => {+ const waitingToStart = scheduled.get(instanceId);+ if (waitingToStart) return waitingToStart;+ const next = (chains.get(instanceId) ?? Promise.resolve()).then(() => {+ scheduled.delete(instanceId);+ return run(instanceId);+ }).catch((error: unknown) => log(`sign-in resume: ${error instanceof Error ? error.message : String(error)}`));+ scheduled.set(instanceId, next);+ chains.set(instanceId, next);+ return next;+ };++ const signedInSince = (instanceId: string, at: number) => (signedInAt.get(instanceId) ?? -Infinity) > at;++ return {+ /** A person's own message its AI's sign-out stopped before the model saw it, once that turn has settled and no other AI+ * carried it on. */+ waiting(wait: SignInWait): Promise<void> | undefined {+ if (waiting.some((other) => other.botId === wait.botId && other.threadId === wait.threadId && other.failedAt > wait.failedAt)) return undefined;+ waiting = waiting.filter((other) => sending.has(other) || other.botId !== wait.botId || other.threadId !== wait.threadId).concat(wait);+ save();+ return signedInSince(wait.selection.instanceId, wait.failedAt) ? pass(wait.selection.instanceId) : undefined;+ },+ /** A signed-out notice row a conversation shows. */+ noticed(notice: SignedOutNotice): Promise<void> | undefined {+ notices.push(notice);+ save();+ return signedInSince(notice.instanceId, notice.at) ? pass(notice.instanceId) : undefined;+ },+ /** Something says this AI is signed in again: a status read, or a sign-in in the app. */+ signedIn(instanceId: string): Promise<void> {+ const last = signedInAt.get(instanceId);+ if (last === undefined || now() - last >= SAME_SIGN_IN_MS) signedInAt.set(instanceId, now());+ resetRecheck(instanceId);+ return pass(instanceId);+ },+ /** After a restart: each AI with a conversation still waiting or a notice still showing is asked once. */+ resumeSaved(): Promise<void> {+ const at = now();+ const engines = new Set([...waiting.map((wait) => wait.selection.instanceId), ...notices.map((notice) => notice.instanceId)]);+ for (const instanceId of engines) if (!signedInAt.has(instanceId)) signedInAt.set(instanceId, at);+ return Promise.all([...engines].map(pass)).then(() => undefined);+ },+ };+}++export type SignInResume = ReturnType<typeof createSignInResume>;++/** Both sign-in events, a status read that turns signed in and a sign-in in the app, clear the takeover's hold before a+ * pass, so the turn it sends again is not held at its start. */+export function createSignInResumeHost(deps: Omit<SignInResumeDeps, "file" | "signedInNow" | "retry"> & {+ dataDir: string;+ registry: Pick<ProviderRegistry, "forgetSnapshots" | "get" | "onSignedIn">;+ takeover: { signedIn(instanceId: string): void };+ startTurn(botId: string, text: string, opts: { threadId: string; editedMessageId: string; replyTo?: Message; dataContext?: Message["dataContext"]; trigger?: UsageTrigger; sender?: Message["sender"] }): Promise<unknown>;+ replyTarget(threadId: string, id: string): Message | undefined;+ startupRead: Promise<unknown> | null;+}) {+ const { registry } = deps;+ const resume = createSignInResume({+ ...deps,+ file: join(deps.dataDir, "sign-in-resume.json"),+ signedInNow: async (instanceId) => {+ registry.forgetSnapshots();+ const instance = registry.get(instanceId);+ const snapshot = await instance?.snapshot();+ const stands = () => Boolean(instance) && registry.get(instanceId) === instance;+ return stands() && snapshot?.state === "available" && snapshot.authenticated === true ? stands : null;+ },+ retry: (wait, message) => deps.startTurn(wait.botId, message.text ?? "", {+ threadId: wait.threadId, editedMessageId: message.id, dataContext: message.dataContext,+ ...(message.replyToId ? { replyTo: deps.replyTarget(wait.threadId, message.replyToId) } : {}),+ ...(wait.trigger ? { trigger: wait.trigger } : {}), ...(message.sender ? { sender: message.sender } : {}),+ }),+ });+ const signedIn = (instanceId: string): void => {+ deps.takeover.signedIn(instanceId);+ void resume.signedIn(instanceId);+ };+ registry.onSignedIn(signedIn);+ void Promise.resolve(deps.startupRead).then(() => resume.resumeSaved());+ return { ...resume, signedIn };+}diff --git a/server/index.ts b/server/index.tsindex 5f6b6ab84b..9b1a05ba25 100644--- a/server/index.ts+++ b/server/index.ts@@ -211,7 +211,7 @@ import {} from "./contracts.ts";import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";import { chosenBackups, recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts"; import { outOfProcesses } from "./process-shortage.ts";-import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts"; import { createRoomLimitTakeover } from "./host/room-limit-takeover.ts";+import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { createSignInResumeHost, signInWait } from "./host/sign-in-resume.ts"; import { ownRequest, quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts"; import { createRoomLimitTakeover } from "./host/room-limit-takeover.ts";import { decodeGeneratedImage } from "./generated-image.ts";import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";import {@@ -1351,7 +1351,7 @@ const attributeUsage = createUsageAttribution({ section: (botId) => store.bot(bo} usageCapGate.booked(row.botId);}-const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => limitTakeover.signedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, personMcp: () => teamConnections.personMcp(), botsPath: () => brokerPath(botBox), moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });+const providerAuthSessions = new ProviderAuthSessions({ signedIn: (instanceId) => signInResume.signedIn(instanceId) }); const mcpServersHost = createMcpServersHost({ dataDir: DATA_DIR, cfg: () => cfg, personMcp: () => teamConnections.personMcp(), botsPath: () => brokerPath(botBox), moveGrants: (bot, move) => moveSavedGrants(store, bot, move), persist: persistMcpServers, bots: () => store.bots, policy: (servers) => managedPolicy.filterMcp(servers), tell: (text, about) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), startsServers: (botId) => { const bot = store.bot(botId); return Boolean(bot && registry.get(bot.modelSelection.instanceId)?.adapter.capabilities.customMcp === true); }, boxed: () => botBox.enabled(), keys: mcpKeys, forgetSignIn: (name) => mcpOAuth.forget(name) });const mcpOAuth = new McpOAuthManager({file: join(DATA_DIR, "mcp-oauth.json"),isOwnerLive: (owner) => owner === "loopback" || sessions.isLive(owner) || isCardOwnerLive(store, owner),@@ -6659,7 +6659,7 @@ bus.subscribe((event: RuntimeEvent) => {const facts = { ...turnStops.read(event.threadId, event.turnId)?.flags, stopReason: directRequestOwners.get(event.threadId)?.stopped ? "cancelled" : event.stopReason };const held = facts.limit ?? (signedOutStop(facts.stopReason, failureDetail) ? "signed-out" as const : undefined); // a limit or a sign-out: one incident a stretch, the person told by its own noticeconst fileIncident = () => { if (broken && (!held || limitTakeover.firstIncident(broken.id, broken.modelSelection, held, facts.limitResetsAt))) reportIncident({ kind: "failed", bot: broken, threadId: event.threadId, detail: failureDetail, facts, notified: Boolean(held) }); };- let directSettled = () => {}; const settledDirect = new Promise<void>((resolve) => { directSettled = resolve; }); if (failed && bot) void quotaSwitch.turnFailed(bot, event, internal, Promise.all([settledDirect, directTurnDispatchClaims.released(event.threadId)]));+ let directSettled = () => {}; const settledDirect = new Promise<void>((resolve) => { directSettled = resolve; }); const resumeWait = failed && bot && held === "signed-out" && event.unsent && ownRequest(directRequestOwners.get(event.threadId), event.turnId, internal) ? signInWait(store, bot.id, event.threadId, directRequestOwners.get(event.threadId)?.messageId, turnTriggers.get(event.threadId), Date.now()) : null; if (failed && bot) { const settledAll = Promise.all([settledDirect, directTurnDispatchClaims.released(event.threadId)]); const switched = quotaSwitch.turnFailed(bot, event, internal, settledAll); if (resumeWait) void Promise.all([settledAll, switched]).then(() => signInResume.waiting(resumeWait)); }else if (bot && event.ok) { quotaSwitch.turnSucceeded(bot, event.threadId); setupRecovery.succeeded(bot.id, event.threadId, { replayed, stopped }); }if (bot && event.ok && !stopped && completedTurnId && !routineRun && !coordinator.assignerOf(event.threadId)) askCards.ownQuestion(bot.id, event.threadId, completedTurnId);const lastReported = turnUsage.get(event.threadId);@@ -8460,7 +8460,7 @@ async function beginTurn(...hostedModels?.resetTask(current.modelSelection, checked.selection), rewound: true,});const rows = takeoverScope ? limitTakeover.carriedOn(current, threadId, current.modelSelection, checked.selection, { scope: takeoverScope, ...(e instanceof TurnUsageLimitRefusedError && e.resetsAt ? { resetsAt: e.resetsAt } : {}) })- : [{ name: `recovery: Automatic recovery: ${instance.displayName || instance.driverKind} could not start. Trying ${target.displayName || target.driverKind} · ${checked.selection.model} once in this thread.`, ok: true }]; for (const tool of rows) store.appendMessage(threadId, { role: "bot", kind: "activity", tool });+ : [{ name: `recovery: Automatic recovery: ${instance.displayName || instance.driverKind} could not start. Trying ${target.displayName || target.driverKind} · ${checked.selection.model} once in this thread.`, ok: true }]; for (const tool of rows) { const row = store.appendMessage(threadId, { role: "bot", kind: "activity", tool }); if (takeoverScope === "signed-out" && "setup" in tool && tool.setup) void signInResume.noticed({ instanceId: current.modelSelection.instanceId, threadId, messageId: row.id, at: row.at }); }if (opts?.coordination || opts?.onSettled) {directCoordinationSettlers.delete(dispatchClaimId);// The backup begins a new root for a goal step; this attempt's root ends here.@@ -8484,7 +8484,7 @@ async function beginTurn(tool: failedTurnTool(message, { ...(e instanceof PlaceUnavailableError ? { place: e.row } : e instanceof TurnUsageLimitRefusedError ? { limitResetsAt: e.resetsAt } : e instanceof TurnAuthenticationRefusedError ? { setup: true } : {}), text: startFailureText(e) }),});const personTurn = opts?.automationSource === undefined && !opts?.commsDepth && !opts?.cardContinuation, told = personTurn && takeoverScope === "signed-out" ? limitTakeover.tell(bot, bot.modelSelection, { scope: "signed-out" }) : null; // a limit or a sign-out is heard once a stretch, not once a turn- if (told) store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${told}`, ok: true, setup: true } });+ if (told) { const row = store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${told}`, ok: true, setup: true } }); void signInResume.noticed({ instanceId: bot.modelSelection.instanceId, threadId, messageId: row.id, at: row.at }); }if (personTurn && (!takeoverScope || limitTakeover.firstIncident(bot.id, bot.modelSelection, takeoverScope, e instanceof TurnUsageLimitRefusedError ? e.resetsAt : undefined))) {if (!told) notify(buildNotification("turn-failed", bot, threadId, redactSecretsInText(message), { avatarUrl: bot.avatarUrl }),@@ -8495,7 +8495,7 @@ async function beginTurn(directTurnBots.delete(threadId);opts?.onDispatchError?.(message);// A dispatch failure emits no turn.completed, so drain here or the queue behind this turn strands.- drainQueuedSends();+ drainQueuedSends(); const waits = e instanceof TurnAuthenticationRefusedError && personTurn && ownRequest(directRequestOwners.get(threadId), undefined, false) ? signInWait(store, bot.id, threadId, userMessage.id, opts?.trigger, Date.now()) : null; if (waits) void signInResume.waiting(waits);}})();return userMessage;@@ -8639,7 +8639,7 @@ async function stopBotForEmergencyApprovalDowngrade(botId: string): Promise<voidconst engineName = (engine: string) => engineLabel(engine, registry.get(engine) ?? undefined);const limitClock = new LimitResetClock({ file: join(DATA_DIR, "limit-holds.json"), accounts: () => planAccountsFromInstances(instanceConfigs(cfg)), onChange: () => routines?.retimeLimitResets(),- waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine, model) => limitClock.blockedUntil(engine, model), resetAt: (engine, model) => limitClock.resetAt(engine, model), meterOnly: (engine, model) => limitClock.meterOnly(engine, model), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), botsOn: (id) => store.bots.filter((bot) => !bot.hidden && bot.modelSelection.instanceId === id), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => chosenBackups(store.bot(botId), cfg.automaticRecovery), signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => { limitFailovers.record(failover); perf.noteFailover(failover.threadId, failover.why === "signed-out" ? "signed-out" : "limit"); } }); registry.onSignedIn((instanceId) => limitTakeover.signedIn(instanceId));+ waiting: () => Boolean(routines?.listRoutines().some((routine) => routine.enabled && routine.schedule.type === "limit_reset")) }); const limitTakeover = createLimitTakeover({ file: join(DATA_DIR, "limit-notices.json"), holdsFile: join(DATA_DIR, "limit-takeover-holds.json"), configs: () => instanceConfigs(cfg), context: selectionContext, blockedUntil: (engine, model) => limitClock.blockedUntil(engine, model), resetAt: (engine, model) => limitClock.resetAt(engine, model), meterOnly: (engine, model) => limitClock.meterOnly(engine, model), enabled: () => quotaSwitchEnabled(), where: CLOUD_HOME ? "on the Cloud" : "on this computer", signedOutNow: (id) => registry.knownSnapshot(id)?.authenticated === false, signedOutNoticed: () => registry.forgetSnapshots(), botsOn: (id) => store.bots.filter((bot) => !bot.hidden && bot.modelSelection.instanceId === id), engineName, engines: () => selectableInstances(registry.instances().map((engine) => ({ instanceId: engine.instanceId, driverKind: engine.driverKind, displayName: engine.displayName, enabled: engine.enabled, access: registry.access(engine.instanceId), models: engine.models, snapshot: registry.knownSnapshot(engine.instanceId) ?? { state: "unavailable" as const, reason: "not read yet" }, capabilities: engine.adapter.capabilities }))), chosen: (botId) => chosenBackups(store.bot(botId), cfg.automaticRecovery), signedOutChosen: (botId) => { const bot = store.bot(botId); return bot ? startupBackups(bot, cfg.automaticRecovery) : []; }, tell: (about, text) => notify(buildNoticeNotification(about, store.bot(about.id)?.threadId ?? "", text)), record: (failover) => { limitFailovers.record(failover); perf.noteFailover(failover.threadId, failover.why === "signed-out" ? "signed-out" : "limit"); } }); const signInResume = createSignInResumeHost({ dataDir: DATA_DIR, store, registry, takeover: limitTakeover, engineName, startTurn, replyTarget: resolveReplyTarget, startupRead: enginesRead, busy: (botId, threadId) => threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId), atCapacity: (botId, threadId) => botAtThreadCapacity(botId, threadId) });const limitFailovers = new LimitFailovers({ file: join(DATA_DIR, "limit-failovers.json"), blockedUntil: (engine, model) => limitClock.blockedUntil(engine, model), signedOut: (engine) => limitTakeover.stillSignedOut(engine), engineName,threadModel: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection ?? null,note: (threadId, line, text) => store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${line}`, ok: true, ...(text ? { nameCode: text.key, nameParams: text.params } : {}) } }),@@ -9443,7 +9443,7 @@ const approvalBus: YourComputerBus = { store, notify };// A bot resets a stuck cloud computer: its own, or as a Chief one of a bot it manages; Settings' reset, at once.const cloudComputerResets = createCloudComputerResetAsks({ language: threadLanguage, store, refusal: (from, target) => target.id !== from.id && !(chiefLevel(from) && canManage(from, target)) ? "You can ask to reset only your own cloud computer; a Chief of Staff can also ask for a bot in a department it manages." : noOwnCloudComputer(target, boat.boatConfigured(cfg), Boolean(inheritedTeamComputer(target))), computer: async (botId) => (await ownCloudComputer(cfg, botId, managedBoatOwners()))?.boxId ?? null, reset: async (botId, boxId) => { if (boatLifecycleBusyBots.has(botId)) throw Object.assign(new Error("this bot's cloud computer is being changed — wait for it to finish"), { status: 409 }); return resetBotCloudComputer(cfg, botId, managedBoatOwners(), (instance) => { if (computerProviderConfigTransitions.has("box")) throw Object.assign(new Error(providerTransitionMessage("box")), { status: 409 }); workspaceMaintenance.assertAvailable(); return claimManagedBoatMutation(instance); }, boxId); } });-const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ store, coordinator, registry, turnStops, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover, ownCards: (requestId, behavior) => computerAsks?.asks.answer(requestId, behavior) ?? false });+const { quotaSwitch, harnessCardOutcome } = createQuotaSwitchHost({ signedOutNotice: (threadId, instanceId, row) => void signInResume.noticed({ instanceId, threadId, messageId: row.id, at: row.at }), store, coordinator, registry, turnStops, hostedModels, providerConfigs, policyModelRefusal, checkedTaskModelSwitch, threadBusy, directRequestOwners, startOrQueueDirectMessage, takeover: limitTakeover, ownCards: (requestId, behavior) => computerAsks?.asks.answer(requestId, behavior) ?? false });// Consent cards live only in memory: settle every card still open on disk, or it locks the composer forever.{diff --git a/server/provider-auth-sessions.test.ts b/server/provider-auth-sessions.test.tsindex 475f52049d..de412e3a29 100644--- a/server/provider-auth-sessions.test.ts+++ b/server/provider-auth-sessions.test.ts@@ -40,6 +40,17 @@ describe("a finished sign-in", () => {await sessions.start({ ...instance, instanceId: "claude" }, "owner");expect(signedIn.mock.calls).toEqual([["codex"], ["codex"], ["claude"]]);});++ it("is told once for a flow its client reads again after it finished", async () => {+ const { instance, auth } = fixture();+ const signedIn = vi.fn();+ const sessions = new ProviderAuthSessions({ signedIn });+ await sessions.start(instance, "owner");+ instance.getAuthentication.mockResolvedValue({ ...auth, phase: "succeeded" } as never);+ await sessions.status("codex", "owner", "random-flow");+ await sessions.status("codex", "owner", "random-flow");+ expect(signedIn.mock.calls).toEqual([["codex"]]);+ });});describe("provider login ownership", () => {diff --git a/server/provider-auth-sessions.ts b/server/provider-auth-sessions.tsindex 56e15b0077..4cfe248d71 100644--- a/server/provider-auth-sessions.ts+++ b/server/provider-auth-sessions.ts@@ -11,6 +11,8 @@ type Flow = {starting: boolean;revoked: boolean;revision: number;+ /** Its success was told: a client reading the finished flow again is not another sign-in. */+ told?: true;};const failure = (message: string, status: number) => Object.assign(new Error(message), { status });@@ -79,7 +81,10 @@ export class ProviderAuthSessions {const status = await flow.instance.getAuthentication(flowId);if (flow.revoked || this.flows.get(instanceId) !== flow || flow.flowId !== flowId || flow.revision !== revision) throw failure("This sign-in session ended.", 404);if (status.phase !== "waiting" && status.phase !== "verifying") flow.expiresAt = 0;- if (status.phase === "succeeded") this.signedIn(instanceId);+ if (status.phase === "succeeded" && !flow.told) {+ flow.told = true;+ this.signedIn(instanceId);+ }return status;}diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.tsindex c3f1e5eae9..7ee2c15047 100644--- a/server/quota-switch.test.ts+++ b/server/quota-switch.test.ts@@ -508,9 +508,13 @@ describe("quota switch", () => {it("with no backup chosen moves nothing, and a second refusal adds no notice", async () => {backups = [];+ const shown: Array<{ threadId: string; instanceId: string; id: string }> = [];+ quota = createQuotaSwitch({ ...deps, signedOutNotice: (threadId, instanceId, row) => shown.push({ threadId, instanceId, id: row.id }) });await signedOut({ messageId: said("hi") });await signedOut({ messageId: said("hi again") });expect(notices()).toEqual([{ name: `notice: ${NOTICE}`, ok: true, setup: true }]);+ const notice = store.messagesFor(bot.threadId).find((message) => message.tool?.name === `notice: ${NOTICE}`)!;+ expect(shown, "the notice is handed on, to say the AI is signed in again later").toEqual([{ threadId: bot.threadId, instanceId: defaultSelection().instanceId, id: notice.id }]);expect(thread().modelSelection).toEqual(defaultSelection());expect(resend).not.toHaveBeenCalled();});diff --git a/server/quota-switch.ts b/server/quota-switch.tsindex fd9c4cc8cc..7a4b284179 100644--- a/server/quota-switch.ts+++ b/server/quota-switch.ts@@ -55,6 +55,8 @@ export interface QuotaSwitchDeps {resend: (botId: string, threadId: string, message: Message, replyTo: Message | undefined, spoken: { via?: "call"; callId?: string }) => Promise<unknown>;enabled?: () => boolean;after?: (ms: number, run: () => void) => { cancel(): void };+ /** The notice telling the person to sign `instanceId` in again, as this conversation shows it. */+ signedOutNotice?: (threadId: string, instanceId: string, row: Message) => void;}export interface QuotaSwitch {@@ -88,6 +90,11 @@ export function quotaSwitchEnabled(env: NodeJS.ProcessEnv = process.env): booleaconst nameOf = (engine: QuotaSwitchEngine): string => engine.displayName || engine.driverKind;+/** Only the person's own request: never a routine's, a webhook's, a relayed or a guest's. */+export function ownRequest(request: QuotaRequest | undefined, turnId: string | undefined, internal: boolean): request is QuotaRequest {+ return !internal && Boolean(request) && !request!.stopped && request!.origin?.kind === "user" && (!request!.turnId || !turnId || request!.turnId === turnId);+}+/** A line a bot delivered (peerAsk) is never resent in the person's name. */function resendable(store: Store, threadId: string, messageId: string | undefined): Message | undefined {if (!messageId) return undefined;@@ -110,9 +117,9 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {/** A second press while the engine is read is the same answer, never another. */const answering = new Map<string, Promise<QuotaAnswer>>();- const notice = (threadId: string, text: string, ok: boolean, setup = false, words?: ServerText): void => {+ const notice = (threadId: string, text: string, ok: boolean, setup = false, words?: ServerText): Message => {// `notice:` makes it a status row every client shows, never a folded tool step; `setup`: signing in fixes it.- store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ...(words ? { nameCode: words.key, nameParams: words.params } : {}), ok, ...(setup ? { setup: true } : {}) } });+ return store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `notice: ${text}`, ...(words ? { nameCode: words.key, nameParams: words.params } : {}), ok, ...(setup ? { setup: true } : {}) } });};const openCard = (threadId: string): Message | undefined => store.messagesFor(threadId)@@ -228,13 +235,14 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch {const resetsAt = scope === "signed-out" ? undefined : flags?.limitResetsAt;// A sign-out is told once, first and without a backup's name: what the person must do is sign in again.const told = scope === "signed-out" ? deps.takeover?.tell(thread, from, { scope }) : undefined;- if (told) notice(threadId, told, true, true);+ if (told) {+ const row = notice(threadId, told, true, true);+ deps.signedOutNotice?.(threadId, from.instanceId, row);+ }const tell = (backup?: ModelSelection) => {if (scope !== "signed-out") deps.takeover?.tell(thread, from, { ...(resetsAt ? { resetsAt } : {}), scope, ...(backup ? { backup } : {}) });};- // Only the person's own request: never a routine's, a webhook's, a relayed or a guest's.- const own = !internal && request && !request.stopped && request.origin?.kind === "user"- && (!request.turnId || !event.turnId || request.turnId === event.turnId);+ const own = ownRequest(request, event.turnId, internal);const relayed = request?.messageId && store.messagesFor(threadId).find((message) => message.id === request.messageId)?.peerAsk;if (!own || !request || relayed || !enabled() || openCard(threadId)) {deps.takeover?.passedOver(thread, from, scope, skipped);diff --git a/server/sign-in-resume-antigravity.e2e.test.ts b/server/sign-in-resume-antigravity.e2e.test.tsnew file mode 100644index 0000000000..d51b8563bf--- /dev/null+++ b/server/sign-in-resume-antigravity.e2e.test.ts@@ -0,0 +1,87 @@+import { spawn, type ChildProcess } from "node:child_process";+import { closeSync, mkdtempSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";++import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";+import { nativeFixture } from "./testing/antigravity-native-fixture.ts";+import { waitForExit } from "./testing/cleanup.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++type Row = { id: string; parentId?: string | null; role: string; kind: string; text?: string; tool?: { name: string; ok: boolean; setup?: boolean } };++it.skipIf(process.platform === "win32")("a bot on a signed-out Antigravity runs its stuck message again once Antigravity is signed in in the app", async () => {+ const cli = nativeFixture(mkdtempSync(join(tmpdir(), "omb-sign-in-resume-agy-")));+ const fixture = await launchVerificationServer({});+ const { url, dataDir, logPath } = fixture.info;+ let server: ChildProcess | undefined;+ const evidence: unknown[] = [];+ try {+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ const configPath = join(dataDir, "config.json");+ const config = JSON.parse(readFileSync(configPath, "utf8"));+ config.instances.antigravity = { driver: "antigravityAgent", config: { cli: cli.executable }, environment: { FAKE_AGY_LOG: cli.log } };+ config.automaticRecovery = { enabled: false };+ writeFileSync(configPath, JSON.stringify(config));+ const log = openSync(logPath, "a", 0o600);+ server = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env: verificationServerEnvironment({}, dataDir, Number(new URL(url).port)),+ stdio: ["ignore", log, log],+ });+ closeSync(log);++ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(60_000) });+ const result = await response.json() as any;+ expect(response.ok, `${method} ${path}: ${JSON.stringify(result)}`).toBe(true);+ return result;+ };+ const control = async (...args: string[]) => await runControlOmb([...args, "--url", url]) as any;+ const antigravity = async () => ((await api("GET", "/api/instances?fresh=1")).instances as any[]).find((instance) => instance.instanceId === "antigravity");+ const activePath = async (threadId: string) => {+ const { messages, activeLeafId } = await api("GET", `/api/threads/${threadId}/messages?limit=500`) as { messages: Row[]; activeLeafId?: string };+ const byId = new Map(messages.map((row) => [row.id, row]));+ const path: Row[] = [];+ for (let row = activeLeafId ? byId.get(activeLeafId) : messages.at(-1); row; row = row.parentId ? byId.get(row.parentId) : undefined) path.unshift(row);+ return path;+ };+ const prompts = () => cli.methods().filter((method) => method === "session/prompt").length;++ await expect.poll(async () => { try { return (await fetch(url + "/api/health")).ok; } catch { return false; } }, { timeout: 30_000 }).toBe(true);+ const { bots } = await api("GET", "/api/bots") as { bots: Array<{ id: string; chiefOfStaff?: boolean }> };+ const starter = bots.find((bot) => bot.chiefOfStaff);+ if (starter) await api("PATCH", `/api/bots/${starter.id}`, { chiefOfStaff: false });+ await expect.poll(async () => (await antigravity())?.snapshot.authenticated, { timeout: 60_000 }).toBe(false);+ const model = (await antigravity()).models.options[0].id as string;++ const { bot } = await control("new-bot", "--name", "Wren");+ await api("PATCH", `/api/bots/${bot.id}`, { modelSelection: { instanceId: "antigravity", model } });+ await control("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "继续吧");+ expect((await control("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "60")).status).toBe("failed");+ const stuck = await activePath(bot.activeTaskId);+ evidence.push({ stuck });+ expect(stuck.filter((row) => row.tool?.setup).map((row) => row.tool!.name)).toEqual([+ "error: Antigravity needs a Google account — choose Sign in with Google in engine setup",+ "notice: Google Gemini (Antigravity) is signed out on this computer. Sign in again in Settings → AI to keep using it. Until then Wren can't run: it has no backup.",+ ]);+ expect(prompts()).toBe(0);++ const flow = (await api("POST", "/api/instances/antigravity/auth/start", {})).auth;+ await api("POST", "/api/instances/antigravity/auth/complete", { flowId: flow.flowId, callbackUrl: "fixture-code" });+ await expect.poll(prompts, { timeout: 60_000 }).toBe(1);+ expect((await control("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "60")).status).toBe("settled");+ const now = await activePath(bot.activeTaskId);+ evidence.push({ now });+ expect(now.filter((row) => row.tool?.setup)).toEqual([]);+ expect(now.filter((row) => row.role === "user").map((row) => row.text)).toEqual(["继续吧"]);+ expect(now.filter((row) => row.role === "bot" && row.kind === "text").at(-1)).toMatchObject({ text: "fixture reply" });+ } finally {+ writeFileSync(`${logPath}.sign-in-resume-agy.json`, JSON.stringify(evidence, null, 2));+ await waitForExit(server, { signal: "SIGTERM" });+ await fixture.close();+ console.info(JSON.stringify({ logPath, evidence: `${logPath}.sign-in-resume-agy.json` }));+ }+}, hostTimeout(300_000));diff --git a/server/sign-in-resume.e2e.test.ts b/server/sign-in-resume.e2e.test.tsnew file mode 100644index 0000000000..133596db2b--- /dev/null+++ b/server/sign-in-resume.e2e.test.ts@@ -0,0 +1,128 @@+// The fake Claude CLI's sign-in is its own files (FAKE_CLAUDE_HOME_FILES, FAKE_CLAUDE_AUTH=file), written here as a+// terminal's `claude auth login` would.+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, it } from "vitest";++import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++type Row = { id: string; parentId?: string | null; role: string; kind: string; text?: string; tool?: { name: string; ok: boolean; setup?: boolean; nameCode?: string } };++async function withSignedOutClaude(check: (fixture: {+ api: (method: string, path: string, body?: unknown) => Promise<any>;+ control: (...args: string[]) => Promise<any>;+ /** How many prompts the fake CLI was given that carry `text`. */+ promptsWith: (text: string) => number;+ signIn: () => Promise<void>;+ /** The conversation as it reads now: its active branch, from the root to the active leaf. */+ activePath: (threadId: string) => Promise<Row[]>;+ all: (threadId: string) => Promise<Row[]>;+ evidence: unknown[];+}) => Promise<void>) {+ const scratch = mkdtempSync(join(tmpdir(), "omb-sign-in-resume-e2e-"));+ const promptsFile = join(scratch, "prompts.jsonl");+ const fixture = await launchVerificationServer({ ...process.env, FAKE_CLAUDE_HOME_FILES: "1", FAKE_CLAUDE_AUTH: "file", FAKE_CLAUDE_PROMPTS: promptsFile });+ const { url, dataDir } = fixture.info;+ const evidence: unknown[] = [];+ try {+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, { method, headers: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ const result = await response.json() as any;+ expect(response.ok, `${method} ${path}: ${JSON.stringify(result)}`).toBe(true);+ return result;+ };+ const page = async (threadId: string) => await api("GET", `/api/threads/${threadId}/messages?limit=500`) as { messages: Row[]; activeLeafId?: string | null };+ const signedIn = async () => ((await api("GET", "/api/instances?fresh=1")).instances as any[]).find((instance) => instance.instanceId === "claude")?.snapshot.authenticated;+ const claudeHome = join(dataDir, ".claude");++ await api("PUT", "/api/config", { automaticRecovery: { enabled: false } });+ const { bots } = await api("GET", "/api/bots") as { bots: Array<{ id: string; chiefOfStaff?: boolean }> };+ const starter = bots.find((bot) => bot.chiefOfStaff);+ if (starter) await api("PATCH", `/api/bots/${starter.id}`, { chiefOfStaff: false });+ await expect.poll(signedIn, { timeout: 20_000 }).toBe(false);++ await check({+ api, evidence,+ control: async (...args: string[]) => await runControlOmb([...args, "--url", url]) as any,+ promptsWith: (text) => (existsSync(promptsFile) ? readFileSync(promptsFile, "utf8").split("\n").filter(Boolean) : []).filter((line) => line.includes(text)).length,+ signIn: async () => {+ mkdirSync(claudeHome, { recursive: true });+ writeFileSync(join(claudeHome, ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "fixture-token-not-a-credential" } }));+ writeFileSync(join(claudeHome, "fake-auth.json"), JSON.stringify({ email: "[email protected]" }));+ await expect.poll(signedIn, { timeout: 20_000 }).toBe(true);+ },+ activePath: async (threadId) => {+ const { messages, activeLeafId } = await page(threadId);+ const byId = new Map(messages.map((row) => [row.id, row]));+ const path: Row[] = [];+ for (let row = activeLeafId ? byId.get(activeLeafId) : messages.at(-1); row; row = row.parentId ? byId.get(row.parentId) : undefined) path.unshift(row);+ return path;+ },+ all: async (threadId) => (await page(threadId)).messages,+ });+ } finally {+ writeFileSync(join(scratch, "evidence.json"), JSON.stringify(evidence, null, 2));+ console.info(JSON.stringify({ log: fixture.info.logPath, evidence: join(scratch, "evidence.json") }));+ await fixture.close();+ }+}++const setupRows = (rows: Row[]) => rows.filter((row) => row.tool?.setup);++it("signing in again runs each stuck conversation's message once more, and its sign-out rows leave the conversation", async () => {+ await withSignedOutClaude(async ({ control, promptsWith, signIn, activePath, all, evidence }) => {+ const kai = (await control("new-bot", "--name", "Kai")).bot;+ const rosa = (await control("new-bot", "--name", "Rosa")).bot;+ for (const bot of [kai, rosa]) {+ await control("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", `Draft the plan for ${bot.name}`);+ expect((await control("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30")).status).toBe("failed");+ const stuck = await activePath(bot.activeTaskId);+ evidence.push({ bot: bot.name, stuck });+ expect(setupRows(stuck).map((row) => row.tool!.name)).toEqual([+ "error: Not logged in · Please run /login",+ expect.stringMatching(/^notice: Verification fixture is signed out on this computer\. .*Until then .* can't run: they have no backup\.$/),+ ]);+ expect(promptsWith(`Draft the plan for ${bot.name}`)).toBe(1);+ }++ await signIn();++ for (const bot of [kai, rosa]) {+ await expect.poll(() => promptsWith(`Draft the plan for ${bot.name}`), { timeout: 30_000 }).toBe(2);+ expect((await control("wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30")).status).toBe("settled");+ const now = await activePath(bot.activeTaskId);+ evidence.push({ bot: bot.name, resumed: now });+ expect(setupRows(now), "no sign-out row on the conversation as it reads now").toEqual([]);+ expect(now.filter((row) => row.role === "user").map((row) => row.text)).toEqual([`Draft the plan for ${bot.name}`]);+ expect(now.some((row) => row.role === "bot" && row.kind === "text" && row.text && !row.text.startsWith("Hi, I'm"))).toBe(true);+ const history = await all(bot.activeTaskId);+ expect(setupRows(history).map((row) => row.tool!.name), "the failed try stays on its own version").toEqual(["error: Not logged in · Please run /login"]);+ expect(history.filter((row) => row.tool?.nameCode === "chat.notice.signedInAgain"), "and its notice says the AI is signed in again").toHaveLength(1);+ }+ });+}, hostTimeout(240_000));++it("a conversation moved to another model meanwhile is not run again, and its notice says the AI is signed in again", async () => {+ await withSignedOutClaude(async ({ api, control, promptsWith, signIn, activePath, evidence }) => {+ const kai = (await control("new-bot", "--name", "Kai")).bot;+ await control("send", "--bot", kai.id, "--task", kai.activeTaskId, "--text", "Draft the launch plan");+ expect((await control("wait", "--bot", kai.id, "--task", kai.activeTaskId, "--timeout", "30")).status).toBe("failed");+ const { instances } = await api("GET", "/api/instances") as { instances: any[] };+ const claude = instances.find((instance) => instance.instanceId === "claude");+ const other = claude.models.options.find((option: any) => option.id !== kai.modelSelection.model);+ expect(other, "the fixture's Claude offers a second model").toBeTruthy();+ await api("PATCH", `/api/bots/${kai.id}/tasks/${kai.activeTaskId}`, { modelSelection: { instanceId: "claude", model: other.id } });++ await signIn();+ await expect.poll(async () => (await activePath(kai.activeTaskId)).some((row) => row.tool?.nameCode === "chat.notice.signedInAgain"), { timeout: 30_000 }).toBe(true);+ const now = await activePath(kai.activeTaskId);+ evidence.push({ moved: now });+ expect(now.filter((row) => row.tool?.name.startsWith("notice:")).map((row) => row.tool)).toEqual([+ { name: "notice: Verification fixture is signed in again.", nameCode: "chat.notice.signedInAgain", nameParams: { engine: "Verification fixture" }, ok: true },+ ]);+ expect(setupRows(now).map((row) => row.tool!.name)).toEqual(["error: Not logged in · Please run /login"]);+ expect(promptsWith("Draft the launch plan")).toBe(1);+ });+}, hostTimeout(240_000));diff --git a/shared/sign-in-notice.ts b/shared/sign-in-notice.tsnew file mode 100644index 0000000000..f4d92059fe--- /dev/null+++ b/shared/sign-in-notice.ts@@ -0,0 +1,7 @@+export const SIGNED_IN_AGAIN = "chat.notice.signedInAgain";++/** A signed-out notice (signing in fixes it), or the same row once its AI is signed in again: Retry stays on the turn it+ * follows. */+export function signInNotice(row: { kind: string; tool?: { name: string; setup?: boolean; nameCode?: string } }): boolean {+ return row.kind === "activity" && Boolean(row.tool) && (row.tool!.nameCode === SIGNED_IN_AGAIN || (row.tool!.setup === true && row.tool!.name.startsWith("notice:")));+}diff --git a/src/lib/transcript-derivations.test.ts b/src/lib/transcript-derivations.test.tsindex a1b1280b3e..38dd51637a 100644--- a/src/lib/transcript-derivations.test.ts+++ b/src/lib/transcript-derivations.test.ts@@ -69,6 +69,19 @@ describe("transcriptLookups", () => {expect(transcriptLookups([digest], [digest]).retryableId).toBeUndefined();});+ it("keeps Retry on a turn its AI's sign-out stopped, past the notice about that sign-in", () => {+ const failed = msg("e", { kind: "activity", tool: { name: "error: Not logged in · Please run /login", ok: false, setup: true }, at: 40, parentId: "f" });+ const signedOut = msg("n", { kind: "activity", tool: { name: "notice: Claude is signed out on this computer.", ok: true, setup: true }, at: 41, parentId: "e" });+ const signedIn = msg("n", { kind: "activity", tool: { name: "notice: Claude is signed in again.", nameCode: "chat.notice.signedInAgain", nameParams: { engine: "Claude" }, ok: true }, at: 41, parentId: "e" });+ const turnDigest = msg("d2", { kind: "digest", text: "turn failed", at: 42, parentId: "n" });+ for (const notice of [signedOut, signedIn]) {+ const path = [root, q3, a3, follow, failed, notice, turnDigest];+ expect(transcriptLookups(path, path).retryableId).toBe("e");+ }+ const partlyRan = msg("p", { kind: "activity", tool: { name: "notice: switched to Codex. Part of your request had already run, so it was not sent again.", nameCode: "chat.notice.backupAlreadyRan", nameParams: { name: "Codex" }, ok: false }, at: 41, parentId: "e" });+ expect(transcriptLookups([root, follow, failed, partlyRan], [root, follow, failed, partlyRan]).retryableId).toBe("p");+ });+it("keeps Retry on the last conversational row when a live call's record follows it", () => {const record = msg("call", {kind: "call",diff --git a/src/lib/transcript-derivations.ts b/src/lib/transcript-derivations.tsindex 6faa3b9674..ba28b1949e 100644--- a/src/lib/transcript-derivations.ts+++ b/src/lib/transcript-derivations.ts@@ -1,8 +1,9 @@import type { Message } from "@/state/store";import { activeLocale, t } from "@/lib/i18n";-import { lastNonReceipt } from "@/lib/receipts";+import { isReceipt } from "@/lib/receipts";import { noticeText } from "@/lib/activity-text";import type { ServerTextParams } from "../../shared/server-text";+import { signInNotice } from "../../shared/sign-in-notice";export interface TranscriptLookups {editVersions(message: Message): readonly Message[] | undefined;@@ -23,7 +24,7 @@ export function transcriptLookups(all: readonly Message[], branch: readonly Messelse forks.set(parent, [message]);}for (const siblings of forks.values()) siblings.sort((a, b) => a.at - b.at);- const retryableId = lastNonReceipt(branch)?.id;+ const retryableId = branch.findLast((message) => !isReceipt(message) && !signInNotice(message))?.id;const lastCompaction = branch.findLast((message) => message.kind === "compaction");return {editVersions(message) {diff --git a/src/locales/en.json b/src/locales/en.jsonindex c86657d93e..1055f005c9 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10307,6 +10307,7 @@"serverError.wait.alreadyEnded": "This wait has already ended.","chat.notice.failoverSignedInAgain": "{engine} is signed in again, so this conversation is back on {engine}.","chat.notice.failoverSignedOut": "{from} is signed out, so {to} took over.",+ "chat.notice.signedInAgain": "{engine} is signed in again.","serverError.botDefaults.nameLength": "name must be at most 100 characters","serverError.botDefaults.sectionLength": "section must be at most 60 characters","serverError.botDefaults.invalid": "These bot settings are not valid.",