Skip to content

Commit 96f0ea6

Browse files
committed
feat(desktop): offer explicit recovery for ended remote thread sessions
Preserve provider refusal codes through the prompt store and offer tenant-scoped end, checkpoint recovery, and fresh-start actions. Ending sessions expose a recheck action; capability failures retain Retry and Dismiss. Legacy providers keep phrase-based error handling. Signed-off-by: Tee8z <[email protected]>
1 parent b88f22e commit 96f0ea6

11 files changed

Lines changed: 1077 additions & 2 deletions

‎desktop/src/features/messages/lib/remoteAgentSession.test.mjs‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { test } from "node:test";
33
import {
44
publishedChannelMessage,
55
publishedRemoteSession,
6+
remoteSessionOffersCheckpoint,
7+
remoteSessionRecoveryKind,
68
usesThreadSandbox,
79
} from "./remoteAgentSession.ts";
810

@@ -83,3 +85,94 @@ test("only an explicitly configured Kubernetes Sandbox uses thread launches", ()
8385
);
8486
assert.equal(usesThreadSandbox({ backend: { type: "local" } }), false);
8587
});
88+
89+
// Every lifecycle refusal the Kubernetes provider returns (sandbox.rs), plus
90+
// errors that must not offer recovery.
91+
const providerErrors = [
92+
[
93+
"Sandbox session ended (stopped); explicit recovery is required",
94+
"recover",
95+
true,
96+
],
97+
["Sandbox session ended; explicit recovery is required", "recover", true],
98+
[
99+
"Sandbox Pod was replaced; credentials remain bound to the original session, explicit recovery is required",
100+
"recover",
101+
true,
102+
],
103+
[
104+
"Sandbox is not an active managed session; explicit recovery is required",
105+
"recover",
106+
true,
107+
],
108+
[
109+
"Sandbox session is ending; recover it explicitly once it has ended",
110+
"ending",
111+
true,
112+
],
113+
[
114+
"this session has no verified checkpoint; start fresh instead",
115+
"recover",
116+
false,
117+
],
118+
[
119+
"no ended session exists for this thread to recover; start fresh instead",
120+
"recover",
121+
false,
122+
],
123+
[
124+
"recovery requires an ended session; this Sandbox is still active, so end it first",
125+
"end-first",
126+
true,
127+
],
128+
[
129+
"Sandbox launch configuration differs; end the session, then explicit recovery is required",
130+
"end-first",
131+
true,
132+
],
133+
[
134+
"Sandbox belongs to a different relay; use a new thread or explicit recovery",
135+
null,
136+
true,
137+
],
138+
[
139+
"agent already has a Pod; stop and recover it explicitly before using Sandbox",
140+
null,
141+
true,
142+
],
143+
["provider timed out after 600s", null, true],
144+
["", null, true],
145+
];
146+
147+
test("provider lifecycle errors map to the explicit action they ask for", () => {
148+
for (const [error, kind, offersCheckpoint] of providerErrors) {
149+
assert.equal(remoteSessionRecoveryKind(error), kind, error);
150+
assert.equal(
151+
remoteSessionRecoveryKind(error.toUpperCase()),
152+
kind,
153+
`case-insensitive: ${error}`,
154+
);
155+
assert.equal(remoteSessionOffersCheckpoint(error), offersCheckpoint, error);
156+
}
157+
});
158+
159+
test("provider codes override prose and survive Tauri error wrapping", () => {
160+
for (const [code, kind, checkpoint] of [
161+
["session_active", "end-first", true],
162+
["config_differs", "end-first", true],
163+
["session_ending", "ending", true],
164+
["session_ended", "recover", true],
165+
["no_checkpoint", "recover", false],
166+
["no_ended_session", "recover", false],
167+
["future_refusal", null, true],
168+
]) {
169+
const payload = { code, message: "session ended; start fresh instead" };
170+
for (const error of [
171+
payload,
172+
Object.assign(new Error(payload.message), { payload }),
173+
]) {
174+
assert.equal(remoteSessionRecoveryKind(error), kind, code);
175+
assert.equal(remoteSessionOffersCheckpoint(error), checkpoint, code);
176+
}
177+
}
178+
});

