okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
12.1 KiB205 linesraw
1/**
2 * #5008: two chats, one workspace, a tool that writes a unique marker.
3 * A folder shared by two chats is shared on purpose; what a chat shows as its own (messages, tool cards, "files this turn made") is private.
4 */
5import test from 'node:test';
6import assert from 'node:assert/strict';
7import { build } from 'esbuild';
8import { fileURLToPath } from 'node:url';
9import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs';
10import { tmpdir } from 'node:os';
11import { join } from 'node:path';
12import { DeliverableTracker, FolderClaims } from '../server/agent/deliverables.mjs';
13import { createChatStore } from '../server/chat-store.mjs';
14import { installFakeHostFetch } from './helpers/fake-host-chats.mjs';
15
16const here = (p) => fileURLToPath(new URL(p, import.meta.url));
17
18/* ---------------------------------------------------------------- host side: files a turn made */
19
20/** A "tool" of a chat: writes a file with a unique marker, then asks the chat's tracker about it (what the bridge does on a write/edit card). */
21function tool(dir, tracker, name, marker) {
22  writeFileSync(join(dir, name), `marker:${marker}\n`);
23  return tracker.check(name, { explicit: true });
24}
25
26test('two chats in one folder: each turn reports only the files its own tools wrote, interleaved, and a script file nobody can own is withheld', () => {
27  const dir = mkdtempSync(join(tmpdir(), 'strata-5008-'));
28  try {
29    const claims = new FolderClaims();
30    const A = new DeliverableTracker(dir, { claims, owner: 'chat-A' });
31    const B = new DeliverableTracker(dir, { claims, owner: 'chat-B' });
32    A.snapshot(); claims.begin(dir, 'chat-A');
33    B.snapshot(); claims.begin(dir, 'chat-B');
34    const reportedA = [], reportedB = [];
35    // alternate marked turns
36    reportedA.push(tool(dir, A, 'a-1.txt', 'A-one'));
37    reportedB.push(tool(dir, B, 'b-1.txt', 'B-one'));
38    reportedA.push(tool(dir, A, 'a-2.txt', 'A-two'));
39    reportedB.push(tool(dir, B, 'b-2.txt', 'B-two'));
40    mkdirSync(join(dir, 'out')); writeFileSync(join(dir, 'out', 'script-made.csv'), 'x,y\n1,2\n');   // a script's output, while both run
41    // A ends first: its sweep must not claim B's files
42    const sweptA = A.sweep(); claims.end(dir, 'chat-A');
43    const sweptB = B.sweep(); claims.end(dir, 'chat-B');
44    assert.deepEqual(reportedA.map(d => d.path), ['a-1.txt', 'a-2.txt']);
45    assert.deepEqual(reportedB.map(d => d.path), ['b-1.txt', 'b-2.txt']);
46    assert.deepEqual(sweptA.map(d => d.path), [], 'chat A is not given chat B\'s files, nor a file whose writer cannot be told');
47    assert.deepEqual(sweptB.map(d => d.path), [], 'and the other way round');
48  } finally { rmSync(dir, { recursive: true, force: true }); }
49});
50
51test('a chat working alone still gets the files its scripts made (nothing changes without a second chat)', () => {
52  const dir = mkdtempSync(join(tmpdir(), 'strata-5008b-'));
53  try {
54    const claims = new FolderClaims();
55    const A = new DeliverableTracker(dir, { claims, owner: 'chat-A' });
56    A.snapshot(); claims.begin(dir, 'chat-A');
57    writeFileSync(join(dir, 'built.js'), 'x\n');
58    assert.deepEqual(A.sweep().map(d => d.path), ['built.js']);
59    claims.end(dir, 'chat-A');
60    // a second chat that starts after the first has ended is not overlapped with it
61    const B = new DeliverableTracker(dir, { claims, owner: 'chat-B' });
62    B.snapshot(); claims.begin(dir, 'chat-B');
63    writeFileSync(join(dir, 'later.js'), 'y\n');
64    assert.deepEqual(B.sweep().map(d => d.path), ['later.js']);
65    claims.end(dir, 'chat-B');
66  } finally { rmSync(dir, { recursive: true, force: true }); }
67});
68
69test('a chat that is stopped or fails still lets go of the folder, and another folder is never affected', () => {
70  const one = mkdtempSync(join(tmpdir(), 'strata-5008c-')), two = mkdtempSync(join(tmpdir(), 'strata-5008d-'));
71  try {
72    const claims = new FolderClaims();
73    const A = new DeliverableTracker(one, { claims, owner: 'chat-A' });
74    const B = new DeliverableTracker(two, { claims, owner: 'chat-B' });
75    A.snapshot(); claims.begin(one, 'chat-A');
76    B.snapshot(); claims.begin(two, 'chat-B');
77    writeFileSync(join(one, 'a.js'), 'x\n'); writeFileSync(join(two, 'b.js'), 'y\n');
78    assert.deepEqual(A.sweep().map(d => d.path), ['a.js'], 'different folders are not overlapped');
79    assert.deepEqual(B.sweep().map(d => d.path), ['b.js']);
80    claims.end(one, 'chat-A'); claims.end(one, 'chat-A');   // ending twice (stop, then error) is harmless
81    claims.end(two, 'chat-B');
82    assert.equal(claims.ownerOf(one, 'a.js'), null);
83    assert.equal(claims.overlapped(one, 'chat-A'), false);
84  } finally { rmSync(one, { recursive: true, force: true }); rmSync(two, { recursive: true, force: true }); }
85});
86
87test('a file both chats wrote with their file tools is reported to each chat that wrote it', () => {
88  const dir = mkdtempSync(join(tmpdir(), 'strata-5008e-'));
89  try {
90    const claims = new FolderClaims();
91    const A = new DeliverableTracker(dir, { claims, owner: 'chat-A' });
92    const B = new DeliverableTracker(dir, { claims, owner: 'chat-B' });
93    A.snapshot(); claims.begin(dir, 'chat-A'); B.snapshot(); claims.begin(dir, 'chat-B');
94    assert.equal(tool(dir, A, 'shared.md', 'A').status, 'created');
95    assert.ok(tool(dir, B, 'shared.md', 'B-longer-marker'), 'the second chat\'s own write is its own deliverable');
96  } finally { rmSync(dir, { recursive: true, force: true }); }
97});
98
99/* ---------------------------------------------------------------- app side: messages and tool cards of two live chats */
100
101async function bundle(entry, plugins = []) {
102  const result = await build({
103    entryPoints: [here(entry)], bundle: true, format: 'esm', platform: 'node', write: false, logLevel: 'silent',
104    alias: { react: here('./helpers/react-stub.mjs') }, loader: { '.json': 'json' }, plugins,
105  });
106  return import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`);
107}
108
109test('two live chats in one workspace keep their messages, tool cards and saved copies apart, interleaved, and after a restart', async () => {
110  const hostDir = mkdtempSync(join(tmpdir(), 'strata-5008-host-'));
111  const chatStore = createChatStore({ dir: hostDir });
112  const fakeHost = installFakeHostFetch(chatStore);
113  try {
114  globalThis.window ??= globalThis;
115  globalThis.document ??= { addEventListener() {}, hasFocus: () => true, visibilityState: 'visible', documentElement: { dataset: {}, style: { setProperty() {} }, classList: { toggle() {}, add() {}, remove() {} } } };
116  const memory = new Map();
117  globalThis.localStorage = {
118    get length() { return memory.size; },
119    key: (i) => [...memory.keys()][i] ?? null,
120    getItem: (k) => memory.get(k) ?? null,
121    setItem: (k, v) => { memory.set(k, v); },
122    removeItem: (k) => memory.delete(k),
123  };
124  globalThis.navigator ??= { language: 'en' };
125  globalThis.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
126  globalThis.__streams = [];
127  const mockClient = {
128    name: 'mock-client',
129    setup(b) {
130      b.onResolve({ filter: /\/client$/ }, () => ({ path: 'mock-client', namespace: 'mock' }));
131      b.onLoad({ filter: /.*/, namespace: 'mock' }, () => ({
132        loader: 'js',
133        contents: `
134          export class ApiError extends Error {}
135          const reject = async () => { throw new Error('offline'); };
136          export const api = { get: reject, post: async () => ({}), put: reject, patch: reject, del: reject, delete: reject };
137          export function onEvent() { return () => {}; }
138          export async function streamPost(path, body, onFrame) {
139            await new Promise((release) => globalThis.__streams.push({ body, onFrame, release }));
140          }`,
141      }));
142    },
143  };
144  const store = await bundle('../src/lib/store.ts', [mockClient]);
145  await store.loadChatsFromHost();   // the first read of the host's chats (the page's own start-up does this inside bootstrap)
146  const wait = async (n) => { for (let i = 0; i < 200 && globalThis.__streams.length < n; i++) await new Promise((r) => setTimeout(r, 5)); assert.ok(globalThis.__streams.length >= n, `stream ${n} started`); };
147
148  const a = store.newSession();
149  const turnA = store.sendMessage('question for chat A MARK-A');
150  await wait(1);
151  const b = store.newSession();
152  const turnB = store.sendMessage('question for chat B MARK-B');
153  await wait(2);
154  const [sa, sb] = globalThis.__streams;
155  assert.equal(sa.body.sessionId, a.id);
156  assert.equal(sb.body.sessionId, b.id);
157  assert.notEqual(sa.body.sessionId, sb.body.sessionId);
158  assert.ok(!JSON.stringify(sb.body.history).includes('MARK-A'), 'chat B\'s request carries none of chat A\'s history');
159
160  const tool = (id, marker) => ({ type: 'agent-tool', tool: { id, name: 'write', state: 'done', args: { file_path: `${marker}.txt` }, result: `wrote marker ${marker}` } });
161  // interleave: A, B, A, B
162  sa.onFrame({ type: 'start', model: 'm', contextMax: 8192, requestId: 'rA', agent: true });
163  sb.onFrame({ type: 'start', model: 'm', contextMax: 8192, requestId: 'rB', agent: true });
164  sa.onFrame(tool('call-1', 'A-unique-1'));
165  sb.onFrame(tool('call-1', 'B-unique-1'));   // the same call id in both chats: ids are only unique inside a chat
166  sa.onFrame({ type: 'delta', text: 'answer A ' });
167  sb.onFrame({ type: 'delta', text: 'answer B ' });
168  sa.onFrame({ type: 'delta', text: 'ends A' });
169  sb.onFrame({ type: 'delta', text: 'ends B' });
170  sa.onFrame({ type: 'done', tokensIn: 5, tokensOut: 5, durationMs: 10, usageSource: 'reported' });
171  sb.onFrame({ type: 'done', tokensIn: 5, tokensOut: 5, durationMs: 10, usageSource: 'reported' });
172  sa.release(); sb.release();
173  await Promise.all([turnA, turnB]);
174  await store.flushSessions();
175
176  const saved = [];
177  for (const e of chatStore.list().chats) saved.push(JSON.parse(await chatStore.read(e.id)).session);
178  assert.equal(saved.length, 2, JSON.stringify(fakeHost.calls.map((c) => `${c.method} ${c.path}`)));
179  const bodyOf = (id) => JSON.stringify(saved.find((s) => s.id === id));
180  assert.ok(bodyOf(a.id).includes('MARK-A') && bodyOf(a.id).includes('A-unique-1') && bodyOf(a.id).includes('ends A'));
181  assert.ok(!/MARK-B|B-unique|ends B/.test(bodyOf(a.id)), 'chat A holds nothing of chat B');
182  assert.ok(bodyOf(b.id).includes('MARK-B') && bodyOf(b.id).includes('B-unique-1') && bodyOf(b.id).includes('ends B'));
183  assert.ok(!/MARK-A|A-unique|ends A/.test(bodyOf(b.id)), 'chat B holds nothing of chat A');
184
185  // A second window saves a chat of its own, and then one of this window's chats; this window takes the first over and keeps its own.
186  const other = { id: 's_from_other_window', title: 'from window 2', createdAt: '2026-12-01T00:00:00.000Z', updatedAt: '2026-12-01T00:00:01.000Z', messages: [{ id: 'o1', role: 'user', content: 'MARK-OTHER-WINDOW' }] };
187  const saved2 = await chatStore.save(other.id, JSON.stringify(other));
188  await store.applyChatChange(other.id, saved2.rev, false);
189  assert.ok(store.useStore((s) => s.sessions).some((s) => s.id === other.id && s.messages[0].content === 'MARK-OTHER-WINDOW'), 'the chat saved by the other window appears here');
190  // while a turn is running in chat A here, the other window's save of chat A does not replace it
191  store.selectSession(a.id);
192  const liveSend = store.sendMessage('second question MARK-A2');
193  await wait(3);
194  const [, , sa2] = globalThis.__streams;
195  await chatStore.save(a.id, JSON.stringify({ ...JSON.parse(JSON.stringify(store.useStore((s) => s.sessions).find((s) => s.id === a.id))), title: 'renamed in window 2' }));
196  await store.applyChatChange(a.id, 99, false);
197  assert.notEqual(store.useStore((s) => s.sessions).find((s) => s.id === a.id).title, 'renamed in window 2', 'a chat with a turn running here is not replaced');
198  sa2.onFrame({ type: 'done', tokensIn: 1, tokensOut: 1, durationMs: 1, usageSource: 'reported' });
199  sa2.release(); await liveSend;
200  // the other window deletes its chat
201  await chatStore.remove(other.id);
202  await store.applyChatChange(other.id, null, true);
203  assert.ok(!store.useStore((s) => s.sessions).some((s) => s.id === other.id), 'a chat the other window deleted goes here too');
204  } finally { fakeHost.restore(); rmSync(hostDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }   // a save that lands while the folder is removed (ENOTEMPTY, seen on a macOS runner): try again
205});