File size: 6,678 Bytes
0ed8124
 
 
 
 
 
 
 
33e51e5
0ed8124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33e51e5
0ed8124
33e51e5
 
 
 
0ed8124
 
33e51e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ed8124
 
 
 
179a355
0ed8124
33e51e5
 
 
 
0ed8124
33e51e5
0ed8124
 
 
 
33e51e5
 
 
 
0ed8124
 
33e51e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ed8124
 
 
 
 
 
 
 
179a355
 
 
33e51e5
 
 
 
 
 
 
 
 
 
179a355
0ed8124
 
33e51e5
0ed8124
33e51e5
0ed8124
33e51e5
0ed8124
 
 
 
 
 
 
 
 
 
 
33e51e5
0ed8124
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import { chromium } from '@playwright/test';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createServer as createViteServer } from 'vite';

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const memoryKey = '__bonsai_persistence_probe__';
const conversationId = '__bonsai_conversation_probe__';
const artifactId = '__bonsai_artifact_persistence_probe__';
let browser;
let page;
let vite;

try {
  vite = await createViteServer({
    root,
    logLevel: 'error',
    server: { host: '127.0.0.1', port: 0 },
    plugins: [{
      name: 'persistence-probe-page',
      configureServer(server) {
        server.middlewares.use('/persistence-probe.html', (_request, response) => {
          response.setHeader('Content-Type', 'text/html; charset=utf-8');
          response.end('<!doctype html><title>Persistence probe</title>');
        });
      },
    }],
  });
  await vite.listen();
  const address = vite.httpServer?.address();
  if (!address || typeof address === 'string') throw new Error('Vite persistence probe did not expose a TCP port');

  browser = await chromium.launch({ headless: true });
  page = await browser.newPage();
  await page.goto(`http://127.0.0.1:${address.port}/persistence-probe.html`);
  await page.evaluate(async ({ memoryKey, conversationId, artifactId }) => {
    const idb = await import('/src/lib/idb.ts');
    const {
      evaluateHtmlArtifact,
      prepareArtifactDeployment,
    } = await import('/src/lib/artifact-runtime.ts');
    await idb.deleteMemory(memoryKey);
    await idb.putMemory(memoryKey, 'survives reload');
    const artifact = prepareArtifactDeployment([
      {
        path: 'index.html',
        content: '<main id="app">Loading</main><script type="module" src="./src/main.js"></script>',
      },
      {
        path: 'src/main.js',
        content: 'const data = await fetch("../data/state.json").then((response) => response.json()); document.querySelector("#app").textContent = data.message;',
      },
      { path: 'data/state.json', content: '{"message":"workspace survives reload"}' },
    ], 'Persistent workspace', 'index.html', artifactId);
    artifact.evaluation = await evaluateHtmlArtifact(artifact);
    if (artifact.evaluation.status !== 'passed') {
      throw new Error(`Artifact setup failed: ${JSON.stringify(artifact.evaluation)}`);
    }
    const staleRecoverySnapshot = {
      ...artifact,
      files: artifact.files.map((file) => file.path === 'data/state.json'
        ? {
            ...file,
            content: '{"message":"stale conversation snapshot"}',
            bytes: new TextEncoder().encode('{"message":"stale conversation snapshot"}').byteLength,
          }
        : file),
    };
    await idb.saveConversation({
      id: conversationId,
      title: 'Persistence probe',
      modelId: 'bonsai-1.7b',
      toolsEnabled: true,
      updatedAt: 0,
      messages: [
        { role: 'user', content: 'keep locally' },
        { role: 'assistant', content: '', artifacts: [staleRecoverySnapshot] },
      ],
    });
  }, { memoryKey, conversationId, artifactId });

  await page.reload({ waitUntil: 'domcontentloaded' });
  const persisted = await page.evaluate(async ({ memoryKey, conversationId }) => {
    const idb = await import('/src/lib/idb.ts');
    const {
      evaluateHtmlArtifact,
      hydrateArtifactDocument,
    } = await import('/src/lib/artifact-runtime.ts');
    const memory = await idb.getMemory(memoryKey);
    const conversation = await idb.loadConversation(conversationId);
    const snapshot = conversation?.messages?.[1]?.artifacts?.[0];
    if (!snapshot) throw new Error('Saved conversation lost its artifact snapshot');
    const artifact = await hydrateArtifactDocument(snapshot);
    const evaluation = await evaluateHtmlArtifact(artifact);
    return {
      memory,
      conversation,
      artifact: {
        id: artifact.id,
        storage: artifact.workspaceStorage,
        files: artifact.files?.map(({ path, content }) => ({ path, content })),
        sandboxContainsCurrent: artifact.sandboxedSource.includes('workspace survives reload'),
        sandboxContainsStale: artifact.sandboxedSource.includes('stale conversation snapshot'),
        evaluation,
      },
    };
  }, { memoryKey, conversationId });

  if (persisted.memory?.value !== 'survives reload') {
    throw new Error(`Memory did not survive reload: ${JSON.stringify(persisted.memory)}`);
  }
  if (persisted.conversation?.messages?.[0]?.content !== 'keep locally') {
    throw new Error(`Conversation did not survive reload: ${JSON.stringify(persisted.conversation)}`);
  }
  if (persisted.conversation?.toolsEnabled !== true) {
    throw new Error(`Per-chat tools state did not survive reload: ${JSON.stringify(persisted.conversation)}`);
  }
  if (persisted.artifact?.id !== artifactId
    || persisted.artifact.storage !== 'opfs'
    || persisted.artifact.files?.length !== 3
    || !persisted.artifact.files.some((file) => file.path === 'data/state.json' && file.content.includes('survives reload'))
    || persisted.artifact.sandboxContainsCurrent !== true
    || persisted.artifact.sandboxContainsStale !== false
    || persisted.artifact.evaluation?.status !== 'passed'
    || persisted.artifact.evaluation?.dom?.textPreview !== 'workspace survives reload') {
    throw new Error(`Artifact workspace did not survive reload: ${JSON.stringify(persisted.artifact)}`);
  }
  console.log('Persistence passed: memory, per-chat tools state, conversation, and its three-file OPFS artifact survived reload and re-evaluated');
} finally {
  if (page) {
    await page.evaluate(async ({ memoryKey, conversationId, artifactId }) => {
      const idb = await import('/src/lib/idb.ts');
      const { deleteArtifactDocumentStorage } = await import('/src/lib/artifact-runtime.ts');
      await idb.deleteMemory(memoryKey).catch(() => undefined);
      await deleteArtifactDocumentStorage(artifactId).catch(() => undefined);
      const request = indexedDB.open('bonsai-webgpu-chat', 1);
      await new Promise((resolve) => {
        request.onsuccess = () => {
          const database = request.result;
          const transaction = database.transaction('conversations', 'readwrite');
          transaction.objectStore('conversations').delete(conversationId);
          transaction.oncomplete = () => { database.close(); resolve(); };
          transaction.onerror = () => { database.close(); resolve(); };
        };
        request.onerror = () => resolve();
      });
    }, { memoryKey, conversationId, artifactId }).catch(() => undefined);
  }
  await browser?.close();
  await vite?.close();
}