‎desktop/src/features/messages/lib/remoteAgentSession.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,81 @@ export function publishedRemoteSession(
3838
if (!/^[0-9a-f]{64}$/.test(threadRoot)) return undefined;
3939
return { channelId, threadRoot };
4040
}
41+
42+
/** The explicit action a thread-session error asks the user for. */
43+
export type RemoteSessionRecoveryKind = "recover" | "end-first" | "ending";
44+
45+
/** Preserve codes carried by both raw provider failures and Tauri errors. */
46+
export function remoteSessionErrorCode(error: unknown): string | undefined {
47+
if (typeof error !== "object" || error === null) return undefined;
48+
if ("payload" in error) return remoteSessionErrorCode(error.payload);
49+
return "code" in error && typeof error.code === "string"
50+
? error.code
51+
: undefined;
52+
}
53+
54+
function errorMessage(error: unknown): string {
55+
if (typeof error === "string") return error.toLowerCase();
56+
if (
57+
typeof error === "object" &&
58+
error !== null &&
59+
"message" in error &&
60+
typeof error.message === "string"
61+
)
62+
return error.message.toLowerCase();
63+
return "";
64+
}
65+
66+
/** Codes take precedence; phrase matching is only for older providers. */
67+
export function remoteSessionRecoveryKind(
68+
error: unknown,
69+
): RemoteSessionRecoveryKind | null {
70+
const code = remoteSessionErrorCode(error);
71+
if (code !== undefined) {
72+
switch (code) {
73+
case "session_active":
74+
case "config_differs":
75+
return "end-first";
76+
case "session_ending":
77+
return "ending";
78+
case "session_ended":
79+
case "pod_ended":
80+
case "pod_replaced":
81+
case "session_not_running":
82+
case "binding_expired":
83+
case "recovery_interrupted":
84+
case "no_checkpoint":
85+
case "no_ended_session":
86+
return "recover";
87+
default:
88+
return null;
89+
}
90+
}
91+
const message = errorMessage(error);
92+
if (message.includes("end it first") || message.includes("end the session"))
93+
return "end-first";
94+
if (
95+
message.includes("session is ending") ||
96+
message.includes("session is still ending")
97+
)
98+
return "ending";
99+
if (
100+
message.includes("explicit recovery is required") ||
101+
message.includes("recover it explicitly once it has ended") ||
102+
message.includes("session ended") ||
103+
message.includes("start fresh instead")
104+
)
105+
return "recover";
106+
return null;
107+
}
108+
109+
export function remoteSessionOffersCheckpoint(error: unknown): boolean {
110+
const code = remoteSessionErrorCode(error);
111+
if (code !== undefined)
112+
return code !== "no_checkpoint" && code !== "no_ended_session";
113+
const message = errorMessage(error);
114+
return !(
115+
message.includes("no verified checkpoint") ||
116+
message.includes("no ended session exists")
117+
);
118+
}
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import assert from "node:assert/strict";
2+
import { test } from "node:test";
3+
import {
4+
clearRemoteSessionRecoveryPrompt,
5+
getRemoteSessionRecoveryPrompts,
6+
MAX_REMOTE_SESSION_RECOVERY_PROMPTS,
7+
recordRemoteSessionRecoveryPrompt,
8+
remoteSessionRecoveryPromptsForThread,
9+
subscribeRemoteSessionRecoveryPrompts,
10+
withRemoteSessionRecoveryPrompt,
11+
} from "./remoteSessionRecoveryPrompts.ts";
12+
13+
const channelId = "f9ee507e-d03c-4570-baa6-02951c38e1cd";
14+
15+
function prompt(overrides = {}) {
16+
return {
17+
agentPubkey: "a".repeat(64),
18+
agentName: "Agent",
19+
session: { channelId, threadRoot: "b".repeat(64) },
20+
expectedRelayUrl: "wss://relay.example",
21+
expectedSignerPubkey: "c".repeat(64),
22+
error: "Sandbox session ended; explicit recovery is required",
23+
...overrides,
24+
};
25+
}
26+
27+
test("a newer failure for the same tenant, agent, and thread replaces the older one", () => {
28+
const first = prompt();
29+
const second = prompt({
30+
agentPubkey: "A".repeat(64),
31+
error: "Sandbox session is ending; recover it explicitly once it has ended",
32+
});
33+
const next = withRemoteSessionRecoveryPrompt(
34+
withRemoteSessionRecoveryPrompt([], first),
35+
second,
36+
);
37+
assert.deepEqual(next, [second]);
38+
39+
const otherTenant = prompt({ expectedSignerPubkey: "d".repeat(64) });
40+
assert.equal(withRemoteSessionRecoveryPrompt(next, otherTenant).length, 2);
41+
});
42+
43+
test("the prompt store stays bounded, keeping the newest failures", () => {
44+
let prompts = [];
45+
for (
46+
let index = 0;
47+
index <= MAX_REMOTE_SESSION_RECOVERY_PROMPTS;
48+
index += 1
49+
) {
50+
prompts = withRemoteSessionRecoveryPrompt(
51+
prompts,
52+
prompt({
53+
session: {
54+
channelId,
55+
threadRoot: index.toString(16).padStart(64, "0"),
56+
},
57+
}),
58+
);
59+
}
60+
assert.equal(prompts.length, MAX_REMOTE_SESSION_RECOVERY_PROMPTS);
61+
assert.equal(prompts[0].session.threadRoot, "1".padStart(64, "0"));
62+
});
63+
64+
test("a thread selects only its own prompts", () => {
65+
const here = prompt();
66+
const otherThread = prompt({
67+
session: { channelId, threadRoot: "e".repeat(64) },
68+
});
69+
const otherChannel = prompt({
70+
session: {
71+
channelId: "00000000-0000-4000-8000-000000000000",
72+
threadRoot: "b".repeat(64),
73+
},
74+
});
75+
assert.deepEqual(
76+
remoteSessionRecoveryPromptsForThread(
77+
[here, otherThread, otherChannel],
78+
here.session,
79+
),
80+
[here],
81+
);
82+
});
83+
84+
test("recording and clearing notify subscribers; clearing matches the start's scope", () => {
85+
let notifications = 0;
86+
const unsubscribe = subscribeRemoteSessionRecoveryPrompts(() => {
87+
notifications += 1;
88+
});
89+
const failed = prompt();
90+
recordRemoteSessionRecoveryPrompt(failed);
91+
assert.deepEqual(getRemoteSessionRecoveryPrompts(), [failed]);
92+
// A later successful start carries no error or name, only its scope.
93+
clearRemoteSessionRecoveryPrompt({
94+
agentPubkey: failed.agentPubkey.toUpperCase(),
95+
session: failed.session,
96+
expectedRelayUrl: ` ${failed.expectedRelayUrl} `,
97+
expectedSignerPubkey: failed.expectedSignerPubkey,
98+
});
99+
assert.deepEqual(getRemoteSessionRecoveryPrompts(), []);
100+
clearRemoteSessionRecoveryPrompt(failed);
101+
assert.equal(notifications, 2, "clearing an absent prompt is silent");
102+
unsubscribe();
103+
});
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import type { RemoteAgentSession } from "@/shared/api/remoteAgentSession";
2+
import { normalizePubkey } from "@/shared/lib/pubkey";
3+
4+
/**
5+
* A thread-session start that failed with a lifecycle error. The thread panel
6+
* offers the explicit recovery actions for it. Only the failure is kept: the
7+
* user's recovery choice is sent with one command and never stored.
8+
*/
9+
export type RemoteSessionRecoveryPrompt = {
10+
agentPubkey: string;
11+
agentName: string;
12+
session: RemoteAgentSession;
13+
/** Tenant scope of the failed start; the recovery command asserts it. */
14+
expectedRelayUrl: string;
15+
expectedSignerPubkey: string;
16+
error: string;
17+
code?: string;
18+
};
19+
20+
/** Bounds the store: one entry per failed (tenant, agent, thread). */
21+
export const MAX_REMOTE_SESSION_RECOVERY_PROMPTS = 32;
22+
23+
let prompts: readonly RemoteSessionRecoveryPrompt[] = [];
24+
const listeners = new Set<() => void>();
25+
26+
/** Identity of a prompt: the tenant, the agent, and the thread. */
27+
export function remoteSessionRecoveryPromptKey(
28+
prompt: Pick<
29+
RemoteSessionRecoveryPrompt,
30+
"agentPubkey" | "session" | "expectedRelayUrl" | "expectedSignerPubkey"
31+
>,
32+
): string {
33+
return [
34+
prompt.expectedRelayUrl.trim(),
35+
normalizePubkey(prompt.expectedSignerPubkey),
36+
normalizePubkey(prompt.agentPubkey),
37+
prompt.session.channelId,
38+
prompt.session.threadRoot,
39+
].join("\u0000");
40+
}
41+
42+
/** Pure update: replace any prompt with the same key, newest last, bounded. */
43+
export function withRemoteSessionRecoveryPrompt(
44+
current: readonly RemoteSessionRecoveryPrompt[],
45+
prompt: RemoteSessionRecoveryPrompt,
46+
): readonly RemoteSessionRecoveryPrompt[] {
47+
const key = remoteSessionRecoveryPromptKey(prompt);
48+
return [
49+
...current.filter(
50+
(existing) => remoteSessionRecoveryPromptKey(existing) !== key,
51+
),
52+
prompt,
53+
].slice(-MAX_REMOTE_SESSION_RECOVERY_PROMPTS);
54+
}
55+
56+
/** Pure selection: the prompts for one thread. */
57+
export function remoteSessionRecoveryPromptsForThread(
58+
current: readonly RemoteSessionRecoveryPrompt[],
59+
session: RemoteAgentSession,
60+
): RemoteSessionRecoveryPrompt[] {
61+
return current.filter(
62+
(prompt) =>
63+
prompt.session.channelId === session.channelId &&
64+
prompt.session.threadRoot === session.threadRoot,
65+
);
66+
}
67+
68+
function setPrompts(next: readonly RemoteSessionRecoveryPrompt[]): void {
69+
if (next === prompts) return;
70+
prompts = next;
71+
for (const listener of listeners) listener();
72+
}
73+
74+
/** Records a failed thread-session start so its thread can offer recovery. */
75+
export function recordRemoteSessionRecoveryPrompt(
76+
prompt: RemoteSessionRecoveryPrompt,
77+
): void {
78+
setPrompts(withRemoteSessionRecoveryPrompt(prompts, prompt));
79+
}
80+
81+
/** Drops a prompt after its session started, recovered, or was dismissed. */
82+
export function clearRemoteSessionRecoveryPrompt(
83+
prompt: Parameters<typeof remoteSessionRecoveryPromptKey>[0],
84+
): void {
85+
const key = remoteSessionRecoveryPromptKey(prompt);
86+
const next = prompts.filter(
87+
(existing) => remoteSessionRecoveryPromptKey(existing) !== key,
88+
);
89+
if (next.length !== prompts.length) setPrompts(next);
90+
}
91+
92+
export function subscribeRemoteSessionRecoveryPrompts(
93+
listener: () => void,
94+
): () => void {
95+
listeners.add(listener);
96+
return () => {
97+
listeners.delete(listener);
98+
};
99+
}
100+
101+
export function getRemoteSessionRecoveryPrompts(): readonly RemoteSessionRecoveryPrompt[] {
102+
return prompts;
103+
}

0 commit comments

Comments
 (0)