@pi-chamber/web 1.0.6-rc.4 → 1.0.6-rc.6
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-BZ--w7Lh.js → DiagramView-BxBfOrN5.js} +1 -1
- package/dist/assets/{DiffView-Dtn6otnT.js → DiffView-CSC9GMrb.js} +3 -3
- package/dist/assets/{FileSaveConflictDialog-p1ik30al.js → FileSaveConflictDialog-C_MNWp6w.js} +1 -1
- package/dist/assets/{FilesView-D0Z0VmQm.js → FilesView-DeN6KmNt.js} +4 -4
- package/dist/assets/{GitHubDetailScaffold-a27RksFo.js → GitHubDetailScaffold-CrtJwlqV.js} +2 -2
- package/dist/assets/{GitHubLinkPicker-B0CfzNfk.js → GitHubLinkPicker-g6w8K95J.js} +1 -1
- package/dist/assets/GitHubListPrimitives-lAi2ywE3.js +1 -0
- package/dist/assets/{GitView-BNkoaVYl.js → GitView-D9_em8Vx.js} +5 -5
- package/dist/assets/IssuesSurface-DCiHe6TE.js +7 -0
- package/dist/assets/{JsonTreeView-CEiJsFnP.js → JsonTreeView-D64mTfTx.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-418ChlsN.js → MarkdownRendererImpl-DwE90rTA.js} +3 -3
- package/dist/assets/PatchDiff-CcIwURzW.js +1 -0
- package/dist/assets/{PierreDiffViewer-CkuyY9ne.js → PierreDiffViewer-tN7awL0-.js} +2 -2
- package/dist/assets/PullRequestsSurface-iX4r3QlS.js +2 -0
- package/dist/assets/{SessionSwitcherContent-DkfjRgwv.js → SessionSwitcherContent-DrrM0ObM.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CEw8BEs6.js → SessionSwitcherDropdown-B9_0JwY7.js} +2 -2
- package/dist/assets/SessionUnreadDot-Bpgp2gLO.js +1 -0
- package/dist/assets/SettingsView-C4hec1iy.js +6 -0
- package/dist/assets/{SettingsWindow-D03Z9QyW.js → SettingsWindow-Bepcpy0R.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-CONTbZgX.js → StickyHorizontalScrollbar-DNsbTLS7.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DibddNlz.js → ToolOutputDialog-Dl9-vpvL.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-Bx7T1M2f.js → ToolPartDiffPreview-CLlHEPYD.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-BY-mDMT8.js → VirtualizedFileDiff-D9OpUpR3.js} +4 -4
- package/dist/assets/{Virtualizer-cIf8dSOQ.js → Virtualizer-okhy9Aq3.js} +1 -1
- package/dist/assets/{collapsible-BhQdnj8G.js → collapsible-ZT74WYMA.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-CzkFqhaU.js → computeVirtualFileMetrics-CDv_UBXL.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-CjCOK8EB.js → contextFileOpenGuard-BJ2sAhZG.js} +1 -1
- package/dist/assets/{fileTreeStatus-CPTpyKOV.js → fileTreeStatus-B2PDFobt.js} +2 -2
- package/dist/assets/{gitStatusPredicates-_GNbGCCb.js → gitStatusPredicates-BDdOjxH_.js} +1 -1
- package/dist/assets/{githubLink-CwIFogWd.js → githubLink-wwC2_C_9.js} +2 -2
- package/dist/assets/index-BaLCg7tL.css +1 -0
- package/dist/assets/{index-DjOKW10B.js → index-MXKT8Ir9.js} +1 -1
- package/dist/assets/index-fmzQmSSv.js +11 -0
- package/dist/assets/{main-C51a3z3b.js → main-CnW7qm2b.js} +2 -2
- package/dist/assets/{main-1wmEZ4Is.js → main-DmHVgAh0.js} +4 -4
- package/dist/assets/{markdownCore-Dsr6dY5C.js → markdownCore-DOFhfL5i.js} +2 -2
- package/dist/assets/{miniChat-DCxCx1fF.js → miniChat-D_Wl2jlx.js} +2 -2
- package/dist/assets/{mobile-D6Ac2Mu3.js → mobile-Cl-KcfGW.js} +2 -2
- package/dist/assets/{nativeFileSave-P_Eg5Dgb.js → nativeFileSave-B4Rg6n8u.js} +1 -1
- package/dist/assets/{pi-session-focus-preference-DjDyjZ1C.js → pi-session-focus-preference-BqEU9Iq6.js} +3 -3
- package/dist/assets/{renderDiffWithHighlighter-CK_inhQE.js → renderDiffWithHighlighter-U7WjeGm9.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-wBNgFl0U.js → renderElectronMiniChatApp-BJxNc9OP.js} +2 -2
- package/dist/assets/{renderFileWithHighlighter-B_PFeRW5.js → renderFileWithHighlighter-DiwpFgMp.js} +1 -1
- package/dist/assets/{renderMobileApp-B3mhxGnb.js → renderMobileApp-d5KpyvBc.js} +3 -3
- package/dist/assets/runtimeEndpointReset-Cd4yJDsk.js +62 -0
- package/dist/assets/{runtimeSurface-C3YPOBlg.js → runtimeSurface-X62LLBLv.js} +1 -1
- package/dist/assets/{useAppFontEffects-CoFst31H.js → useAppFontEffects-FKnY7Fe2.js} +92 -92
- package/dist/assets/useGitHubRemoteSearch-4QMXIODG.js +1 -0
- package/dist/assets/{useSwitcherItems-DHCCg4GF.js → useSwitcherItems-DtCNsq8u.js} +1 -1
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-B9_YeZyx.js → vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js} +1 -1
- package/dist/assets/{vendor-base-ui-CKSCJw-4.js → vendor-base-ui-BCqPBzDj.js} +1 -1
- package/dist/assets/{vendor-boot-Ciu-Edvy.js → vendor-boot-3SaHYVb1.js} +1 -1
- package/dist/assets/{vendor-capacitor-app-Bpy_aPMq.js → vendor-capacitor-app-NbQ-WiPS.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-DO8AIjrZ.js → vendor-capacitor-keyboard-CgrHt8iN.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-SQkytwUW.js → vendor-capacitor-status-bar-CWt0OF5t.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-CInQsE8a.js → vendor-codemirror-autocomplete-WThuuUAz.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-QbsN3LGE.js → vendor-codemirror-lang-angular-BbLGCxF6.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-BT5U7lxV.js → vendor-codemirror-lang-cpp-Cceks-9O.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-dF-Dxbty.js → vendor-codemirror-lang-css-D1wpUg3Z.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-e4dp1bar.js → vendor-codemirror-lang-go-Cv0zXHHM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DKcbBVQ4.js → vendor-codemirror-lang-html-DbL8oT9H.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CB2-FWv6.js → vendor-codemirror-lang-java-CNugenuC.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-B1zJk7xE.js → vendor-codemirror-lang-javascript-Bx_FIyZF.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-BsERjdSd.js → vendor-codemirror-lang-jinja-DDGjB3Zq.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-C0pZ0NhY.js → vendor-codemirror-lang-json-DIvqf9Pb.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-_N9HmR4h.js → vendor-codemirror-lang-less-D8r9dGG1.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-D02xJRCD.js → vendor-codemirror-lang-liquid-B24mguYi.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-_6ojeUuZ.js → vendor-codemirror-lang-markdown-v3yG2sbf.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-DguCnbJA.js → vendor-codemirror-lang-php-BcZGalqy.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-Byr5gw5f.js → vendor-codemirror-lang-python-b-JqEwQy.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-DN6Wh0eK.js → vendor-codemirror-lang-rust-B1uZxDW-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-DOlEW7q1.js → vendor-codemirror-lang-sass-DqPrngKp.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-BJzE9Dby.js → vendor-codemirror-lang-sql-UyCnpt-k.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-DR8E-2nr.js → vendor-codemirror-lang-vue-xDwYkovV.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-n6lcDH5S.js → vendor-codemirror-lang-wast-CF3169p_.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-Cf2lmlmY.js → vendor-codemirror-lang-xml-FCtVhuOb.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-DSR_E0yh.js → vendor-codemirror-lang-yaml-g0sPmAnv.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-CSid5JuX.js → vendor-codemirror-language-data-B03xgzP2.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-8lY3lt6q.js → vendor-codemirror-search-Dw3Wpu15.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-DZYTDKiD.js → vendor-lezer-cpp-Cu3E-KUI.js} +1 -1
- package/dist/assets/{vendor-lezer-css-6qV4fYNQ.js → vendor-lezer-css-Cb8vp67u.js} +1 -1
- package/dist/assets/{vendor-lezer-go-BDi_Iblq.js → vendor-lezer-go-BTsIaOm7.js} +1 -1
- package/dist/assets/{vendor-lezer-html-BjqcY-oJ.js → vendor-lezer-html-UQMsUwj-.js} +1 -1
- package/dist/assets/{vendor-lezer-java-J2BXqz1h.js → vendor-lezer-java-BIWrFrAx.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-CiQ9F8yX.js → vendor-lezer-javascript-BH2Etgoy.js} +1 -1
- package/dist/assets/{vendor-lezer-json-BxN83KKR.js → vendor-lezer-json-CE-QUCwM.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-BVsDua_K.js → vendor-lezer-lr-HY6Yc0Vr.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-BkMtRQ3X.js → vendor-lezer-markdown-xFL3Evwf.js} +1 -1
- package/dist/assets/{vendor-lezer-php-B3XqnXdP.js → vendor-lezer-php-Cr_mQGrG.js} +1 -1
- package/dist/assets/{vendor-lezer-python-D342CidI.js → vendor-lezer-python-BNRFWCb0.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-Dbfg_4LA.js → vendor-lezer-rust-BvfOK5cU.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-ClxPaFt1.js → vendor-lezer-sass-qoxiLisk.js} +1 -1
- package/dist/assets/{vendor-lezer-xml-I_S6FQ1u.js → vendor-lezer-xml--x8SSpqU.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-COA6HWLP.js → vendor-lezer-yaml-BDo1JaEr.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-7IE2zVmx.js → vendor-replit-codemirror-vim-D1Fe7FiY.js} +1 -1
- package/dist/assets/{web-components-CzkvK_V5.js → web-components-D5QImbWv.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/pi/archive-store.js +38 -10
- package/server/lib/pi/archive-store.test.js +10 -0
- package/server/lib/pi/routes.js +65 -18
- package/server/lib/pi/routes.test.js +189 -8
- 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 +155 -84
- package/server/lib/pi/session-shelf-store.test.js +134 -33
- package/server/lib/pi/ui-settings-store.js +59 -0
- package/server/lib/pi/ui-settings-store.test.js +105 -6
- package/dist/assets/GitHubListPrimitives-LFdR70l6.js +0 -1
- package/dist/assets/IssuesSurface-D4kD7_VW.js +0 -7
- package/dist/assets/PatchDiff-BtOv_oLB.js +0 -1
- package/dist/assets/PullRequestsSurface-PML07zr-.js +0 -2
- package/dist/assets/SessionUnreadDot-DXUn8-ss.js +0 -1
- package/dist/assets/SettingsView-BvUeFUqw.js +0 -6
- package/dist/assets/index-Cfrwo5uQ.js +0 -11
- package/dist/assets/index-D7k62S9M.css +0 -1
- package/dist/assets/runtimeEndpointReset-D8lAOCUB.js +0 -62
- package/dist/assets/useGitHubRemoteSearch-C0-6hhMJ.js +0 -1
package/dist/mini-chat.html
CHANGED
|
@@ -89,15 +89,15 @@
|
|
|
89
89
|
}
|
|
90
90
|
</style>
|
|
91
91
|
|
|
92
|
-
<script type="module" crossorigin src="/assets/miniChat-
|
|
92
|
+
<script type="module" crossorigin src="/assets/miniChat-D_Wl2jlx.js"></script>
|
|
93
93
|
<link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
|
|
94
94
|
<link rel="modulepreload" crossorigin href="/assets/vendor-react-Bz1tRBxM.js">
|
|
95
95
|
<link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CXhN0IMY.js">
|
|
96
96
|
<link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
|
|
97
97
|
<link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-BKkUfl9q.js">
|
|
98
98
|
<link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-t_7AcMTv.js">
|
|
99
|
-
<link rel="modulepreload" crossorigin href="/assets/index-
|
|
100
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
99
|
+
<link rel="modulepreload" crossorigin href="/assets/index-fmzQmSSv.js">
|
|
100
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BaLCg7tL.css">
|
|
101
101
|
<link rel="stylesheet" crossorigin href="/assets/vendor-katex-css-Cp579UoJ.css">
|
|
102
102
|
</head>
|
|
103
103
|
<body class="h-full bg-background text-foreground">
|
package/dist/mobile.html
CHANGED
|
@@ -63,15 +63,15 @@
|
|
|
63
63
|
})();
|
|
64
64
|
</script>
|
|
65
65
|
|
|
66
|
-
<script type="module" crossorigin src="/assets/mobile-
|
|
66
|
+
<script type="module" crossorigin src="/assets/mobile-Cl-KcfGW.js"></script>
|
|
67
67
|
<link rel="modulepreload" crossorigin href="/assets/vendor-vite-runtime-DD1OZmLC.js">
|
|
68
68
|
<link rel="modulepreload" crossorigin href="/assets/vendor-react-Bz1tRBxM.js">
|
|
69
69
|
<link rel="modulepreload" crossorigin href="/assets/vendor-zustand-CXhN0IMY.js">
|
|
70
70
|
<link rel="modulepreload" crossorigin href="/assets/vendor-clsx-B-dksMZM.js">
|
|
71
71
|
<link rel="modulepreload" crossorigin href="/assets/vendor-tailwind-merge-BKkUfl9q.js">
|
|
72
72
|
<link rel="modulepreload" crossorigin href="/assets/vendor-fuse.js-t_7AcMTv.js">
|
|
73
|
-
<link rel="modulepreload" crossorigin href="/assets/index-
|
|
74
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
73
|
+
<link rel="modulepreload" crossorigin href="/assets/index-fmzQmSSv.js">
|
|
74
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BaLCg7tL.css">
|
|
75
75
|
<link rel="stylesheet" crossorigin href="/assets/vendor-katex-css-Cp579UoJ.css">
|
|
76
76
|
</head>
|
|
77
77
|
<body class="h-full bg-background text-foreground">
|
package/package.json
CHANGED
|
@@ -10,6 +10,12 @@ const invalidArchive = () => {
|
|
|
10
10
|
return error;
|
|
11
11
|
};
|
|
12
12
|
|
|
13
|
+
const invalidArgument = () => {
|
|
14
|
+
const error = new Error('The archive request is invalid.');
|
|
15
|
+
error.code = 'INVALID_ARGUMENT';
|
|
16
|
+
return error;
|
|
17
|
+
};
|
|
18
|
+
|
|
13
19
|
/**
|
|
14
20
|
* PiChamber-owned archive metadata. Pi JSONL remains untouched: the sidecar is
|
|
15
21
|
* keyed only by opaque Pi session IDs and every write is atomic.
|
|
@@ -29,25 +35,47 @@ export const createPiArchiveStore = ({ file = join(resolvePiChamberDataDir(), 'p
|
|
|
29
35
|
}
|
|
30
36
|
};
|
|
31
37
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
error.code = 'INVALID_ARGUMENT';
|
|
36
|
-
throw error;
|
|
37
|
-
}
|
|
38
|
+
// Serializes writes in this process and across processes sharing the data
|
|
39
|
+
// directory. `change` edits the current map in place.
|
|
40
|
+
const mutate = (change) => {
|
|
38
41
|
const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
|
|
39
42
|
const current = await read();
|
|
40
|
-
|
|
41
|
-
else delete current[sessionId];
|
|
43
|
+
const result = change(current);
|
|
42
44
|
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
43
45
|
const temporary = `${file}.tmp`;
|
|
44
46
|
await writeFile(temporary, JSON.stringify(current), { mode: 0o600 });
|
|
45
47
|
await rename(temporary, file);
|
|
46
|
-
return
|
|
48
|
+
return result;
|
|
47
49
|
}));
|
|
48
50
|
writeChain = operation.catch(() => {});
|
|
49
51
|
return operation;
|
|
50
52
|
};
|
|
51
53
|
|
|
52
|
-
|
|
54
|
+
const set = async (sessionId, archived) => {
|
|
55
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0 || typeof archived !== 'boolean') throw invalidArgument();
|
|
56
|
+
return mutate((current) => {
|
|
57
|
+
if (archived) current[sessionId] = Date.now();
|
|
58
|
+
else delete current[sessionId];
|
|
59
|
+
return archived ? current[sessionId] : undefined;
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Archive each `{ sessionId: archivedAt }` that is not archived yet, at the
|
|
65
|
+
* given time. Sessions already archived keep their time. Used by the
|
|
66
|
+
* one-time settled-shelf migration.
|
|
67
|
+
*/
|
|
68
|
+
const archiveMissing = async (entries) => {
|
|
69
|
+
if (!entries || typeof entries !== 'object' || Array.isArray(entries)) throw invalidArgument();
|
|
70
|
+
const list = Object.entries(entries);
|
|
71
|
+
if (list.some(([sessionId, at]) => sessionId.length === 0 || !Number.isSafeInteger(at) || at <= 0)) throw invalidArgument();
|
|
72
|
+
if (list.length === 0) return;
|
|
73
|
+
await mutate((current) => {
|
|
74
|
+
for (const [sessionId, at] of list) {
|
|
75
|
+
if (!Object.hasOwn(current, sessionId)) current[sessionId] = at;
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
return { read, set, archiveMissing };
|
|
53
81
|
};
|
|
@@ -29,4 +29,14 @@ describe('Pi archive sidecar', () => {
|
|
|
29
29
|
await writeFile(file, 'not-json');
|
|
30
30
|
await expect(archive.read()).rejects.toMatchObject({ code: 'ARCHIVE_METADATA_INVALID' });
|
|
31
31
|
});
|
|
32
|
+
|
|
33
|
+
it('archives missing sessions at given times without moving existing archive times', async () => {
|
|
34
|
+
const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-archive-'));
|
|
35
|
+
const archive = createPiArchiveStore({ file: join(root, 'pi', 'session-archive.json') });
|
|
36
|
+
await archive.set('kept', true);
|
|
37
|
+
const keptAt = (await archive.read()).kept;
|
|
38
|
+
await archive.archiveMissing({ kept: 5, added: 7 });
|
|
39
|
+
await expect(archive.read()).resolves.toEqual({ kept: keptAt, added: 7 });
|
|
40
|
+
await expect(archive.archiveMissing({ bad: -1 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
|
|
41
|
+
});
|
|
32
42
|
});
|
package/server/lib/pi/routes.js
CHANGED
|
@@ -940,6 +940,11 @@ export const projectEventFrame = (frame) => {
|
|
|
940
940
|
const level = ['info', 'warning', 'error'].includes(frame.payload.level) ? frame.payload.level : 'info';
|
|
941
941
|
return { ...common, payload: { message: frame.payload.message.slice(0, 2000), level } };
|
|
942
942
|
}
|
|
943
|
+
case 'session.archive': {
|
|
944
|
+
// An archive mark changed on the server; devices re-list the folder.
|
|
945
|
+
if (typeof frame.payload.archived !== 'boolean') return null;
|
|
946
|
+
return { ...common, payload: { archived: frame.payload.archived } };
|
|
947
|
+
}
|
|
943
948
|
case 'session.openUrl': {
|
|
944
949
|
// An Open request (lib/open-url). `serverNow` is stamped at delivery so
|
|
945
950
|
// a device can tell a live request from a replayed one using only the
|
|
@@ -1121,7 +1126,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1121
1126
|
attachmentStore = createPiAttachmentStore(),
|
|
1122
1127
|
settingsStore = createPiSettingsStore(),
|
|
1123
1128
|
sessionFoldersStore = createPiSessionFoldersStore(),
|
|
1124
|
-
sessionShelfStore = createPiSessionShelfStore(),
|
|
1129
|
+
sessionShelfStore = createPiSessionShelfStore({ archiveStore }),
|
|
1125
1130
|
uiSettingsStore = createPiUiSettingsStore(),
|
|
1126
1131
|
snippetsStore = createPiSnippetsStore(),
|
|
1127
1132
|
listCustomThemes = listPiCustomThemes,
|
|
@@ -1135,14 +1140,41 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1135
1140
|
eventStreamMaxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
|
|
1136
1141
|
}) => {
|
|
1137
1142
|
const eventStreamRegistry = createPiEventStreamRegistry();
|
|
1138
|
-
//
|
|
1139
|
-
//
|
|
1140
|
-
|
|
1143
|
+
// Tell every device an archive mark changed (a `session.archive` event on
|
|
1144
|
+
// the session's stream) so other clients re-list that folder. The change is
|
|
1145
|
+
// already saved, so this never delays or fails the request: an older
|
|
1146
|
+
// daemon without `archive.publish` only logs, and devices catch up on
|
|
1147
|
+
// their next list.
|
|
1148
|
+
const publishArchiveChange = (sessionId, archived, directory) => {
|
|
1149
|
+
void (async () => {
|
|
1150
|
+
try {
|
|
1151
|
+
await getDaemonRuntime(getPiSessionDaemonRuntime).request('archive.publish', {
|
|
1152
|
+
sessionId,
|
|
1153
|
+
archived,
|
|
1154
|
+
...(typeof directory === 'string' && directory.length > 0 ? { directory } : {}),
|
|
1155
|
+
});
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
console.warn('[pi] could not tell other devices about an archive change', error?.code ?? error);
|
|
1158
|
+
}
|
|
1159
|
+
})();
|
|
1160
|
+
};
|
|
1161
|
+
// A message or command the user sends ends a snooze and unarchives the
|
|
1162
|
+
// session. The send already succeeded, so a failed write only logs.
|
|
1163
|
+
const bringBackForActivity = async (sessionId) => {
|
|
1141
1164
|
try {
|
|
1142
1165
|
await sessionShelfStore.clearForActivity(sessionId);
|
|
1143
1166
|
} catch (error) {
|
|
1144
1167
|
console.warn('[pi] could not clear the session shelf after a send', error?.code ?? error);
|
|
1145
1168
|
}
|
|
1169
|
+
try {
|
|
1170
|
+
const archived = await archiveStore.read();
|
|
1171
|
+
if (Object.hasOwn(archived, sessionId)) {
|
|
1172
|
+
await archiveStore.set(sessionId, false);
|
|
1173
|
+
publishArchiveChange(sessionId, false);
|
|
1174
|
+
}
|
|
1175
|
+
} catch (error) {
|
|
1176
|
+
console.warn('[pi] could not unarchive a session after a send', error?.code ?? error);
|
|
1177
|
+
}
|
|
1146
1178
|
};
|
|
1147
1179
|
app.get('/api/pi/ui-settings', async (_req, res) => {
|
|
1148
1180
|
try {
|
|
@@ -1196,9 +1228,13 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1196
1228
|
app.get('/api/pi/update-check', async (req, res) => {
|
|
1197
1229
|
try {
|
|
1198
1230
|
const appType = typeof req.query.appType === 'string' ? req.query.appType : undefined;
|
|
1231
|
+
// Web checks follow the server's channel. The mobile app keeps its own
|
|
1232
|
+
// channel on the device and sends it; older apps send none and get stable.
|
|
1199
1233
|
const channel = appType === undefined || appType === 'web'
|
|
1200
1234
|
? await readServerUpdateChannel()
|
|
1201
|
-
: '
|
|
1235
|
+
: appType === 'mobile-capacitor'
|
|
1236
|
+
? normalizeServerUpdateChannel(req.query.channel)
|
|
1237
|
+
: 'stable';
|
|
1202
1238
|
res.json(await updateChecker({
|
|
1203
1239
|
currentVersion: typeof req.query.currentVersion === 'string' ? req.query.currentVersion : undefined,
|
|
1204
1240
|
appType,
|
|
@@ -2039,14 +2075,15 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2039
2075
|
const { sessionId } = req.params;
|
|
2040
2076
|
const body = req.body && typeof req.body === 'object' ? req.body : {};
|
|
2041
2077
|
const directory = typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined;
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
const
|
|
2047
|
-
const
|
|
2048
|
-
|
|
2049
|
-
|
|
2078
|
+
// Older clients (the Settle release candidate) may still send `settled`:
|
|
2079
|
+
// 'settled' archives the session; 'active' and null do nothing. Remove
|
|
2080
|
+
// this mapping one release after Archive replaced Settle.
|
|
2081
|
+
const hasSettled = Object.hasOwn(body, 'settled');
|
|
2082
|
+
const hasSnooze = Object.hasOwn(body, 'snoozedUntil');
|
|
2083
|
+
const settledValid = !hasSettled || body.settled === null || body.settled === 'settled' || body.settled === 'active';
|
|
2084
|
+
const snoozeValid = !hasSnooze || body.snoozedUntil === null
|
|
2085
|
+
|| (Number.isSafeInteger(body.snoozedUntil) && body.snoozedUntil > 0);
|
|
2086
|
+
if (!sessionId || (!hasSettled && !hasSnooze) || !settledValid || !snoozeValid) {
|
|
2050
2087
|
res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
|
|
2051
2088
|
return;
|
|
2052
2089
|
}
|
|
@@ -2058,12 +2095,20 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2058
2095
|
directory ? { directory } : undefined,
|
|
2059
2096
|
);
|
|
2060
2097
|
const items = projectSessionList(result?.sessions);
|
|
2061
|
-
|
|
2098
|
+
const item = items.find((candidate) => candidate.session.id === sessionId);
|
|
2099
|
+
if (!item) {
|
|
2062
2100
|
const error = new Error('The Pi session does not exist.');
|
|
2063
2101
|
error.code = 'INVALID_SESSION';
|
|
2064
2102
|
throw error;
|
|
2065
2103
|
}
|
|
2066
|
-
|
|
2104
|
+
if (hasSettled && body.settled === 'settled') {
|
|
2105
|
+
await archiveStore.set(sessionId, true);
|
|
2106
|
+
publishArchiveChange(sessionId, true, item.session.directory || directory);
|
|
2107
|
+
}
|
|
2108
|
+
const entry = hasSnooze
|
|
2109
|
+
? await sessionShelfStore.update(sessionId, { snoozedUntil: body.snoozedUntil })
|
|
2110
|
+
: (await sessionShelfStore.read())[sessionId] ?? null;
|
|
2111
|
+
res.json({ entry });
|
|
2067
2112
|
} catch (error) {
|
|
2068
2113
|
writeDaemonError(res, error);
|
|
2069
2114
|
}
|
|
@@ -2085,12 +2130,14 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2085
2130
|
directory ? { directory } : undefined,
|
|
2086
2131
|
);
|
|
2087
2132
|
const items = projectSessionList(result?.sessions);
|
|
2088
|
-
|
|
2133
|
+
const item = items.find((candidate) => candidate.session.id === sessionId);
|
|
2134
|
+
if (!item) {
|
|
2089
2135
|
const error = new Error('The Pi session does not exist.');
|
|
2090
2136
|
error.code = 'INVALID_SESSION';
|
|
2091
2137
|
throw error;
|
|
2092
2138
|
}
|
|
2093
2139
|
await archiveStore.set(sessionId, archived);
|
|
2140
|
+
publishArchiveChange(sessionId, archived, item.session.directory || directory);
|
|
2094
2141
|
res.status(204).end();
|
|
2095
2142
|
} catch (error) {
|
|
2096
2143
|
writeDaemonError(res, error);
|
|
@@ -2280,7 +2327,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2280
2327
|
return;
|
|
2281
2328
|
}
|
|
2282
2329
|
await attachmentStore.consume?.(attachmentIds);
|
|
2283
|
-
await
|
|
2330
|
+
await bringBackForActivity(req.params.sessionId);
|
|
2284
2331
|
res.status(202).json({
|
|
2285
2332
|
accepted: true,
|
|
2286
2333
|
messageId: result.messageId,
|
|
@@ -2355,7 +2402,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
2355
2402
|
writeDaemonError(res, protocolMismatch());
|
|
2356
2403
|
return;
|
|
2357
2404
|
}
|
|
2358
|
-
await
|
|
2405
|
+
await bringBackForActivity(req.params.sessionId);
|
|
2359
2406
|
res.status(202).json({ accepted: true, id: result.id });
|
|
2360
2407
|
});
|
|
2361
2408
|
|
|
@@ -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,
|
|
@@ -180,6 +188,9 @@ describe('Pi runtime route', () => {
|
|
|
180
188
|
await expect((await fetch(`${base}/api/pi/themes`)).json()).resolves.toEqual({ themes: [{ metadata: { id: 'custom' } }] });
|
|
181
189
|
await expect((await fetch(`${base}/api/pi/update-check?appType=web`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'rc' });
|
|
182
190
|
await expect((await fetch(`${base}/api/pi/update-check?appType=mobile-capacitor`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'stable' });
|
|
191
|
+
await expect((await fetch(`${base}/api/pi/update-check?appType=mobile-capacitor&channel=rc`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'rc' });
|
|
192
|
+
await expect((await fetch(`${base}/api/pi/update-check?appType=mobile-capacitor&channel=nightly`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'stable' });
|
|
193
|
+
await expect((await fetch(`${base}/api/pi/update-check?appType=desktop-electron&channel=rc`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0', channel: 'stable' });
|
|
183
194
|
const installResponse = await fetch(`${base}/api/pi/update-install`, { method: 'POST' });
|
|
184
195
|
expect(installResponse.status).toBe(202);
|
|
185
196
|
await expect(installResponse.json()).resolves.toEqual({
|
|
@@ -1549,12 +1560,12 @@ describe('Pi runtime route', () => {
|
|
|
1549
1560
|
it('serves the session shelf, checks membership on writes, and clears it when the user sends', async () => {
|
|
1550
1561
|
const calls = [];
|
|
1551
1562
|
const session = { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 };
|
|
1552
|
-
let shelf = { 'pi-session-7': {
|
|
1563
|
+
let shelf = { 'pi-session-7': { snoozedUntil: 9_000, snoozedAt: 3 } };
|
|
1553
1564
|
const sessionShelfStore = {
|
|
1554
1565
|
read: async () => shelf,
|
|
1555
1566
|
update: async (sessionId, patch) => {
|
|
1556
1567
|
calls.push({ command: 'shelf.update', payload: [sessionId, patch] });
|
|
1557
|
-
return {
|
|
1568
|
+
return { snoozedUntil: 12_000, snoozedAt: 4 };
|
|
1558
1569
|
},
|
|
1559
1570
|
clearForActivity: async (sessionId) => {
|
|
1560
1571
|
calls.push({ command: 'shelf.clear', payload: sessionId });
|
|
@@ -1580,15 +1591,15 @@ describe('Pi runtime route', () => {
|
|
|
1580
1591
|
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1581
1592
|
const post = (path, body) => fetch(`${origin}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1582
1593
|
|
|
1583
|
-
await expect((await fetch(`${origin}/api/pi/session-shelf`)).json()).resolves.toEqual({ sessions: { 'pi-session-7': {
|
|
1594
|
+
await expect((await fetch(`${origin}/api/pi/session-shelf`)).json()).resolves.toEqual({ sessions: { 'pi-session-7': { snoozedUntil: 9_000, snoozedAt: 3 } } });
|
|
1584
1595
|
|
|
1585
|
-
const updated = await post('/api/pi/sessions/pi-session-7/shelf', {
|
|
1596
|
+
const updated = await post('/api/pi/sessions/pi-session-7/shelf', { snoozedUntil: 12_000, directory: '/workspace' });
|
|
1586
1597
|
expect(updated.status).toBe(200);
|
|
1587
|
-
await expect(updated.json()).resolves.toEqual({ entry: {
|
|
1598
|
+
await expect(updated.json()).resolves.toEqual({ entry: { snoozedUntil: 12_000, snoozedAt: 4 } });
|
|
1588
1599
|
expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/workspace' } });
|
|
1589
|
-
expect(calls).toContainEqual({ command: 'shelf.update', payload: ['pi-session-7', {
|
|
1600
|
+
expect(calls).toContainEqual({ command: 'shelf.update', payload: ['pi-session-7', { snoozedUntil: 12_000 }] });
|
|
1590
1601
|
|
|
1591
|
-
expect((await post('/api/pi/sessions/missing/shelf', {
|
|
1602
|
+
expect((await post('/api/pi/sessions/missing/shelf', { snoozedUntil: 12_000 })).status).toBe(404);
|
|
1592
1603
|
expect((await post('/api/pi/sessions/pi-session-7/shelf', {})).status).toBe(400);
|
|
1593
1604
|
expect((await post('/api/pi/sessions/pi-session-7/shelf', { settled: 'done' })).status).toBe(400);
|
|
1594
1605
|
expect((await post('/api/pi/sessions/pi-session-7/shelf', { snoozedUntil: 'tomorrow' })).status).toBe(400);
|
|
@@ -1604,6 +1615,173 @@ describe('Pi runtime route', () => {
|
|
|
1604
1615
|
expect(calls).toContainEqual({ command: 'shelf.remove', payload: 'pi-session-7' });
|
|
1605
1616
|
});
|
|
1606
1617
|
|
|
1618
|
+
it('maps a settled shelf write from an older client to an archive, and accepts active or null as no-ops', async () => {
|
|
1619
|
+
const session = { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 };
|
|
1620
|
+
const archiveSets = [];
|
|
1621
|
+
const shelfUpdates = [];
|
|
1622
|
+
const sessionShelfStore = {
|
|
1623
|
+
read: async () => ({ 'pi-session-7': { snoozedUntil: 9_000, snoozedAt: 3 } }),
|
|
1624
|
+
update: async (sessionId, patch) => {
|
|
1625
|
+
shelfUpdates.push([sessionId, patch]);
|
|
1626
|
+
return null;
|
|
1627
|
+
},
|
|
1628
|
+
};
|
|
1629
|
+
const published = [];
|
|
1630
|
+
const runtime = {
|
|
1631
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1632
|
+
request: async (command, payload) => {
|
|
1633
|
+
if (command === 'archive.publish') published.push(payload);
|
|
1634
|
+
return command === 'sessions.list' ? { sessions: [{ session, updatedAt: 2 }] } : {};
|
|
1635
|
+
},
|
|
1636
|
+
};
|
|
1637
|
+
const app = express();
|
|
1638
|
+
app.use(express.json());
|
|
1639
|
+
registerPiRuntimeRoutes(app, {
|
|
1640
|
+
getPiSessionDaemonRuntime: () => runtime,
|
|
1641
|
+
archiveStore: { read: async () => ({}), set: async (...args) => archiveSets.push(args) },
|
|
1642
|
+
sessionShelfStore,
|
|
1643
|
+
});
|
|
1644
|
+
server = await listen(app);
|
|
1645
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1646
|
+
const post = (body) => fetch(`${origin}/api/pi/sessions/pi-session-7/shelf`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1647
|
+
|
|
1648
|
+
const settled = await post({ settled: 'settled', directory: '/workspace' });
|
|
1649
|
+
expect(settled.status).toBe(200);
|
|
1650
|
+
await expect(settled.json()).resolves.toEqual({ entry: { snoozedUntil: 9_000, snoozedAt: 3 } });
|
|
1651
|
+
expect(archiveSets).toEqual([['pi-session-7', true]]);
|
|
1652
|
+
await vi.waitFor(() => expect(published).toEqual([{ sessionId: 'pi-session-7', archived: true, directory: '/workspace' }]));
|
|
1653
|
+
|
|
1654
|
+
for (const value of ['active', null]) {
|
|
1655
|
+
const response = await post({ settled: value });
|
|
1656
|
+
expect(response.status).toBe(200);
|
|
1657
|
+
await expect(response.json()).resolves.toEqual({ entry: { snoozedUntil: 9_000, snoozedAt: 3 } });
|
|
1658
|
+
}
|
|
1659
|
+
expect(archiveSets).toHaveLength(1);
|
|
1660
|
+
expect(shelfUpdates).toEqual([]);
|
|
1661
|
+
|
|
1662
|
+
// A snooze sent alongside a settled value still applies.
|
|
1663
|
+
expect((await post({ settled: null, snoozedUntil: 12_000 })).status).toBe(200);
|
|
1664
|
+
expect(shelfUpdates).toEqual([['pi-session-7', { snoozedUntil: 12_000 }]]);
|
|
1665
|
+
expect((await fetch(`${origin}/api/pi/sessions/missing/shelf`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ settled: 'settled' }) })).status).toBe(404);
|
|
1666
|
+
expect(archiveSets).toHaveLength(1);
|
|
1667
|
+
expect(published).toHaveLength(1);
|
|
1668
|
+
});
|
|
1669
|
+
|
|
1670
|
+
it('unarchives a session when a prompt, steer, follow-up, or shell command is accepted', async () => {
|
|
1671
|
+
const archive = { 'pi-session-7': 5, 'pi-session-8': 6 };
|
|
1672
|
+
const archiveSets = [];
|
|
1673
|
+
const archiveStore = {
|
|
1674
|
+
read: async () => ({ ...archive }),
|
|
1675
|
+
set: async (sessionId, archived) => {
|
|
1676
|
+
archiveSets.push([sessionId, archived]);
|
|
1677
|
+
if (archived) archive[sessionId] = 10;
|
|
1678
|
+
else delete archive[sessionId];
|
|
1679
|
+
},
|
|
1680
|
+
};
|
|
1681
|
+
let accept = true;
|
|
1682
|
+
const published = [];
|
|
1683
|
+
const runtime = {
|
|
1684
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1685
|
+
request: async (command, payload) => {
|
|
1686
|
+
if (command === 'archive.publish') {
|
|
1687
|
+
published.push(payload);
|
|
1688
|
+
return { published: true };
|
|
1689
|
+
}
|
|
1690
|
+
if (command === 'sessions.bash') return accept ? { accepted: true, id: 'bash-1' } : Promise.reject(Object.assign(new Error('nope'), { code: 'INVALID_SESSION' }));
|
|
1691
|
+
if (command === 'sessions.prompt' || command === 'sessions.steer' || command === 'sessions.followUp') {
|
|
1692
|
+
if (!accept) throw Object.assign(new Error('nope'), { code: 'INVALID_SESSION' });
|
|
1693
|
+
return { accepted: true, messageId: 'message-1' };
|
|
1694
|
+
}
|
|
1695
|
+
return {};
|
|
1696
|
+
},
|
|
1697
|
+
};
|
|
1698
|
+
const app = express();
|
|
1699
|
+
app.use(express.json());
|
|
1700
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore, sessionShelfStore: { clearForActivity: async () => null } });
|
|
1701
|
+
server = await listen(app);
|
|
1702
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1703
|
+
const post = (path, body) => fetch(`${origin}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
1704
|
+
|
|
1705
|
+
// A rejected send leaves the archive alone.
|
|
1706
|
+
accept = false;
|
|
1707
|
+
expect((await post('/api/pi/sessions/pi-session-7/prompt', { text: 'hello', streamEpoch: 'epoch-routes' })).status).not.toBe(202);
|
|
1708
|
+
expect((await post('/api/pi/sessions/pi-session-7/bash', { command: 'ls' })).status).not.toBe(202);
|
|
1709
|
+
expect(archiveSets).toEqual([]);
|
|
1710
|
+
expect(published).toEqual([]);
|
|
1711
|
+
accept = true;
|
|
1712
|
+
|
|
1713
|
+
expect((await post('/api/pi/sessions/pi-session-7/prompt', { text: 'hello', streamEpoch: 'epoch-routes' })).status).toBe(202);
|
|
1714
|
+
expect(archive).toEqual({ 'pi-session-8': 6 });
|
|
1715
|
+
// The daemon resolves the folder from the resident session.
|
|
1716
|
+
await vi.waitFor(() => expect(published).toEqual([{ sessionId: 'pi-session-7', archived: false }]));
|
|
1717
|
+
// Not archived: no write and nothing to publish.
|
|
1718
|
+
expect((await post('/api/pi/sessions/pi-session-7/steer', { text: 'more', streamEpoch: 'epoch-routes' })).status).toBe(202);
|
|
1719
|
+
expect(archiveSets).toEqual([['pi-session-7', false]]);
|
|
1720
|
+
expect(published).toHaveLength(1);
|
|
1721
|
+
|
|
1722
|
+
for (const [path, body] of [
|
|
1723
|
+
['steer', { text: 'more', streamEpoch: 'epoch-routes' }],
|
|
1724
|
+
['follow-up', { text: 'later', streamEpoch: 'epoch-routes' }],
|
|
1725
|
+
['bash', { command: 'ls' }],
|
|
1726
|
+
]) {
|
|
1727
|
+
archive['pi-session-7'] = 5;
|
|
1728
|
+
expect((await post(`/api/pi/sessions/pi-session-7/${path}`, body)).status).toBe(202);
|
|
1729
|
+
expect(archive).toEqual({ 'pi-session-8': 6 });
|
|
1730
|
+
}
|
|
1731
|
+
expect(archiveSets).toHaveLength(4);
|
|
1732
|
+
});
|
|
1733
|
+
|
|
1734
|
+
it('keeps a send accepted when unarchiving fails', async () => {
|
|
1735
|
+
const runtime = {
|
|
1736
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1737
|
+
request: async (command) => (command === 'sessions.bash' ? { accepted: true, id: 'bash-1' } : { accepted: true, messageId: 'message-1' }),
|
|
1738
|
+
};
|
|
1739
|
+
const archiveStore = {
|
|
1740
|
+
read: async () => ({ 'pi-session-7': 5 }),
|
|
1741
|
+
set: async () => { throw Object.assign(new Error('bad'), { code: 'EIO' }); },
|
|
1742
|
+
};
|
|
1743
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1744
|
+
const app = express();
|
|
1745
|
+
app.use(express.json());
|
|
1746
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore, sessionShelfStore: { clearForActivity: async () => null } });
|
|
1747
|
+
server = await listen(app);
|
|
1748
|
+
const origin = `http://127.0.0.1:${server.address().port}`;
|
|
1749
|
+
const prompt = await fetch(`${origin}/api/pi/sessions/pi-session-7/prompt`, {
|
|
1750
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'hello', streamEpoch: 'epoch-routes' }),
|
|
1751
|
+
});
|
|
1752
|
+
expect(prompt.status).toBe(202);
|
|
1753
|
+
const bash = await fetch(`${origin}/api/pi/sessions/pi-session-7/bash`, {
|
|
1754
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'ls' }),
|
|
1755
|
+
});
|
|
1756
|
+
expect(bash.status).toBe(202);
|
|
1757
|
+
expect(warn).toHaveBeenCalledTimes(2);
|
|
1758
|
+
warn.mockRestore();
|
|
1759
|
+
});
|
|
1760
|
+
|
|
1761
|
+
it('keeps an archive change when the daemon cannot publish it', async () => {
|
|
1762
|
+
const runtime = {
|
|
1763
|
+
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
1764
|
+
request: async (command) => {
|
|
1765
|
+
if (command === 'sessions.list') return { sessions: [{ session: { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 }, updatedAt: 2 }] };
|
|
1766
|
+
if (command === 'archive.publish') throw Object.assign(new Error('old daemon'), { code: 'UNKNOWN_COMMAND' });
|
|
1767
|
+
return {};
|
|
1768
|
+
},
|
|
1769
|
+
};
|
|
1770
|
+
const archiveSets = [];
|
|
1771
|
+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1772
|
+
const app = express();
|
|
1773
|
+
app.use(express.json());
|
|
1774
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}), set: async (...args) => archiveSets.push(args) } });
|
|
1775
|
+
server = await listen(app);
|
|
1776
|
+
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-7/archive`, {
|
|
1777
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived: true }),
|
|
1778
|
+
});
|
|
1779
|
+
expect(response.status).toBe(204);
|
|
1780
|
+
expect(archiveSets).toEqual([['pi-session-7', true]]);
|
|
1781
|
+
await vi.waitFor(() => expect(warn).toHaveBeenCalled());
|
|
1782
|
+
warn.mockRestore();
|
|
1783
|
+
});
|
|
1784
|
+
|
|
1607
1785
|
it('keeps a send accepted when clearing the shelf fails', async () => {
|
|
1608
1786
|
const runtime = {
|
|
1609
1787
|
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
@@ -1613,7 +1791,7 @@ describe('Pi runtime route', () => {
|
|
|
1613
1791
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
|
1614
1792
|
const app = express();
|
|
1615
1793
|
app.use(express.json());
|
|
1616
|
-
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, sessionShelfStore });
|
|
1794
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) }, sessionShelfStore });
|
|
1617
1795
|
server = await listen(app);
|
|
1618
1796
|
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-7/prompt`, {
|
|
1619
1797
|
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'hello', streamEpoch: 'epoch-routes' }),
|
|
@@ -1732,6 +1910,8 @@ describe('Pi runtime route', () => {
|
|
|
1732
1910
|
expect((await fetch(base, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ archived: true, directory: '/other' }) })).status).toBe(204);
|
|
1733
1911
|
expect(archiveSets).toEqual([['foreign-1', true]]);
|
|
1734
1912
|
expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/other' } });
|
|
1913
|
+
// Every device hears about it, on the session's own folder.
|
|
1914
|
+
await vi.waitFor(() => expect(calls).toContainEqual({ command: 'archive.publish', payload: { sessionId: 'foreign-1', archived: true, directory: '/other' } }));
|
|
1735
1915
|
|
|
1736
1916
|
// Wrong directory fails membership without writing the sidecar.
|
|
1737
1917
|
calls.length = 0;
|
|
@@ -1740,6 +1920,7 @@ describe('Pi runtime route', () => {
|
|
|
1740
1920
|
expect(wrong.status).not.toBe(204);
|
|
1741
1921
|
expect(archiveSets).toEqual([]);
|
|
1742
1922
|
expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/focused' } });
|
|
1923
|
+
expect(calls.some((call) => call.command === 'archive.publish')).toBe(false);
|
|
1743
1924
|
});
|
|
1744
1925
|
|
|
1745
1926
|
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');
|