返回 DeepSeek-Reasonix
sessionComposerPersistence.ts
根目录 / desktop / frontend / src / lib / sessionComposerPersistence.ts
1 import { useEffect, useMemo, useSyncExternalStore } from "react";
2 import { app, sessionPurgeHandlers } from "./bridge";
3 import type { SessionRef } from "./sessionRef";
4 import type { PersistentComposerDraft, PersistentComposerTarget } from "./composerDraftTypes";
5 import type { SessionComposerState, SessionLifecycleResult } from "../generated/desktopContract.generated";
6 import { followupNotSubmitted } from "./pendingFollowup";
7 import { submissionOutcome, modelApplicationError, type ModelApplicationDetails } from "./modelApplication";
8
9 export const emptySessionInput = (): PersistentComposerDraft => ({ text: "", invocations: [], attachments: [], workspaceRefs: [], pastedBlocks: [], openPastedLabels: [], sessionRefs: [], selectedTextRefs: [] });
10 type Entry = { ref: SessionRef; state?: SessionComposerState; content: PersistentComposerDraft; generation: number; version: number; saved: number; users: number; touched: number;
11 retired?: boolean; retirement: Promise<void>; retire: () => void;
12 inputTasks: Set<Promise<unknown>>;
13 application?: ModelApplicationDetails; error?: string; taskError?: string; unreadable?: boolean; registering?: boolean; recovering?: Promise<void>; unsubmittedId?: string; settledId?: string; tasks: Set<Promise<unknown>>; loading?: Promise<void>; saving?: Promise<void>; timer?: ReturnType<typeof setTimeout> };
14 const entries = new Map<string, Entry>();
15 const tabs = new Map<string, string>();
16 const tabOwners = new Map<string, symbol>();
17
18 export function sendPersistedComposer<T>(tabId: string, display: string, submit: string, id: string, send: () => T | Promise<T>, expectedEdit?: number, sourceKey = tabs.get(tabId), kind = "turn") {
19 const entry = entries.get(sourceKey || "");
20 const owner = tabOwners.get(tabId);
21 const task = (async () => {
22 const complete = await beginPersistedComposerSubmission(tabId,id,JSON.stringify({kind,display,submit}),expectedEdit,sourceKey,owner);
23 try {
24 if (tabs.get(tabId) !== sourceKey || tabOwners.get(tabId) !== owner) throw new Error("reasonix_error:inbox_not_submitted");
25 const result = await send();
26 await complete?.("accepted");
27 return result;
28 } catch (error) {
29 const message=String(error);
30 const outcome = submissionOutcome(error);
31 const rejected = outcome ? outcome === "not_accepted" : followupNotSubmitted(error) || /^(?:Error:\s*)?submission not accepted(?:\n|$)/.test(message);
32 await complete?.(rejected ? "not_accepted" : "unknown");
33 throw error;
34 }
35 })().catch(async error => {
36 if (entry) await recoverInput(entry).catch(() => {});
37 throw error;
38 });
39 if (entry) { entry.tasks.add(task); void task.finally(()=>{entry.tasks.delete(task);prune();}).catch(()=>{}); }
40 return task;
41 }
42 const listeners = new Set<() => void>();
43 let serial = 0, revision = 0, exiting = false;
44 const keyFor = (ref: SessionRef) => `${ref.hostId}:${ref.sessionId}`;
45 const notify = () => { revision++; listeners.forEach(fn => fn()); };
46 const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
47 const snapshot = () => revision;
48 // Only successful purge receipts revoke draft ownership. A missing-session
49 // read/save error is not evidence that the user authorized discarding input.
50 export function reconcileSessionComposerPurge(method: string, args: unknown[], result: unknown) {
51 const refs = method === "PurgeCanonicalSession" ? [args[0] as SessionRef]
52 : (args[0] as { action: string }).action === "purge"
53 ? (result as SessionLifecycleResult).items.filter(item => item.committed).map(item => item.ref ?? item.target.ref) : [];
54 for (const ref of refs) {
55 if (!ref) continue;
56 const key = keyFor(ref), entry = entries.get(key);
57 if (!entry) continue;
58 entry.retired = true; entry.retire();
59 if (entry.timer) clearTimeout(entry.timer);
60 entries.delete(key);
61 for (const [tab, mapped] of tabs) if (mapped === key) { tabs.delete(tab); tabOwners.delete(tab); }
62 }
63 notify();
64 }
65 // Register before any composer owner can exist, including while an RPC is pending.
66 for (const method of ["ApplySessionLifecycle", "PurgeCanonicalSession"]) {
67 sessionPurgeHandlers[method] = (args, result) => reconcileSessionComposerPurge(method, args, result);
68 }
69 function prune() {
70 const idle=[...entries.entries()].filter(([,entry])=>entry.users===0 && entry.state && !entry.error && !entry.recovering && !entry.loading && !entry.saving && !entry.tasks.size && entry.version===entry.saved).sort((a,b)=>b[1].touched-a[1].touched);
71 for (const [key,entry] of idle.slice(20)) {
72 if (entry.timer) clearTimeout(entry.timer);
73 entries.delete(key);
74 for (const [tab,mapped] of tabs) if(mapped===key) tabs.delete(tab);
75 }
76 }
77 function parse(raw: string): PersistentComposerDraft {
78 const value = JSON.parse(raw || "{}");
79 if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid saved input");
80 if (value.text !== undefined && typeof value.text !== "string") throw new Error("Invalid saved input text");
81 for (const field of ["invocations","attachments","workspaceRefs","pastedBlocks","openPastedLabels","sessionRefs","selectedTextRefs"]) {
82 if (value[field] !== undefined && !Array.isArray(value[field])) throw new Error(`Invalid saved input ${field}`);
83 }
84 const content = { ...emptySessionInput(), ...value } as PersistentComposerDraft;
85 // Preview URLs are temporary renderer resources and never durable data.
86 content.attachments = (content.attachments || []).map(attachment => ({ ...attachment, previewUrl: undefined, file: undefined }));
87 return content;
88 }
89 function encoded(content: PersistentComposerDraft) {
90 return JSON.stringify({ ...content, attachments: content.attachments.map(attachment => ({ ...attachment,
91 path: attachment.recoveryPath || attachment.path, draftId: attachment.recoveryPath ? undefined : attachment.draftId,
92 previewUrl: undefined, file: undefined })) });
93 }
94 function entryFor(ref: SessionRef) {
95 const key = keyFor(ref);
96 let entry = entries.get(key);
97 if (!entry) {
98 let retire!: () => void;
99 const retirement = new Promise<void>(resolve => { retire = resolve; });
100 entry = { ref, content: emptySessionInput(), generation: ++serial, version: 0, saved: 0, users:0, touched:Date.now(), tasks: new Set(), inputTasks: new Set(), retirement, retire }; entries.set(key, entry);
101 }
102 return entry;
103 }
104 const submissionLocked = (entry: Entry) => entry.retired || !entry.state || Boolean(entry.registering || entry.unsubmittedId || entry.state.submissionId);
105 const locked = (entry: Entry) => submissionLocked(entry) || Boolean(entry.recovering || entry.unreadable);
106 async function load(entry: Entry) {
107 if (entry.loading) return entry.loading;
108 entry.loading = (async () => {
109 try {
110 const state = await app.GetSessionComposerState(entry.ref);
111 if (entry.retired || entry.version !== entry.saved) return;
112 const content=parse(state.contentJson);
113 entry.state = state; entry.content = content; entry.error = undefined; entry.unreadable = false;
114 // Reading durable input must not require a live attachment controller.
115 // Composer restores and validates external references before submission.
116 const attachments = entry.content.attachments;
117 void Promise.all(attachments.map(async attachment => {
118 try {
119 const previewUrl = await app.AttachmentDataURLForComposerTarget({kind:"session",session:entry.ref},attachment.recoveryPath || attachment.path);
120 if (entries.get(keyFor(entry.ref))!==entry || !entry.content.attachments.includes(attachment)) return;
121 entry.content = {...entry.content,attachments:entry.content.attachments.map(item=>item===attachment ? {...item,previewUrl} : item)};
122 notify();
123 } catch { /* Missing files remain visible as repairable references. */ }
124 }));
125 } catch (error) { if (!entry.retired) { entry.error = String(error); entry.unreadable = true; } }
126 finally { entry.loading = undefined; notify(); prune(); }
127 })();
128 return entry.loading;
129 }
130 async function flush(entry: Entry) {
131 if (entry.retired) return;
132 if (entry.recovering) await entry.recovering;
133 if (entry.loading) await entry.loading;
134 if (entry.retired) return;
135 if (entry.saving) { await entry.saving; if (entry.version > entry.saved) return flush(entry); return; }
136 if (entry.error || !entry.state) throw new Error(entry.error || "Input is not loaded");
137 if (entry.version === entry.saved && !entry.state.historyChanged) return;
138 entry.saving = (async () => {
139 let rebased = false;
140 while (!entry.retired && (entry.saved < entry.version || entry.state?.historyChanged)) {
141 if (!entry.state || entry.state.submissionId) throw new Error("Check the previous submission before editing");
142 const version = entry.version;
143 const result = await app.SaveSessionComposerState({ ref: entry.ref, expectedRevision: entry.state.revision,
144 contentJson: encoded(entry.content), contentVersion: 1, acknowledgeHistory: true });
145 if (entry.retired) return;
146 if (result.conflict) {
147 entry.state = result;
148 if (rebased || result.submissionId) throw new Error("Input changed during saving; retry to save the retained input");
149 // Rebase once without replacing the input currently being edited.
150 rebased = true; continue;
151 }
152 if (result.historyChanged) { entry.state = result; throw new Error("The conversation changed. Review the saved input."); }
153 entry.state = result; entry.saved = version;
154 }
155 })();
156 try { await entry.saving; } catch (error) { if (!entry.retired) { entry.error = String(error); throw error; } }
157 finally { entry.saving = undefined; notify(); prune(); }
158 }
159 function edit(entry: Entry, content: PersistentComposerDraft, accepted = false) {
160 if (accepted ? submissionLocked(entry) : locked(entry)) return;
161 // Admission stays locked during recovery, but accepted async work owns its
162 // result. Keep it in the local version that recovery reconciles and saves.
163 entry.content = content; entry.version++;
164 if (!entry.recovering && !entry.unreadable) entry.error = undefined;
165 entry.taskError = undefined; entry.application = undefined;
166 if (entry.timer) clearTimeout(entry.timer);
167 entry.timer = setTimeout(() => {
168 void flush(entry).catch(async () => { await recoverInput(entry); if (!locked(entry)) await flush(entry); }).catch(() => {});
169 }, 250);
170 notify();
171 }
172
173 export async function flushAllSessionComposers() {
174 exiting = true;
175 notify();
176 // Retry cached failures once per close attempt. A new failure must still
177 // veto close, and recovery must reconcile the store before retaining edits.
178 const retryable = new Set([...entries.values()].filter(entry => entry.error));
179 try {
180 do {
181 for (const entry of entries.values()) {
182 const save = async () => {
183 while (!entry.retired && entry.tasks.size) await Promise.race([Promise.allSettled([...entry.tasks]), entry.retirement]);
184 if (entry.retired) return;
185 // Loading/recovery can reveal an error or unsaved input even when the
186 // version looked clean at the start of close. Never skip those barriers.
187 if (entry.loading) await entry.loading;
188 if (entry.recovering) await entry.recovering;
189 if (entry.saving) await entry.saving;
190 if (entry.retired) return;
191 if (entry.error && retryable.delete(entry)) await recoverInput(entry);
192 if (entry.version > entry.saved || entry.error) await flush(entry);
193 };
194 // A committed purge also releases an already-running close barrier.
195 try { await Promise.race([save(), entry.retirement]); }
196 catch (error) { if (!entry.retired) throw error; }
197 }
198 // Accepted work may attach a continuation to an owner already visited
199 // while another owner's save was pending. Require global quiescence.
200 } while ([...entries.values()].some(entry => entry.tasks.size || entry.loading || entry.recovering || entry.saving || entry.version > entry.saved || entry.error));
201 } catch (error) { resumeSessionComposerEditing(); throw error; }
202 }
203 export function resumeSessionComposerEditing() { exiting = false; notify(); }
204
205 export async function beginPersistedComposerSubmission(tabId: string, submissionId: string, requestJSON: string, expectedEdit?: number, key = tabs.get(tabId), owner = tabOwners.get(tabId)) {
206 const entry = key ? entries.get(key) : undefined;
207 if (!entry) return undefined;
208 await flush(entry);
209 if (!owner || tabs.get(tabId) !== key || tabOwners.get(tabId) !== owner) throw new Error("reasonix_error:inbox_not_submitted");
210 // Accepted input must publish before a submission can freeze this draft.
211 // Submission tasks also participate in close draining, but never in this guard.
212 if (entry.inputTasks.size) throw new Error("Input is still being prepared; review and send again");
213 if (expectedEdit !== undefined && entry.version !== expectedEdit) throw new Error("Input changed while preparing submission; review and send again");
214 if (exiting || !entry.state || locked(entry)) throw new Error("Review the saved input before sending");
215 const submittedVersion = entry.version;
216 entry.registering = true;
217 notify();
218 try {
219 entry.state = await app.BeginSessionComposerSubmission(entry.ref, entry.state.revision, submissionId, requestJSON);
220 } catch (error) {
221 // The host may have committed despite transport failure. Reconcile before
222 // allowing edits or another send; never infer rejection from a lost reply.
223 entry.unsubmittedId = submissionId;
224 entry.unreadable = true; entry.error = String(error);
225 throw error;
226 } finally { entry.registering = false; notify(); }
227 if (entry.state.conflict) { notify(); throw new Error("The input changed before submission"); }
228 notify();
229 return (outcome: "accepted" | "not_accepted" | "unknown") => settleSubmission(entry, submissionId, outcome, submittedVersion);
230 }
231
232 async function settleSubmission(entry: Entry, submissionId: string, outcome: "accepted" | "not_accepted" | "unknown", submittedVersion: number) {
233 if (entry.retired) return;
234 const result = await app.CompleteSessionComposerSubmission(entry.ref, submissionId, outcome);
235 if (entry.retired) return;
236 if (result.conflict) { notify(); throw new Error("The input changed during submission"); }
237 if (!entry.state || BigInt(result.revision) >= BigInt(entry.state.revision)) {
238 entry.state = result;
239 // A recovery read may already have settled this send and enabled new
240 // edits. Only replace the captured version, using the host's actual input.
241 if (!result.submissionId && entry.version === submittedVersion) {
242 entry.content = parse(result.contentJson); entry.version++; entry.saved = entry.version;
243 }
244 if (!result.submissionId) entry.settledId = submissionId;
245 }
246 notify();
247 }
248
249 async function recoverInput(entry: Entry) {
250 if (entry.retired) return;
251 if (entry.recovering) return entry.recovering;
252 if (entry.registering) return;
253 entry.recovering = (async () => {
254 if (entry.loading) await entry.loading;
255 if (entry.saving) await entry.saving.catch(() => {});
256 if (entry.retired) return;
257 const previous = entry.state;
258 const pending = previous?.submissionId || entry.unsubmittedId;
259 try {
260 let state = await app.GetSessionComposerState(entry.ref);
261 if (entry.retired) return;
262 // This renderer never invoked send after a failed registration. Only its
263 // own registration can be released; an absent receipt alone is not proof.
264 if (entry.unsubmittedId && state.submissionId === entry.unsubmittedId) {
265 state = await app.CompleteSessionComposerSubmission(entry.ref, entry.unsubmittedId, "not_accepted");
266 if (entry.retired) return;
267 }
268 const content = parse(state.contentJson);
269 if (entry.state && BigInt(state.revision) < BigInt(entry.state.revision)) return;
270 entry.error = undefined; entry.unreadable = false;
271 entry.state = state;
272 if (state.submissionId) return;
273 if (pending) entry.settledId = pending;
274 if (previous?.submissionId && encoded(entry.content) === encoded(parse(previous.contentJson))) {
275 entry.content = content; entry.version++; entry.saved = entry.version;
276 } else if (encoded(content) === encoded(entry.content)) {
277 entry.saved = entry.version;
278 } else if (previous && encoded(content) !== encoded(parse(previous.contentJson))) {
279 // Continue with this window's input on its next save or explicit send.
280 if (entry.version === entry.saved) entry.version++;
281 } else if (!previous) {
282 entry.content = content; entry.saved = entry.version;
283 }
284 entry.unsubmittedId = undefined;
285 } catch (error) { if (!entry.retired) { entry.error = String(error); entry.unreadable = true; throw error; } }
286 })();
287 notify();
288 try { await entry.recovering; } finally { entry.recovering = undefined; notify(); }
289 }
290
291 export function useSessionComposerPersistence(ref: SessionRef | undefined, tabId: string | undefined) {
292 const key = ref?.hostId === "local" ? keyFor(ref) : "";
293 const entry = useMemo(() => key && ref ? entryFor(ref) : undefined, [key]);
294 useSyncExternalStore(subscribe, snapshot);
295 useEffect(() => {
296 if (!entry || entry.retired) return;
297 entries.set(key,entry);
298 entry.users++; entry.touched=Date.now();
299 const owner = Symbol();
300 if (tabId) { tabs.set(tabId,key); tabOwners.set(tabId,owner); }
301 if (!entry.state && !entry.loading) void load(entry);
302 return () => {
303 if (tabId && tabOwners.get(tabId) === owner) { tabs.delete(tabId); tabOwners.delete(tabId); }
304 entry.users--; if (entry.version > entry.saved) void flush(entry).catch(() => {}); prune();
305 };
306 }, [entry,key,tabId]);
307 const target: PersistentComposerTarget | undefined = entry ? {
308 draftId:key, generation:entry.generation, initial:entry.content, revision:entry.version,
309 isCurrent:(id,generation) => !entry.retired && entries.get(key)===entry && id===key && generation===entry.generation,
310 canEdit:() => !exiting && !locked(entry),
311 // Already accepted tasks still publish through onPatch while closing.
312 onChange:(_id,generation,content) => { if (generation===entry.generation) edit(entry,content); },
313 onPatch:(_id,generation,patch) => { if (!entry.retired && generation===entry.generation) edit(entry,{ ...entry.content,...(typeof patch==="function" ? patch(entry.content) : patch) },true); },
314 trackTask:(_id,generation,promise,blocksSubmission) => {
315 if (!entry.retired && generation===entry.generation) {
316 entry.tasks.add(promise); if (blocksSubmission) entry.inputTasks.add(promise);
317 void promise.finally(()=>{entry.tasks.delete(promise);entry.inputTasks.delete(promise);prune();}).catch(()=>{});
318 }
319 return promise;
320 },
321 // Failed attachment operations remain visible, but do not make the
322 // retained input unreadable or prevent its independent durable save.
323 onTaskError:(_id,generation,error) => { if (!entry.retired && generation===entry.generation) { entry.taskError=error; notify(); } },
324 } : undefined;
325 return { target, blocked:entry ? exiting || locked(entry) : false, error:entry?.error, taskError:entry?.taskError,
326 dismissTaskError:() => { if (entry) { entry.taskError=undefined; notify(); } },
327 application:entry?.application,
328 setApplication:(value:ModelApplicationDetails|undefined)=>{if(entry){entry.application=value;notify();}},
329 reportSubmissionError:(error:unknown) => { if (entry) {entry.application=modelApplicationError(error);notify();} },
330 // Editable retained text does not authorize restoring a mode from older history.
331 goalDraft:!entry?.state?.historyChanged && entry?.content.goalDraft,
332 setGoalDraft:(enabled:boolean) => { if (entry && !exiting) edit(entry,{...entry.content,goalDraft:enabled}); },
333 settleSubmission:async (id:string) => { if (entry?.state?.submissionId === id) await settleSubmission(entry,id,"accepted",entry.version); },
334 attention: Boolean(entry?.state?.submissionId),
335 recovering: Boolean(entry?.recovering),
336 settledId: entry?.settledId,
337 retry:async () => { if (!entry) return; await recoverInput(entry); if (!locked(entry)) await flush(entry); },
338 };
339 }
340
340 lines TYPESCRIPT