@pi-chamber/web 1.0.6-rc.3 → 1.0.6-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{DiagramView-Dq5w8TCG.js → DiagramView--XO16VPB.js} +1 -1
- package/dist/assets/DiffView-Duy2_7Gp.js +18 -0
- package/dist/assets/{FileSaveConflictDialog-dFqLbFzT.js → FileSaveConflictDialog-B1DvL9zy.js} +2 -2
- package/dist/assets/FilesView-CjjPpE4c.js +6 -0
- package/dist/assets/{GitHubDetailScaffold-B2HRjT8V.js → GitHubDetailScaffold-DqxAKqCT.js} +4 -4
- package/dist/assets/{GitHubLinkPicker-D7I3J9_O.js → GitHubLinkPicker-ELF_chia.js} +1 -1
- package/dist/assets/GitHubListPrimitives-C2nGTntk.js +1 -0
- package/dist/assets/GitView-5fIq2nzM.js +9 -0
- package/dist/assets/IssuesSurface-Dq5A_bWq.js +7 -0
- package/dist/assets/{JsonTreeView-BJr5kBg4.js → JsonTreeView-BjFFSUwi.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-B9Cu4TCh.js +12 -0
- package/dist/assets/{PatchDiff-B6RBZULC.js → PatchDiff-CTqTTcg7.js} +1 -1
- package/dist/assets/{PierreDiffViewer-YJJQkE7t.js → PierreDiffViewer-H2f4pJ1k.js} +15 -3
- package/dist/assets/PullRequestsSurface-DPpb2RW_.js +2 -0
- package/dist/assets/SessionSwitcherContent-B5DaBWZU.js +1 -0
- package/dist/assets/{SessionSwitcherDropdown-CEAid1Bd.js → SessionSwitcherDropdown-D86FaZg_.js} +2 -2
- package/dist/assets/SessionUnreadDot-CY9-1iV2.js +1 -0
- package/dist/assets/SettingsView-CiIuOi_E.js +6 -0
- package/dist/assets/{SettingsWindow-5dK-buUn.js → SettingsWindow-Bw1dUoJ1.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-p7EbL2-E.js → StickyHorizontalScrollbar-DNsbTLS7.js} +1 -1
- package/dist/assets/{ToolOutputDialog-gITobhpo.js → ToolOutputDialog-aR4kcgKL.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-nOJxBl-Y.js → ToolPartDiffPreview-B_wWmhtE.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-BmJk6XJm.js → VirtualizedFileDiff-BYby097w.js} +4 -4
- package/dist/assets/{Virtualizer-DNJrJKVb.js → Virtualizer-okhy9Aq3.js} +1 -1
- package/dist/assets/{collapsible-0yfy07W2.js → collapsible-Dz0bPrJ_.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-BCFpa-1q.js → computeVirtualFileMetrics-8MuwxSC6.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-BCi5nTZp.js → contextFileOpenGuard-fZ2NIQMQ.js} +1 -1
- package/dist/assets/fileTreeStatus-BzhMMLA9.js +7 -0
- package/dist/assets/gitStatusPredicates-Cyh9UhYX.js +1 -0
- package/dist/assets/{githubLink-CCmFsyTF.js → githubLink-D2PznPcI.js} +2 -2
- package/dist/assets/{index-BaeFf5Q8.js → index-BX5pAOQX.js} +1 -1
- package/dist/assets/index-Cs2nBW_t.js +11 -0
- package/dist/assets/index-tmO0fZa4.css +1 -0
- package/dist/assets/main-7vBNPBMb.js +137 -0
- package/dist/assets/{main-CgXs2e27.js → main-BI6qe8pz.js} +2 -2
- package/dist/assets/{markdownCore-DTNVLpYS.js → markdownCore-D5jiabKe.js} +1 -1
- package/dist/assets/{miniChat-CrAin_em.js → miniChat-B3up4Bnz.js} +2 -2
- package/dist/assets/{mobile-EK9oTupb.js → mobile-B4vLFgBc.js} +2 -2
- package/dist/assets/{nativeFileSave-Bhafll_7.js → nativeFileSave-DpBH1Sa3.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-BoN1cyoG.js → pi-session-focus-preference-BrB72skF.js} +3 -3
- package/dist/assets/{renderDiffWithHighlighter-DixZh5Zd.js → renderDiffWithHighlighter-B6T04JGG.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-CX10w321.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-s6fQq9eg.js → renderFileWithHighlighter-DtAcGyJr.js} +1 -1
- package/dist/assets/renderMobileApp-C9n-BhPZ.js +11 -0
- package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +62 -0
- package/dist/assets/{runtimeSurface-CJN1oo_1.js → runtimeSurface-DiP2a57a.js} +1 -1
- package/dist/assets/useAppFontEffects-Oyin3dgQ.js +215 -0
- package/dist/assets/useGitHubRemoteSearch-CZ9Hauw0.js +1 -0
- package/dist/assets/useSwitcherItems-BSqDA1IF.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js → vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js} +1 -1
- package/dist/assets/{vendor-base-ui-C7vVMZTg.js → vendor-base-ui-BCqPBzDj.js} +1 -1
- package/dist/assets/{vendor-boot-CoTxysn6.js → vendor-boot-3SaHYVb1.js} +18 -18
- package/dist/assets/{vendor-capacitor-app-NX6DULfp.js → vendor-capacitor-app-NbQ-WiPS.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-DJD81I9f.js → vendor-capacitor-keyboard-CgrHt8iN.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-DV24OoQV.js → vendor-capacitor-status-bar-CWt0OF5t.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-qsuH4Dh-.js → vendor-codemirror-autocomplete-WThuuUAz.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-ZHWyBf7j.js → vendor-codemirror-lang-angular-BbLGCxF6.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-pCTOmv-k.js → vendor-codemirror-lang-cpp-Cceks-9O.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-2bFuyM70.js → vendor-codemirror-lang-css-D1wpUg3Z.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-DrG_c7D7.js → vendor-codemirror-lang-go-Cv0zXHHM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-BV8lrR8v.js → vendor-codemirror-lang-html-DbL8oT9H.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-DrsvH6T2.js → vendor-codemirror-lang-java-CNugenuC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Dkzl3s07.js → vendor-codemirror-lang-javascript-Bx_FIyZF.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-8Nn3bnoP.js → vendor-codemirror-lang-jinja-DDGjB3Zq.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-CsdmtHhi.js → vendor-codemirror-lang-json-DIvqf9Pb.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-DJuZ4cZe.js → vendor-codemirror-lang-less-D8r9dGG1.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-D2RO-Pzr.js → vendor-codemirror-lang-liquid-B24mguYi.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-C0Zu3b3n.js → vendor-codemirror-lang-markdown-v3yG2sbf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-CuDtt2Zj.js → vendor-codemirror-lang-php-BcZGalqy.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-Cv2exx_M.js → vendor-codemirror-lang-python-b-JqEwQy.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-C4TxJ6Rg.js → vendor-codemirror-lang-rust-B1uZxDW-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-BmtPz8kf.js → vendor-codemirror-lang-sass-DqPrngKp.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-BF1ZaXqJ.js → vendor-codemirror-lang-sql-UyCnpt-k.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-DZgXrP2k.js → vendor-codemirror-lang-vue-xDwYkovV.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-DsnaGtL_.js → vendor-codemirror-lang-wast-CF3169p_.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-D8DzzFat.js → vendor-codemirror-lang-xml-FCtVhuOb.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-D5hBv7m6.js → vendor-codemirror-lang-yaml-g0sPmAnv.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-vn2RyN9T.js → vendor-codemirror-language-data-B03xgzP2.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-BVCYIV0D.js → vendor-codemirror-search-Dw3Wpu15.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-vqXSn3lv.js → vendor-lezer-cpp-Cu3E-KUI.js} +1 -1
- package/dist/assets/{vendor-lezer-css-JnEzSyZR.js → vendor-lezer-css-Cb8vp67u.js} +1 -1
- package/dist/assets/{vendor-lezer-go-dD2gQMIL.js → vendor-lezer-go-BTsIaOm7.js} +1 -1
- package/dist/assets/{vendor-lezer-html-Cr3U-1pu.js → vendor-lezer-html-UQMsUwj-.js} +1 -1
- package/dist/assets/{vendor-lezer-java-CRM0IMCo.js → vendor-lezer-java-BIWrFrAx.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-B3s21DIS.js → vendor-lezer-javascript-BH2Etgoy.js} +1 -1
- package/dist/assets/{vendor-lezer-json-DPFM6EBV.js → vendor-lezer-json-CE-QUCwM.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-Bllrq8hY.js → vendor-lezer-lr-HY6Yc0Vr.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-6-3PLvXG.js → vendor-lezer-markdown-xFL3Evwf.js} +1 -1
- package/dist/assets/{vendor-lezer-php-DOyzfHRl.js → vendor-lezer-php-Cr_mQGrG.js} +1 -1
- package/dist/assets/{vendor-lezer-python-CdHdN5qt.js → vendor-lezer-python-BNRFWCb0.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-CqnW8EMH.js → vendor-lezer-rust-BvfOK5cU.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-BbcF4y6A.js → vendor-lezer-sass-qoxiLisk.js} +1 -1
- package/dist/assets/{vendor-lezer-xml-C31AyWoo.js → vendor-lezer-xml--x8SSpqU.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-Cv908yC2.js → vendor-lezer-yaml-BDo1JaEr.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-Cwhyn_5f.js → vendor-replit-codemirror-vim-D1Fe7FiY.js} +1 -1
- package/dist/assets/{web-components-Bz5oGa3p.js → web-components-CkTNGkJ2.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/git/DOCUMENTATION.md +1 -0
- package/server/lib/git/routes.js +14 -0
- package/server/lib/git/routes.test.js +37 -0
- package/server/lib/git/service.js +27 -0
- package/server/lib/git/service.test.js +32 -0
- package/server/lib/pi/archive-store.js +38 -10
- package/server/lib/pi/archive-store.test.js +10 -0
- package/server/lib/pi/routes.js +107 -2
- package/server/lib/pi/routes.test.js +255 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -1
- package/server/lib/pi/session-daemon/session-daemon-engines.test.js +18 -0
- package/server/lib/pi/session-daemon/session-daemon.js +24 -1
- package/server/lib/pi/session-shelf-store.js +252 -0
- package/server/lib/pi/session-shelf-store.test.js +174 -0
- package/server/lib/pi/ui-settings-store.js +60 -0
- package/server/lib/pi/ui-settings-store.test.js +105 -6
- package/dist/assets/DiffView-CFIjN2zy.js +0 -18
- package/dist/assets/FilesView-D0b2mEKA.js +0 -6
- package/dist/assets/GitHubListPrimitives-Dw5LAmzm.js +0 -1
- package/dist/assets/GitView-Dhr7qVeI.js +0 -9
- package/dist/assets/IssuesSurface-Bya7OsRl.js +0 -7
- package/dist/assets/MarkdownRendererImpl-DadkFPCz.js +0 -12
- package/dist/assets/PullRequestsSurface-D8JpzP5l.js +0 -2
- package/dist/assets/SessionSwitcherContent-CJ6C2ZKG.js +0 -1
- package/dist/assets/SessionUnreadDot-I1_tmqY9.js +0 -1
- package/dist/assets/SettingsView-B-b76XDV.js +0 -6
- package/dist/assets/gitStatusPredicates-BQOqDJU1.js +0 -1
- package/dist/assets/index-C2ISrmRR.js +0 -11
- package/dist/assets/index-DgwThEwf.css +0 -1
- package/dist/assets/main-DoVzQV56.js +0 -137
- package/dist/assets/renderElectronMiniChatApp-0MqKeGfI.js +0 -2
- package/dist/assets/renderMobileApp-BLoXL_J8.js +0 -11
- package/dist/assets/runtimeEndpointReset-Bv2Y1fMm.js +0 -62
- package/dist/assets/useAppFontEffects-D2xXdmYC.js +0 -215
- package/dist/assets/useFilesViewSearch-BKotcAUN.js +0 -7
- package/dist/assets/useGitHubRemoteSearch-CZ92xKSw.js +0 -1
- package/dist/assets/useSwitcherItems-BfA4omGb.js +0 -1
|
@@ -45,6 +45,14 @@ describe('Pi runtime route', () => {
|
|
|
45
45
|
expect(projectEventFrame(frame({ url: 'http://x.test', attributed: false, createdAt: 1 }))).toBeNull();
|
|
46
46
|
});
|
|
47
47
|
|
|
48
|
+
it('projects archive changes and drops malformed ones', () => {
|
|
49
|
+
const frame = (payload) => ({ protocolVersion: 1, kind: 'event', event: 'session.archive', sequence: 3, payload: { sessionId: 's-1', directory: '/workspace', ...payload } });
|
|
50
|
+
expect(projectEventFrame(frame({ archived: true }))).toEqual({
|
|
51
|
+
protocolVersion: 1, kind: 'event', name: 'session.archive', sequence: 3, sessionId: 's-1', directory: '/workspace', payload: { archived: true },
|
|
52
|
+
});
|
|
53
|
+
expect(projectEventFrame(frame({ archived: 'yes' }))).toBeNull();
|
|
54
|
+
});
|
|
55
|
+
|
|
48
56
|
it('projects prompt-time files on a live user message start', () => {
|
|
49
57
|
expect(projectEventFrame({
|
|
50
58
|
protocolVersion: 1,
|
|
@@ -1546,6 +1554,250 @@ describe('Pi runtime route', () => {
|
|
|
1546
1554
|
}
|
|
1547
1555
|
});
|
|
1548
1556
|
|
|
1557
|
+
it('serves the session shelf, checks membership on writes, and clears it when the user sends', async () => {
|
|
1558
|
+
const calls = [];
|
|
1559
|
+
const session = { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 };
|
|
1560
|
+
let shelf = { 'pi-session-7': { snoozedUntil: 9_000, snoozedAt: 3 } };
|
|
1561
|
+
const sessionShelfStore = {
|
|
1562
|
+
read: async () => shelf,
|
|
1563
|
+
update: async (sessionId, patch) => {
|
|
1564
|
+
calls.push({ command: 'shelf.update', payload: [sessionId, patch] });
|
|
1565
|
+
return { snoozedUntil: 12_000, snoozedAt: 4 };
|
|
1566
|
+
},
|
|
1567
|
+
clearForActivity: async (sessionId) => {
|
|
1568
|
+
calls.push({ command: 'shelf.clear', payload: sessionId });
|
|
1569
|
+
shelf = {};
|
|
1570
|
+
return null;
|
|
1571
|
+
},
|
|
1572
|
+
remove: async (sessionId) => calls.push({ command: 'shelf.remove', payload: sessionId }),
|
|
1573
|
+
};
|
|
1574
|
+
const runtime = {
|
|
1575
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1576
|
+
request: async (command, payload) => {
|
|
1577
|
+
calls.push({ command, payload });
|
|
1578
|
+
if (command === 'sessions.list') return { sessions: [{ session, updatedAt: 2 }] };
|
|
1579
|
+
if (command === 'sessions.prompt') return { accepted: true, messageId: 'message-1' };
|
|
1580
|
+
if (command === 'sessions.bash') return { accepted: true, id: 'bash-1' };
|
|
1581
|
+
return {};
|
|
1582
|
+
},
|
|
1583
|
+
};
|
|
1584
|
+
const app = express();
|
|
1585
|
+
app.use(express.json());
|
|
1586
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) }, sessionShelfStore });
|
|
1587
|
+
server = await listen(app);
|
|
1588
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1589
|
+
const post = (path, body) => fetch(`${origin}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1590
|
+
|
|
1591
|
+
await expect((await fetch(`${origin}/api/pi/session-shelf`)).json()).resolves.toEqual({ sessions: { 'pi-session-7': { snoozedUntil: 9_000, snoozedAt: 3 } } });
|
|
1592
|
+
|
|
1593
|
+
const updated = await post('/api/pi/sessions/pi-session-7/shelf', { snoozedUntil: 12_000, directory: '/workspace' });
|
|
1594
|
+
expect(updated.status).toBe(200);
|
|
1595
|
+
await expect(updated.json()).resolves.toEqual({ entry: { snoozedUntil: 12_000, snoozedAt: 4 } });
|
|
1596
|
+
expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/workspace' } });
|
|
1597
|
+
expect(calls).toContainEqual({ command: 'shelf.update', payload: ['pi-session-7', { snoozedUntil: 12_000 }] });
|
|
1598
|
+
|
|
1599
|
+
expect((await post('/api/pi/sessions/missing/shelf', { snoozedUntil: 12_000 })).status).toBe(404);
|
|
1600
|
+
expect((await post('/api/pi/sessions/pi-session-7/shelf', {})).status).toBe(400);
|
|
1601
|
+
expect((await post('/api/pi/sessions/pi-session-7/shelf', { settled: 'done' })).status).toBe(400);
|
|
1602
|
+
expect((await post('/api/pi/sessions/pi-session-7/shelf', { snoozedUntil: 'tomorrow' })).status).toBe(400);
|
|
1603
|
+
expect(calls.filter((call) => call.command === 'shelf.update')).toHaveLength(1);
|
|
1604
|
+
|
|
1605
|
+
expect((await post('/api/pi/sessions/pi-session-7/prompt', { text: 'hello', streamEpoch: 'epoch-routes' })).status).toBe(202);
|
|
1606
|
+
expect((await post('/api/pi/sessions/pi-session-7/bash', { command: 'ls' })).status).toBe(202);
|
|
1607
|
+
expect(calls.filter((call) => call.command === 'shelf.clear')).toEqual([
|
|
1608
|
+
{ command: 'shelf.clear', payload: 'pi-session-7' },
|
|
1609
|
+
{ command: 'shelf.clear', payload: 'pi-session-7' },
|
|
1610
|
+
]);
|
|
1611
|
+
expect((await fetch(`${origin}/api/pi/sessions/pi-session-7`, { method: 'DELETE' })).status).toBe(204);
|
|
1612
|
+
expect(calls).toContainEqual({ command: 'shelf.remove', payload: 'pi-session-7' });
|
|
1613
|
+
});
|
|
1614
|
+
|
|
1615
|
+
it('maps a settled shelf write from an older client to an archive, and accepts active or null as no-ops', async () => {
|
|
1616
|
+
const session = { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 };
|
|
1617
|
+
const archiveSets = [];
|
|
1618
|
+
const shelfUpdates = [];
|
|
1619
|
+
const sessionShelfStore = {
|
|
1620
|
+
read: async () => ({ 'pi-session-7': { snoozedUntil: 9_000, snoozedAt: 3 } }),
|
|
1621
|
+
update: async (sessionId, patch) => {
|
|
1622
|
+
shelfUpdates.push([sessionId, patch]);
|
|
1623
|
+
return null;
|
|
1624
|
+
},
|
|
1625
|
+
};
|
|
1626
|
+
const published = [];
|
|
1627
|
+
const runtime = {
|
|
1628
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1629
|
+
request: async (command, payload) => {
|
|
1630
|
+
if (command === 'archive.publish') published.push(payload);
|
|
1631
|
+
return command === 'sessions.list' ? { sessions: [{ session, updatedAt: 2 }] } : {};
|
|
1632
|
+
},
|
|
1633
|
+
};
|
|
1634
|
+
const app = express();
|
|
1635
|
+
app.use(express.json());
|
|
1636
|
+
registerPiRuntimeRoutes(app, {
|
|
1637
|
+
getPiSessionDaemonRuntime: () => runtime,
|
|
1638
|
+
archiveStore: { read: async () => ({}), set: async (...args) => archiveSets.push(args) },
|
|
1639
|
+
sessionShelfStore,
|
|
1640
|
+
});
|
|
1641
|
+
server = await listen(app);
|
|
1642
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1643
|
+
const post = (body) => fetch(`${origin}/api/pi/sessions/pi-session-7/shelf`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1644
|
+
|
|
1645
|
+
const settled = await post({ settled: 'settled', directory: '/workspace' });
|
|
1646
|
+
expect(settled.status).toBe(200);
|
|
1647
|
+
await expect(settled.json()).resolves.toEqual({ entry: { snoozedUntil: 9_000, snoozedAt: 3 } });
|
|
1648
|
+
expect(archiveSets).toEqual([['pi-session-7', true]]);
|
|
1649
|
+
await vi.waitFor(() => expect(published).toEqual([{ sessionId: 'pi-session-7', archived: true, directory: '/workspace' }]));
|
|
1650
|
+
|
|
1651
|
+
for (const value of ['active', null]) {
|
|
1652
|
+
const response = await post({ settled: value });
|
|
1653
|
+
expect(response.status).toBe(200);
|
|
1654
|
+
await expect(response.json()).resolves.toEqual({ entry: { snoozedUntil: 9_000, snoozedAt: 3 } });
|
|
1655
|
+
}
|
|
1656
|
+
expect(archiveSets).toHaveLength(1);
|
|
1657
|
+
expect(shelfUpdates).toEqual([]);
|
|
1658
|
+
|
|
1659
|
+
// A snooze sent alongside a settled value still applies.
|
|
1660
|
+
expect((await post({ settled: null, snoozedUntil: 12_000 })).status).toBe(200);
|
|
1661
|
+
expect(shelfUpdates).toEqual([['pi-session-7', { snoozedUntil: 12_000 }]]);
|
|
1662
|
+
expect((await fetch(`${origin}/api/pi/sessions/missing/shelf`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ settled: 'settled' }) })).status).toBe(404);
|
|
1663
|
+
expect(archiveSets).toHaveLength(1);
|
|
1664
|
+
expect(published).toHaveLength(1);
|
|
1665
|
+
});
|
|
1666
|
+
|
|
1667
|
+
it('unarchives a session when a prompt, steer, follow-up, or shell command is accepted', async () => {
|
|
1668
|
+
const archive = { 'pi-session-7': 5, 'pi-session-8': 6 };
|
|
1669
|
+
const archiveSets = [];
|
|
1670
|
+
const archiveStore = {
|
|
1671
|
+
read: async () => ({ ...archive }),
|
|
1672
|
+
set: async (sessionId, archived) => {
|
|
1673
|
+
archiveSets.push([sessionId, archived]);
|
|
1674
|
+
if (archived) archive[sessionId] = 10;
|
|
1675
|
+
else delete archive[sessionId];
|
|
1676
|
+
},
|
|
1677
|
+
};
|
|
1678
|
+
let accept = true;
|
|
1679
|
+
const published = [];
|
|
1680
|
+
const runtime = {
|
|
1681
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1682
|
+
request: async (command, payload) => {
|
|
1683
|
+
if (command === 'archive.publish') {
|
|
1684
|
+
published.push(payload);
|
|
1685
|
+
return { published: true };
|
|
1686
|
+
}
|
|
1687
|
+
if (command === 'sessions.bash') return accept ? { accepted: true, id: 'bash-1' } : Promise.reject(Object.assign(new Error('nope'), { code: 'INVALID_SESSION' }));
|
|
1688
|
+
if (command === 'sessions.prompt' || command === 'sessions.steer' || command === 'sessions.followUp') {
|
|
1689
|
+
if (!accept) throw Object.assign(new Error('nope'), { code: 'INVALID_SESSION' });
|
|
1690
|
+
return { accepted: true, messageId: 'message-1' };
|
|
1691
|
+
}
|
|
1692
|
+
return {};
|
|
1693
|
+
},
|
|
1694
|
+
};
|
|
1695
|
+
const app = express();
|
|
1696
|
+
app.use(express.json());
|
|
1697
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore, sessionShelfStore: { clearForActivity: async () => null } });
|
|
1698
|
+
server = await listen(app);
|
|
1699
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1700
|
+
const post = (path, body) => fetch(`${origin}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1701
|
+
|
|
1702
|
+
// A rejected send leaves the archive alone.
|
|
1703
|
+
accept = false;
|
|
1704
|
+
expect((await post('/api/pi/sessions/pi-session-7/prompt', { text: 'hello', streamEpoch: 'epoch-routes' })).status).not.toBe(202);
|
|
1705
|
+
expect((await post('/api/pi/sessions/pi-session-7/bash', { command: 'ls' })).status).not.toBe(202);
|
|
1706
|
+
expect(archiveSets).toEqual([]);
|
|
1707
|
+
expect(published).toEqual([]);
|
|
1708
|
+
accept = true;
|
|
1709
|
+
|
|
1710
|
+
expect((await post('/api/pi/sessions/pi-session-7/prompt', { text: 'hello', streamEpoch: 'epoch-routes' })).status).toBe(202);
|
|
1711
|
+
expect(archive).toEqual({ 'pi-session-8': 6 });
|
|
1712
|
+
// The daemon resolves the folder from the resident session.
|
|
1713
|
+
await vi.waitFor(() => expect(published).toEqual([{ sessionId: 'pi-session-7', archived: false }]));
|
|
1714
|
+
// Not archived: no write and nothing to publish.
|
|
1715
|
+
expect((await post('/api/pi/sessions/pi-session-7/steer', { text: 'more', streamEpoch: 'epoch-routes' })).status).toBe(202);
|
|
1716
|
+
expect(archiveSets).toEqual([['pi-session-7', false]]);
|
|
1717
|
+
expect(published).toHaveLength(1);
|
|
1718
|
+
|
|
1719
|
+
for (const [path, body] of [
|
|
1720
|
+
['steer', { text: 'more', streamEpoch: 'epoch-routes' }],
|
|
1721
|
+
['follow-up', { text: 'later', streamEpoch: 'epoch-routes' }],
|
|
1722
|
+
['bash', { command: 'ls' }],
|
|
1723
|
+
]) {
|
|
1724
|
+
archive['pi-session-7'] = 5;
|
|
1725
|
+
expect((await post(`/api/pi/sessions/pi-session-7/${path}`, body)).status).toBe(202);
|
|
1726
|
+
expect(archive).toEqual({ 'pi-session-8': 6 });
|
|
1727
|
+
}
|
|
1728
|
+
expect(archiveSets).toHaveLength(4);
|
|
1729
|
+
});
|
|
1730
|
+
|
|
1731
|
+
it('keeps a send accepted when unarchiving fails', async () => {
|
|
1732
|
+
const runtime = {
|
|
1733
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1734
|
+
request: async (command) => (command === 'sessions.bash' ? { accepted: true, id: 'bash-1' } : { accepted: true, messageId: 'message-1' }),
|
|
1735
|
+
};
|
|
1736
|
+
const archiveStore = {
|
|
1737
|
+
read: async () => ({ 'pi-session-7': 5 }),
|
|
1738
|
+
set: async () => { throw Object.assign(new Error('bad'), { code: 'EIO' }); },
|
|
1739
|
+
};
|
|
1740
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1741
|
+
const app = express();
|
|
1742
|
+
app.use(express.json());
|
|
1743
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore, sessionShelfStore: { clearForActivity: async () => null } });
|
|
1744
|
+
server = await listen(app);
|
|
1745
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1746
|
+
const prompt = await fetch(`${origin}/api/pi/sessions/pi-session-7/prompt`, {
|
|
1747
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'hello', streamEpoch: 'epoch-routes' }),
|
|
1748
|
+
});
|
|
1749
|
+
expect(prompt.status).toBe(202);
|
|
1750
|
+
const bash = await fetch(`${origin}/api/pi/sessions/pi-session-7/bash`, {
|
|
1751
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'ls' }),
|
|
1752
|
+
});
|
|
1753
|
+
expect(bash.status).toBe(202);
|
|
1754
|
+
expect(warn).toHaveBeenCalledTimes(2);
|
|
1755
|
+
warn.mockRestore();
|
|
1756
|
+
});
|
|
1757
|
+
|
|
1758
|
+
it('keeps an archive change when the daemon cannot publish it', async () => {
|
|
1759
|
+
const runtime = {
|
|
1760
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1761
|
+
request: async (command) => {
|
|
1762
|
+
if (command === 'sessions.list') return { sessions: [{ session: { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 }, updatedAt: 2 }] };
|
|
1763
|
+
if (command === 'archive.publish') throw Object.assign(new Error('old daemon'), { code: 'UNKNOWN_COMMAND' });
|
|
1764
|
+
return {};
|
|
1765
|
+
},
|
|
1766
|
+
};
|
|
1767
|
+
const archiveSets = [];
|
|
1768
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1769
|
+
const app = express();
|
|
1770
|
+
app.use(express.json());
|
|
1771
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}), set: async (...args) => archiveSets.push(args) } });
|
|
1772
|
+
server = await listen(app);
|
|
1773
|
+
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-7/archive`, {
|
|
1774
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived: true }),
|
|
1775
|
+
});
|
|
1776
|
+
expect(response.status).toBe(204);
|
|
1777
|
+
expect(archiveSets).toEqual([['pi-session-7', true]]);
|
|
1778
|
+
await vi.waitFor(() => expect(warn).toHaveBeenCalled());
|
|
1779
|
+
warn.mockRestore();
|
|
1780
|
+
});
|
|
1781
|
+
|
|
1782
|
+
it('keeps a send accepted when clearing the shelf fails', async () => {
|
|
1783
|
+
const runtime = {
|
|
1784
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1785
|
+
request: async (command) => (command === 'sessions.prompt' ? { accepted: true, messageId: 'message-1' } : {}),
|
|
1786
|
+
};
|
|
1787
|
+
const sessionShelfStore = { clearForActivity: async () => { throw Object.assign(new Error('bad'), { code: 'SESSION_SHELF_INVALID' }); } };
|
|
1788
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1789
|
+
const app = express();
|
|
1790
|
+
app.use(express.json());
|
|
1791
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) }, sessionShelfStore });
|
|
1792
|
+
server = await listen(app);
|
|
1793
|
+
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-7/prompt`, {
|
|
1794
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'hello', streamEpoch: 'epoch-routes' }),
|
|
1795
|
+
});
|
|
1796
|
+
expect(response.status).toBe(202);
|
|
1797
|
+
expect(warn).toHaveBeenCalled();
|
|
1798
|
+
warn.mockRestore();
|
|
1799
|
+
});
|
|
1800
|
+
|
|
1549
1801
|
it('creates a session and projects the created detail like a session read', async () => {
|
|
1550
1802
|
const calls = [];
|
|
1551
1803
|
let created;
|
|
@@ -1655,6 +1907,8 @@ describe('Pi runtime route', () => {
|
|
|
1655
1907
|
expect((await fetch(base, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived: true, directory: '/other' }) })).status).toBe(204);
|
|
1656
1908
|
expect(archiveSets).toEqual([['foreign-1', true]]);
|
|
1657
1909
|
expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/other' } });
|
|
1910
|
+
// Every device hears about it, on the session's own folder.
|
|
1911
|
+
await vi.waitFor(() => expect(calls).toContainEqual({ command: 'archive.publish', payload: { sessionId: 'foreign-1', archived: true, directory: '/other' } }));
|
|
1658
1912
|
|
|
1659
1913
|
// Wrong directory fails membership without writing the sidecar.
|
|
1660
1914
|
calls.length = 0;
|
|
@@ -1663,6 +1917,7 @@ describe('Pi runtime route', () => {
|
|
|
1663
1917
|
expect(wrong.status).not.toBe(204);
|
|
1664
1918
|
expect(archiveSets).toEqual([]);
|
|
1665
1919
|
expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/focused' } });
|
|
1920
|
+
expect(calls.some((call) => call.command === 'archive.publish')).toBe(false);
|
|
1666
1921
|
});
|
|
1667
1922
|
|
|
1668
1923
|
it('projects daemon file parts for image and attachment history instead of failing the session open', async () => {
|
|
@@ -34,7 +34,11 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
34
34
|
- `../server/server-profile.js` derives one stable daemon profile per server: installed web is `web-p<port>`, development web is `web-dev-p<port>`, installed desktop is `desktop`, and development desktop is `desktop-dev`. `PICHAMBER_SERVER_PROFILE` overrides the derivation with a hashed `custom-<hash>` key so raw input never becomes a path, while preserving whether the launcher is a development build for stale-code replacement. The profile key is stable across restarts; the server instance id is a fresh UUID per launch. Development launchers (`scripts/dev-web-hmr.mjs`, `scripts/dev-web-full.mjs`, `cross-env` in the `dev:server` scripts, `PICHAMBER_ELECTRON_DEV`) explicitly mark themselves so stopping development can never terminate the installed daemon.
|
|
35
35
|
- `../server/cross-process-lock.js` serializes critical sections across servers sharing one data directory (exclusive create, owner nonce, dead-pid steal, bounded wait). It backs the daemon operation lock pattern and every shared read-modify-write store below.
|
|
36
36
|
- `session-lease.js` owns exclusive cross-daemon residency of one Pi session, keyed by canonical agent directory, cwd, and session id under `<agentDir>/.pichamber/locks/sessions/`. The lease is acquired before a resident `AgentSessionRuntime` is created and released after idle disposal, deletion, replacement, or daemon shutdown. Opening or deleting a session leased by another live daemon returns `SESSION_IN_USE` (HTTP 409) while the session stays visible in listings; different sessions remain fully concurrent. Lease files from different `PICHAMBER_DATA_DIR` values still coordinate because they live under the shared agent directory.
|
|
37
|
-
- `../
|
|
37
|
+
- `../session-shelf-store.js` holds sidebar snooze only (`snoozedUntil` / `snoozedAt`) in `<dataDir>/pi/session-shelf.json`; `POST /api/pi/sessions/:id/shelf` accepts only a snooze patch and answers `{ entry }`. Files written before Archive replaced Settle migrate on first read or write under the shelf lock: a `settled` mark becomes an archive at its `settledAt` (an existing archive time is kept) and an `active` mark is dropped. The archive file is written first through `archive-store.js` `archiveMissing`; if that write fails, the migration retries on the next read or write. Until it succeeds, reads return the snooze-only view and snooze writes still go through, with every unmigrated settled mark written back unchanged. A send (`clearForActivity`) or a delete (`remove`) also drops that session's settled mark, so the retried migration never archives a session the user just used. Older clients that still send `settled: 'settled'` archive the session; `'active'` and `null` are no-ops. The older-client mapping is removed one release later.
|
|
38
|
+
- Unarchive on send: an accepted (202) prompt, steer, follow-up, or bash request clears the session's snooze and its archive mark (`bringBackForActivity` in `routes.js`), so a session you return to rejoins the active list. A failed write there is logged and the request still answers 202.
|
|
39
|
+
- Archive changes reach every device: after the archive route, the older-client `settled: 'settled'` shelf write, or an unarchive on send saves the mark, `routes.js` asks the daemon to publish it (`archive.publish`, private, server-only, `{ sessionId, archived, directory? }`; without a directory the daemon uses the resident session's cwd). The daemon publishes `session.archive` (`{ archived }`) on that session's stream, which every subscriber receives. It is a signal, not state: a client whose catalog row disagrees re-lists that folder (coalesced per folder), and the archive store stays the authority. The request is fire-and-forget; a failure (such as an older daemon) only logs, and devices catch up on their next list.
|
|
40
|
+
- Retention settings migration (`ui-settings-store.js`): `sessionAutoArchiveAfterDays` and `sessionAutoDeleteAfterDays` are portable integers 0 to 365 (0 is off). When either is missing or invalid in `settings.json`, the store decides both once, under the read lock, before any write: a new install (no allowlisted field in `settings.json` and no local field in `runtime-state.json`) gets 7 and 0; an existing install maps the old fields (off or missing to 0 and 0, on with archive N to N and 0, on with delete N to N and 30; a missing action means archive, a missing or invalid N means 30, clamped 1 to 365). The old fields (`autoDeleteEnabled`, `autoDeleteAfterDays`, `sessionRetentionAction`, `sidebarAutoSettleAfterDays`) stay allowlisted but unread until a later release removes them. The passes themselves run in the client (`useSessionAutoCleanup`); there is no server-side auto-archive.
|
|
41
|
+
- `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `POST /api/pi/sessions` projects the created detail through the same session-detail projector as `GET /api/pi/sessions/:id`, so extension items appended from `session_start`, the `streamEpoch` stamp, and extension UI snapshot state are returned rather than rejected; only a malformed detail is `DAEMON_PROTOCOL_MISMATCH`. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` owns portable PiChamber preferences at data-root `settings.json` and host, device, and secret-bearing values at `runtime-state.json`. `/api/pi/ui-settings` merges both views for existing clients and splits writes through explicit field allowlists. It migrates an unscoped flat file once; after the portable scope marker exists, local fields found in `settings.json` are ignored rather than applied to the host. The route is not available through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `session-shelf-store.js` persists PiChamber-only sidebar shelf state (a snooze wake time and its start) per session id at data-root `pi/session-shelf.json`, read through `GET /api/pi/session-shelf` and changed through `POST /api/pi/sessions/:id/shelf`, which checks that the session exists like archive does. Archive replaced Settle: a shelf file that still holds `settled` marks is migrated once under the shelf lock, archiving hand-settled sessions at their `settledAt` (already archived sessions keep their time) and dropping the settled fields. The archive file is written first; if that write fails, reads still answer with the snooze state, snooze writes still go through with every unmigrated settled mark written back unchanged, and the next read or write retries. Until one release later the shelf route maps `settled: 'settled'` from an older client to an archive and accepts `'active'` and `null` as no-ops. A prompt, steer, follow-up, or `!` command the daemon accepts clears that session's snooze and unarchives it, and deleting a session removes its entry; a failed shelf or archive write after a successful send only logs and the send still answers `202`. The sending client clears `archived` optimistically. Every archive change, including this unarchive, is then published as `session.archive` (see Archive changes reach every device above); a client also re-lists the folder when it sees a send's user message or `session.bash` event for a session it holds as archived, which covers a failed publish. A malformed file is `SESSION_SHELF_INVALID`, never an empty shelf. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
|
|
38
42
|
- `../event-stream.js` owns the `/api/pi/events` SSE connection lifecycle so `../routes.js` stays a thin adapter. Per connection it installs cleanup before `subscribe` is awaited (a client that leaves during the opening window cannot leak a daemon subscription; a late subscription is closed exactly once), funnels client disconnect, subscription error, and server shutdown through one idempotent cleanup, hands an `AbortSignal` through the supervisor to the private IPC subscriber, never writes a named heartbeat or a late frame to a dead response, and byte-bounds the response socket buffer (`res.writableLength`, default 8 MiB, aligned with the daemon replay budget) with the bound enforced BEFORE each write so no single frame overshoots it. A client that stops reading is disconnected recoverably — the stream ends and the client reconnects from its last accepted sequence for replay or an authoritative snapshot, so no event is silently removed from an otherwise contiguous stream, but frames still buffered when the disconnect fires are not promised as delivered; the reconnect replay is the delivery guarantee — while a healthy client's connection stays independent of the slow one. Every teardown is bounded: a `write()` that returns false starts a drain deadline (default 5s) that ends even a quiet never-draining client, and after `res.end()` a terminate deadline (default 5s) destroys the response, because `end()` alone only queues the FIN behind unflushed data and would otherwise leave a stalled socket open forever and hang server shutdown/close. The response `'error'` guard stays attached for the response's lifetime (idempotent; cleanup can complete while data is still in flight and a late unhandled `'error'` would crash the process). The registry tracks live connections so `registerPiRuntimeRoutes` can expose `closeEventStreams()` for server shutdown, ending active and still-opening streams (and their daemon subscriptions) before the HTTP server closes. The IPC subscriber removes its abort listener and destroys the opening or active daemon socket on cancellation.
|
|
39
43
|
- `*.test.js` uses temporary cwd, agent, data, and runtime directories; it never loads a developer's Pi home, credentials, or sessions. On Windows the private endpoint is a named pipe, not a `.sock` file, and POSIX mode-bit assertions are skipped.
|
|
40
44
|
|
|
@@ -626,6 +626,24 @@ describe('session daemon engines', () => {
|
|
|
626
626
|
expect(result.result).toEqual({ published: false });
|
|
627
627
|
});
|
|
628
628
|
|
|
629
|
+
it('publishes archive changes to every subscriber', async () => {
|
|
630
|
+
const { root } = await startDaemon({});
|
|
631
|
+
const health = await send('runtime.health');
|
|
632
|
+
expect(health.result.capabilities).toContain('archive.publish');
|
|
633
|
+
await expect(send('archive.publish', { sessionId: '', archived: true })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
|
|
634
|
+
await expect(send('archive.publish', { sessionId: 'a', archived: 'yes' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
|
|
635
|
+
|
|
636
|
+
const subscriber = connectClient(currentEndpoint);
|
|
637
|
+
await subscriber.authenticate();
|
|
638
|
+
const seen = subscriber.next((message) => message.kind === 'event' && message.event === 'session.archive');
|
|
639
|
+
const result = await send('archive.publish', { sessionId: 'archived-1', archived: true, directory: root });
|
|
640
|
+
expect(result.result).toEqual({ published: true });
|
|
641
|
+
const event = await seen;
|
|
642
|
+
expect(event.payload).toEqual({ sessionId: 'archived-1', directory: root, archived: true });
|
|
643
|
+
expect(Number.isSafeInteger(event.sequence)).toBe(true);
|
|
644
|
+
await subscriber.close().catch(() => {});
|
|
645
|
+
});
|
|
646
|
+
|
|
629
647
|
it('advertises sessions.pendingInput in runtime.health', async () => {
|
|
630
648
|
await startDaemon({});
|
|
631
649
|
const health = await send('runtime.health');
|
|
@@ -4333,7 +4333,7 @@ export function createSessionDaemon({
|
|
|
4333
4333
|
'providers.login.respond', 'providers.login.status', 'providers.logout', 'settings.get', 'settings.set',
|
|
4334
4334
|
'resources.list', 'resources.update', 'resources.prompts.create', 'resources.prompts.update', 'resources.prompts.delete',
|
|
4335
4335
|
'extensions.list', 'extensions.respond', 'extensions.draft',
|
|
4336
|
-
'openUrl.publish',
|
|
4336
|
+
'openUrl.publish', 'archive.publish',
|
|
4337
4337
|
'extensions.custom.input', 'extensions.custom.viewport', 'extensions.custom.close', 'extensions.custom.focus', 'extensions.custom.refresh',
|
|
4338
4338
|
],
|
|
4339
4339
|
...(Number.isInteger(healthMetadata.daemonPid) ? { daemonPid: healthMetadata.daemonPid } : {}),
|
|
@@ -4588,6 +4588,29 @@ export function createSessionDaemon({
|
|
|
4588
4588
|
});
|
|
4589
4589
|
return;
|
|
4590
4590
|
}
|
|
4591
|
+
case 'archive.publish': {
|
|
4592
|
+
// The PiChamber server changed a session's archive mark (its own
|
|
4593
|
+
// metadata, not Pi state). Publishing it on the session's stream
|
|
4594
|
+
// tells every device to re-list that folder; the server's archive
|
|
4595
|
+
// store stays the authority.
|
|
4596
|
+
const sessionId = message.payload?.sessionId;
|
|
4597
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 256 || typeof message.payload?.archived !== 'boolean') {
|
|
4598
|
+
throw new SessionDaemonProtocolError('INVALID_ARGUMENT', 'A session id and an archived flag are required.');
|
|
4599
|
+
}
|
|
4600
|
+
const requestedDirectory = typeof message.payload?.directory === 'string' && message.payload.directory.length > 0 && message.payload.directory.length <= 4096
|
|
4601
|
+
? message.payload.directory
|
|
4602
|
+
: undefined;
|
|
4603
|
+
const residentCwd = runtimeRegistry?.findBySessionId?.(sessionId)?.cwd;
|
|
4604
|
+
const directory = requestedDirectory ?? (typeof residentCwd === 'string' && residentCwd.length > 0 ? residentCwd : undefined);
|
|
4605
|
+
publish('session.archive', { archived: message.payload.archived }, sessionId, directory);
|
|
4606
|
+
writeFrame(socket, {
|
|
4607
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
4608
|
+
kind: 'response',
|
|
4609
|
+
requestId: message.requestId,
|
|
4610
|
+
result: { published: true },
|
|
4611
|
+
});
|
|
4612
|
+
return;
|
|
4613
|
+
}
|
|
4591
4614
|
case 'openUrl.publish': {
|
|
4592
4615
|
// An Open request from the PiChamber server's intake. Not
|
|
4593
4616
|
// session-scoped on input: the daemon attributes it and publishes a
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
|
|
5
|
+
import { withCrossProcessLock } from '../server/cross-process-lock.js';
|
|
6
|
+
|
|
7
|
+
const MAX_FILE_BYTES = 4 * 1024 * 1024;
|
|
8
|
+
const MAX_SESSION_ID_LENGTH = 512;
|
|
9
|
+
const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
|
|
10
|
+
|
|
11
|
+
const invalidShelf = () => {
|
|
12
|
+
const error = new Error('Pi session shelf metadata is invalid.');
|
|
13
|
+
error.code = 'SESSION_SHELF_INVALID';
|
|
14
|
+
return error;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const invalidArgument = () => {
|
|
18
|
+
const error = new Error('The session shelf request is invalid.');
|
|
19
|
+
error.code = 'INVALID_ARGUMENT';
|
|
20
|
+
return error;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
24
|
+
const isTimestamp = (value) => Number.isSafeInteger(value) && value > 0;
|
|
25
|
+
const isSessionId = (value) => typeof value === 'string' && value.length > 0
|
|
26
|
+
&& value.length <= MAX_SESSION_ID_LENGTH && !FORBIDDEN_KEYS.has(value);
|
|
27
|
+
|
|
28
|
+
// One session's stored entry, or null when it holds nothing. A snooze
|
|
29
|
+
// travels with its start time. Files written before Archive replaced Settle
|
|
30
|
+
// may also carry `settled` ('settled' with its `settledAt`, or 'active');
|
|
31
|
+
// those fields are kept here only so the migration can read them.
|
|
32
|
+
const validateStoredEntry = (value) => {
|
|
33
|
+
if (!isRecord(value)) throw invalidShelf();
|
|
34
|
+
const entry = {};
|
|
35
|
+
if (value.settled !== undefined) {
|
|
36
|
+
if (value.settled === 'settled') {
|
|
37
|
+
if (!isTimestamp(value.settledAt)) throw invalidShelf();
|
|
38
|
+
entry.settled = 'settled';
|
|
39
|
+
entry.settledAt = value.settledAt;
|
|
40
|
+
} else if (value.settled === 'active') {
|
|
41
|
+
entry.settled = 'active';
|
|
42
|
+
} else {
|
|
43
|
+
throw invalidShelf();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (value.snoozedUntil !== undefined) {
|
|
47
|
+
if (!isTimestamp(value.snoozedUntil) || !isTimestamp(value.snoozedAt)) throw invalidShelf();
|
|
48
|
+
entry.snoozedUntil = value.snoozedUntil;
|
|
49
|
+
entry.snoozedAt = value.snoozedAt;
|
|
50
|
+
}
|
|
51
|
+
return Object.keys(entry).length > 0 ? entry : null;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const validateStoredShelf = (value) => {
|
|
55
|
+
if (!isRecord(value)) throw invalidShelf();
|
|
56
|
+
const shelf = {};
|
|
57
|
+
for (const [sessionId, raw] of Object.entries(value)) {
|
|
58
|
+
if (!isSessionId(sessionId)) throw invalidShelf();
|
|
59
|
+
const entry = validateStoredEntry(raw);
|
|
60
|
+
if (entry) shelf[sessionId] = entry;
|
|
61
|
+
}
|
|
62
|
+
return shelf;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const hasLegacySettled = (shelf) => Object.values(shelf).some((entry) => entry.settled !== undefined);
|
|
66
|
+
|
|
67
|
+
// The shelf without the retired settled fields; entries left empty go.
|
|
68
|
+
const withoutSettled = (shelf) => {
|
|
69
|
+
const next = {};
|
|
70
|
+
for (const [sessionId, entry] of Object.entries(shelf)) {
|
|
71
|
+
if (entry.snoozedUntil === undefined) continue;
|
|
72
|
+
next[sessionId] = { snoozedUntil: entry.snoozedUntil, snoozedAt: entry.snoozedAt };
|
|
73
|
+
}
|
|
74
|
+
return next;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// The snooze-only shelf with the settled fields from `stored` put back, for
|
|
78
|
+
// a write while the migration is still pending. `dropSessionId` loses its
|
|
79
|
+
// settled mark.
|
|
80
|
+
const withSettledKept = (shelf, stored, dropSessionId) => {
|
|
81
|
+
const next = {};
|
|
82
|
+
for (const sessionId of new Set([...Object.keys(stored), ...Object.keys(shelf)])) {
|
|
83
|
+
const entry = {};
|
|
84
|
+
const legacy = stored[sessionId];
|
|
85
|
+
if (legacy?.settled !== undefined && sessionId !== dropSessionId) {
|
|
86
|
+
entry.settled = legacy.settled;
|
|
87
|
+
if (legacy.settled === 'settled') entry.settledAt = legacy.settledAt;
|
|
88
|
+
}
|
|
89
|
+
if (shelf[sessionId]) Object.assign(entry, shelf[sessionId]);
|
|
90
|
+
if (Object.keys(entry).length > 0) next[sessionId] = entry;
|
|
91
|
+
}
|
|
92
|
+
return next;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* PiChamber-owned sidebar shelf metadata: when a snoozed session wakes. Like
|
|
97
|
+
* the archive sidecar, it is keyed only by opaque Pi session IDs, leaves Pi
|
|
98
|
+
* JSONL untouched, and every write is atomic under a cross-process lock.
|
|
99
|
+
*
|
|
100
|
+
* - `snoozedUntil` hides a session until that time; `null` wakes it.
|
|
101
|
+
* - `clearForActivity` drops the snooze when the user sends to the session.
|
|
102
|
+
*
|
|
103
|
+
* Settle was replaced by Archive. A file that still holds settled marks is
|
|
104
|
+
* migrated once, under the shelf lock: hand-settled sessions are archived at
|
|
105
|
+
* their settle time (sessions already archived keep theirs), the archive
|
|
106
|
+
* file is written first, then the shelf file without the settled fields. If
|
|
107
|
+
* the archive write fails, the migration runs again on the next read or
|
|
108
|
+
* write. Until then reads answer with the snooze state, and snooze writes
|
|
109
|
+
* still go through with every settled mark left in the file. A send or a
|
|
110
|
+
* delete drops that one session's settled mark, so the retried migration
|
|
111
|
+
* never archives a session the user just used.
|
|
112
|
+
*/
|
|
113
|
+
export const createPiSessionShelfStore = ({
|
|
114
|
+
file = join(resolvePiChamberDataDir(), 'pi', 'session-shelf.json'),
|
|
115
|
+
now = () => Date.now(),
|
|
116
|
+
archiveStore,
|
|
117
|
+
} = {}) => {
|
|
118
|
+
let writeChain = Promise.resolve();
|
|
119
|
+
|
|
120
|
+
const readStored = async () => {
|
|
121
|
+
let raw;
|
|
122
|
+
try {
|
|
123
|
+
raw = await readFile(file, 'utf8');
|
|
124
|
+
} catch (error) {
|
|
125
|
+
if (error?.code === 'ENOENT') return {};
|
|
126
|
+
throw invalidShelf();
|
|
127
|
+
}
|
|
128
|
+
if (Buffer.byteLength(raw) > MAX_FILE_BYTES) throw invalidShelf();
|
|
129
|
+
try {
|
|
130
|
+
return validateStoredShelf(JSON.parse(raw));
|
|
131
|
+
} catch {
|
|
132
|
+
throw invalidShelf();
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
const writeStored = async (shelf) => {
|
|
137
|
+
const serialized = JSON.stringify(shelf);
|
|
138
|
+
if (Buffer.byteLength(serialized) > MAX_FILE_BYTES) throw invalidShelf();
|
|
139
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
140
|
+
const temporary = `${file}.tmp`;
|
|
141
|
+
await writeFile(temporary, serialized, { mode: 0o600 });
|
|
142
|
+
await rename(temporary, file);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// Runs under the shelf lock. Returns the migrated shelf; throws (leaving
|
|
146
|
+
// the shelf file untouched) when the archive write fails.
|
|
147
|
+
const migrateLocked = async (stored) => {
|
|
148
|
+
if (!hasLegacySettled(stored)) return stored;
|
|
149
|
+
const toArchive = {};
|
|
150
|
+
for (const [sessionId, entry] of Object.entries(stored)) {
|
|
151
|
+
if (entry.settled === 'settled') toArchive[sessionId] = entry.settledAt;
|
|
152
|
+
}
|
|
153
|
+
if (Object.keys(toArchive).length > 0) {
|
|
154
|
+
if (typeof archiveStore?.archiveMissing !== 'function') {
|
|
155
|
+
throw Object.assign(new Error('No archive store for the settled migration.'), { code: 'SESSION_SHELF_MIGRATION_UNAVAILABLE' });
|
|
156
|
+
}
|
|
157
|
+
await archiveStore.archiveMissing(toArchive);
|
|
158
|
+
}
|
|
159
|
+
const migrated = withoutSettled(stored);
|
|
160
|
+
await writeStored(migrated);
|
|
161
|
+
return migrated;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// Serializes writes in this process and across processes sharing the data
|
|
165
|
+
// directory. `change` receives the migrated shelf (snooze state only) and
|
|
166
|
+
// may edit it in place; it returns whether the file needs writing, the
|
|
167
|
+
// result, and optionally a session whose settled mark should go too.
|
|
168
|
+
// While the migration keeps failing, writes still go through: the file
|
|
169
|
+
// keeps every other unmigrated settled mark, so the next read retries.
|
|
170
|
+
const locked = (change) => {
|
|
171
|
+
const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
|
|
172
|
+
const stored = await readStored();
|
|
173
|
+
let shelf;
|
|
174
|
+
let unmigrated = null;
|
|
175
|
+
try {
|
|
176
|
+
shelf = await migrateLocked(stored);
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (error?.code === 'SESSION_SHELF_INVALID') throw error;
|
|
179
|
+
console.warn('[pi] could not migrate settled sessions to the archive; will retry', error?.code ?? error);
|
|
180
|
+
shelf = withoutSettled(stored);
|
|
181
|
+
unmigrated = stored;
|
|
182
|
+
}
|
|
183
|
+
const { write, result, dropSettled } = change(shelf);
|
|
184
|
+
const dropsMark = unmigrated !== null && dropSettled !== undefined && unmigrated[dropSettled]?.settled !== undefined;
|
|
185
|
+
if (write || dropsMark) await writeStored(unmigrated ? withSettledKept(shelf, unmigrated, dropSettled) : shelf);
|
|
186
|
+
return result;
|
|
187
|
+
}));
|
|
188
|
+
writeChain = operation.catch(() => {});
|
|
189
|
+
return operation;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const read = async () => {
|
|
193
|
+
const stored = await readStored();
|
|
194
|
+
if (!hasLegacySettled(stored)) return stored;
|
|
195
|
+
try {
|
|
196
|
+
return await locked((shelf) => ({ write: false, result: shelf }));
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (error?.code === 'SESSION_SHELF_INVALID') throw error;
|
|
199
|
+
console.warn('[pi] could not read the session shelf under its lock', error?.code ?? error);
|
|
200
|
+
return withoutSettled(stored);
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
// `change` receives the current entry (or null) and returns the next entry
|
|
205
|
+
// (or null to remove it). `dropSettled` also removes the session's
|
|
206
|
+
// unmigrated settled mark (a send or a delete), so a retried migration
|
|
207
|
+
// cannot archive it afterwards.
|
|
208
|
+
const mutate = (sessionId, change, { dropSettled = false } = {}) => locked((shelf) => {
|
|
209
|
+
const previous = shelf[sessionId] ?? null;
|
|
210
|
+
const next = change(previous);
|
|
211
|
+
if (next) shelf[sessionId] = next;
|
|
212
|
+
else delete shelf[sessionId];
|
|
213
|
+
return {
|
|
214
|
+
write: JSON.stringify(previous) !== JSON.stringify(next ?? null),
|
|
215
|
+
result: next ?? null,
|
|
216
|
+
...(dropSettled ? { dropSettled: sessionId } : {}),
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Apply `{ snoozedUntil }`: a timestamp snoozes, `null` wakes. Returns the
|
|
222
|
+
* session's entry after the write, or null.
|
|
223
|
+
*/
|
|
224
|
+
const update = async (sessionId, patch) => {
|
|
225
|
+
if (!isSessionId(sessionId) || !isRecord(patch)) throw invalidArgument();
|
|
226
|
+
if (Object.keys(patch).some((key) => key !== 'snoozedUntil') || !Object.hasOwn(patch, 'snoozedUntil')) throw invalidArgument();
|
|
227
|
+
if (patch.snoozedUntil !== null && !isTimestamp(patch.snoozedUntil)) throw invalidArgument();
|
|
228
|
+
|
|
229
|
+
return mutate(sessionId, () => (patch.snoozedUntil === null
|
|
230
|
+
? null
|
|
231
|
+
: { snoozedUntil: patch.snoozedUntil, snoozedAt: now() }));
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// Whether the file holds anything for this session: a snooze or an
|
|
235
|
+
// unmigrated settled mark (empty entries are never kept).
|
|
236
|
+
const holds = async (sessionId) => Boolean((await readStored())[sessionId]);
|
|
237
|
+
|
|
238
|
+
/** A message the user sent ends a snooze. */
|
|
239
|
+
const clearForActivity = async (sessionId) => {
|
|
240
|
+
if (!isSessionId(sessionId)) return null;
|
|
241
|
+
if (!(await holds(sessionId))) return null;
|
|
242
|
+
return mutate(sessionId, () => null, { dropSettled: true });
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const remove = async (sessionId) => {
|
|
246
|
+
if (!isSessionId(sessionId)) return;
|
|
247
|
+
if (!(await holds(sessionId))) return;
|
|
248
|
+
await mutate(sessionId, () => null, { dropSettled: true });
|
|
249
|
+
};
|
|
250
|
+
|
|
251
|
+
return { read, update, clearForActivity, remove };
|
|
252
|
+
};
|