Skip to content

The agent that grows with you

fix: retain dashboard mutation identity across uncertain replies

Teknium20dd681307dc
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index dee205d9d20..2543b8519ef 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -1,4 +1,7 @@
import { buildHermesWebSocketUrl } from "@hermes/shared";
+import { createDashboardSessionMutations } from "./session-mutations";
+
+const mutateSessionHttp = createDashboardSessionMutations(fetchJSON);
// The dashboard can be served either at the root of its host (e.g.
// https://kanban.tilos.com/) or under a URL prefix when reverse-proxied
@@ -406,12 +409,7 @@ export const api = {
),
),
deleteSession: (id: string, profile = getManagementProfile()) =>
- fetchJSON<{ ok: boolean }>(
- appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile),
- {
- method: "DELETE",
- },
- ),
+ mutateSessionHttp<{ ok: boolean }>(id, "DELETE", {}, profile),
getEmptySessionsCount: (profile = getManagementProfile()) =>
fetchJSON<{ count: number }>(
appendProfileParam("/api/sessions/empty/count", profile),
@@ -430,14 +428,7 @@ export const api = {
body: JSON.stringify({ ids, profile: profile || undefined }),
}),
renameSession: (id: string, title: string, profile = getManagementProfile()) =>
- fetchJSON<{ ok: boolean; title: string }>(
- `/api/sessions/${encodeURIComponent(id)}`,
- {
- method: "PATCH",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ title, profile: profile || undefined }),
- },
- ),
+ mutateSessionHttp<{ ok: boolean; title: string }>(id, "PATCH", { title }, profile),
getSessionStats: (profile = getManagementProfile()) =>
fetchJSON<SessionStoreStats>(appendProfileParam("/api/sessions/stats", profile)),
exportSessionUrl: (id: string, profile = getManagementProfile()) =>
@@ -445,12 +436,11 @@ export const api = {
importSessions: (
sessions: Array<Record<string, unknown>>,
profile = getManagementProfile(),
- ) =>
- fetchJSON<SessionImportResponse>("/api/sessions/import", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ sessions, profile: profile || undefined }),
- }),
+ ) => {
+ const id = sessions[0]?.id;
+ if (typeof id !== "string" || !id) return Promise.reject(new Error("session id is required"));
+ return mutateSessionHttp<SessionImportResponse>(id, "POST", { sessions }, profile);
+ },
pruneSessions: (
older_than_days: number,
source?: string,
diff --git a/web/src/lib/session-mutations.test.ts b/web/src/lib/session-mutations.test.ts
new file mode 100644
index 00000000000..980f22f0af9
--- /dev/null
+++ b/web/src/lib/session-mutations.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { api, setManagementProfile } from './api';
+
+beforeEach(() => {
+ vi.stubGlobal('window', { __HERMES_SESSION_TOKEN__: 'fixture' });
+ setManagementProfile('work');
+});
+afterEach(() => { vi.unstubAllGlobals(); setManagementProfile(''); });
+
+it('prepares import and delete from snapshots and retries unchanged after a lost reply', async () => {
+ const writes: Array<{ path: string; init: RequestInit }> = [];
+ let lost = true;
+ vi.stubGlobal('fetch', vi.fn(async (path: string, init: RequestInit) => {
+ if (!init.method) {
+ const absent = path.includes('new-import');
+ return Response.json({ exists: !absent, runtime_revision: absent ? 0 : 27, runtime_generation: absent ? null : 6 });
+ }
+ writes.push({ path, init });
+ if (lost) { lost = false; throw new TypeError('Failed to fetch'); }
+ return Response.json({ ok: true });
+ }));
+ await expect(api.deleteSession('existing')).rejects.toThrow('Failed to fetch');
+ await api.deleteSession('existing');
+ expect(writes[1]).toEqual(writes[0]);
+ const query = new URL(writes[0].path, 'http://localhost').searchParams;
+ expect(query.get('expected_revision')).toBe('27');
+ expect(query.get('expected_generation')).toBe('6');
+ expect(query.get('request_id')).toBeTruthy();
+ await api.importSessions([{ id: 'new-import', messages: [] }]);
+ expect(JSON.parse(writes[2].init.body as string)).toMatchObject({ expected_revision: 0,
+ request_id: expect.any(String), profile: 'work' });
+});
+
+it('surfaces revision conflicts and never substitutes missing counters', async () => {
+ const fetcher = vi.fn(async (_path: string, init: RequestInit) => {
+ if (!init.method) { return Response.json({ exists: true, runtime_revision: 11, runtime_generation: 3 }); }
+ expect(JSON.parse(init.body as string)).toMatchObject({ expected_revision: 11, expected_generation: 3 });
+ return Response.json({ detail: 'revision_conflict' }, { status: 409 });
+ });
+ vi.stubGlobal('fetch', fetcher);
+ await expect(api.renameSession('rename', 'title')).rejects.toThrow('revision_conflict');
+ expect(fetcher).toHaveBeenCalledTimes(2);
+ fetcher.mockReset().mockResolvedValue(Response.json({ exists: true }));
+ await expect(api.deleteSession('no-snapshot')).rejects.toThrow(/snapshot/);
+ expect(fetcher).toHaveBeenCalledTimes(1);
+});
diff --git a/web/src/lib/session-mutations.ts b/web/src/lib/session-mutations.ts
new file mode 100644
index 00000000000..999077a3c29
--- /dev/null
+++ b/web/src/lib/session-mutations.ts
@@ -0,0 +1,28 @@
+import { createSessionMutationClient, type SessionMutationSnapshot } from '../../../apps/shared/src/session-http-mutations';
+
+export function createDashboardSessionMutations(fetchJSON: <T>(path: string, init?: RequestInit) => Promise<T>) {
+ const mutate = createSessionMutationClient();
+ return <T>(id: string, method: 'PATCH' | 'DELETE' | 'POST', payload: Record<string, unknown>, profile: string): Promise<T> => {
+ const path = `/api/sessions/${encodeURIComponent(id)}`;
+ const query = new URLSearchParams(profile ? { profile } : {});
+ const suffix = query.size ? `?${query}` : '';
+ // Clone before awaiting the snapshot: a file-selection/UI change cannot
+ // alter the import whose stable request identity is already being prepared.
+ const frozen = JSON.parse(JSON.stringify(payload)) as Record<string, unknown>;
+ const key = JSON.stringify([profile, id, method, frozen]);
+ return mutate(key,
+ () => fetchJSON<SessionMutationSnapshot>(`${path}/mutation-snapshot${suffix}`),
+ identity => {
+ if (method === 'DELETE') {
+ const params = new URLSearchParams(query);
+ for (const [name, value] of Object.entries(identity)) { params.set(name, String(value)); }
+ return fetchJSON<T>(`${path}?${params}`, { method });
+ }
+ const { expected_generation: generation, ...baseIdentity } = identity;
+ return fetchJSON<T>(method === 'POST' ? '/api/sessions/import' : path, { method,
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ ...frozen, ...baseIdentity,
+ ...(method === 'PATCH' ? { expected_generation: generation } : {}), profile: profile || undefined }) });
+ }, method === 'POST');
+ };
+}