@pi-chamber/web 0.7.1 → 0.7.2
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/README.md +2 -1
- package/bin/cli.js +2 -2
- package/bin/cli.test.js +98 -1
- package/bin/lib/DOCUMENTATION.md +2 -1
- package/bin/lib/cli-args.js +8 -5
- package/bin/lib/cli-startup.js +10 -7
- package/bin/lib/cli-startup.test.js +28 -0
- package/bin/lib/commands-startup.js +152 -6
- package/dist/assets/{CommitSection-DuGkZ_bm.js → CommitSection-DfAlM30E.js} +1 -1
- package/dist/assets/{DiagramEditor-C7xe1Brl.js → DiagramEditor-TeJ1G_NN.js} +1 -1
- package/dist/assets/{DiagramView-BTqROEWP.js → DiagramView-DKLIwNth.js} +1 -1
- package/dist/assets/{DiffView-hcqXTjEc.js → DiffView-CZyqSs5W.js} +1 -1
- package/dist/assets/{FilesView-GadyKxta.js → FilesView-rftA7fEL.js} +1 -1
- package/dist/assets/{GitView-BKy-hYUN.js → GitView-D5LMTT2M.js} +3 -3
- package/dist/assets/{JsonTreeView-CGc4eTGI.js → JsonTreeView-DMI3-Smy.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CqfEAhPM.js → MarkdownRendererImpl-gdd-5n9J.js} +1 -1
- package/dist/assets/{PatchDiff-P17-Byb8.js → PatchDiff-GNB1NlAN.js} +1 -1
- package/dist/assets/{PierreDiffViewer-BbUCO4IF.js → PierreDiffViewer-DmJv2AoJ.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-j6KFBSe0.js → SessionSwitcherContent-CWdDPll7.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DSVeuuVL.js → SessionSwitcherDropdown-Cx-Jfmvo.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BVBBEBTg.js → SessionUnreadDot-CKe4uVcf.js} +1 -1
- package/dist/assets/{SettingsView-FnmtcWZc.js → SettingsView-DaxkNy5C.js} +3 -3
- package/dist/assets/{SettingsWindow-Bascj0V3.js → SettingsWindow-D1M_rRDo.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CPMzJ27S.js → ToolOutputDialog-CUKcp77A.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-BZSRKHHM.js → ToolPartDiffPreview-CkzwXAC5.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DFx8xsmh.js → VirtualizedFileDiff-sRc4lN0B.js} +1 -1
- package/dist/assets/{WindowsWindowControls-DIqnZ2uU.js → WindowsWindowControls-CCnU0ckO.js} +121 -121
- package/dist/assets/{collapsible-DlqZyxEY.js → collapsible-B0cIItyf.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-elCbdk6U.js → computeVirtualFileMetrics-B1uVA58l.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-BmQ7Zu-L.js → contextFileOpenGuard-BuedQ5EQ.js} +1 -1
- package/dist/assets/{index-BerHSX92.js → index-BA67uOfZ.js} +1 -1
- package/dist/assets/index-CcbDTf8Q.js +8 -0
- package/dist/assets/index-Cl3XbCeC.css +1 -0
- package/dist/assets/{isDiffPlainText-CvfRfc7h.js → isDiffPlainText-DLDFLL6P.js} +1 -1
- package/dist/assets/{isFilePlainText-_vq9Ghu3.js → isFilePlainText-B2wwrpRU.js} +1 -1
- package/dist/assets/{main-DYs-nZO6.js → main-B5k0qpHJ.js} +4 -4
- package/dist/assets/{main-DTCOwPr3.js → main-Bepu8Jr9.js} +2 -2
- package/dist/assets/{markdownCore-CzWR_p3k.js → markdownCore-BfuFM7mg.js} +1 -1
- package/dist/assets/{miniChat-C2XxEA3N.js → miniChat-Co0Snpgl.js} +2 -2
- package/dist/assets/{mobile-BQhAOqV7.js → mobile-CSvL_Zyu.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-M2bY1WKA.js → renderElectronMiniChatApp-DrMJ1RXX.js} +2 -2
- package/dist/assets/{renderMobileApp-BnpHUUhY.js → renderMobileApp-B2toAnMW.js} +4 -4
- package/dist/assets/{runtimeSurface-OhCUGSKg.js → runtimeSurface-DF3VwUlO.js} +1 -1
- package/dist/assets/{useInlineCommentController-DC0iNSYX.js → useInlineCommentController-CxMP78jg.js} +1 -1
- package/dist/assets/{usePanelSlide-aeAIo1cp.js → usePanelSlide-DUuoQt5X.js} +3 -3
- package/dist/assets/{usePushVisibilityBeacon-om5Qlrt6.js → usePushVisibilityBeacon-CSPdFBaA.js} +1 -1
- package/dist/assets/{useSwitcherItems-Bln2r_Q2.js → useSwitcherItems-zOeC2Cta.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-Dv4zaHRN.js → vendor-codemirror-language-data-C7_BPMCr.js} +2 -2
- package/dist/assets/{web-components-BOt08OHk.js → web-components-BYNCGylQ.js} +1 -1
- 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/package-manager.js +32 -1
- package/server/lib/package-manager.test.js +21 -0
- package/server/lib/pi/attachment-store.js +95 -22
- package/server/lib/pi/attachment-store.test.js +23 -0
- package/server/lib/pi/routes.js +120 -43
- package/server/lib/pi/routes.test.js +63 -2
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +2 -0
- package/server/lib/pi/session-daemon/session-daemon.js +7 -0
- package/dist/assets/index-ChFxkws4.js +0 -8
- package/dist/assets/index-DZ-f_hCQ.css +0 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { mkdir, open, rm, writeFile } from 'node:fs/promises';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
4
|
import { basename, extname, join } from 'node:path';
|
|
5
5
|
|
|
6
6
|
const MAX_ATTACHMENT_BYTES = 100 * 1024 * 1024;
|
|
7
7
|
const MAX_ATTACHMENT_COUNT = 32;
|
|
8
|
+
const MAX_ATTACHMENTS_PER_MESSAGE = 20;
|
|
8
9
|
const ATTACHMENT_TTL_MS = 60 * 60 * 1_000;
|
|
9
10
|
const REJECTED_MIME_PREFIXES = ['application/x-msdownload', 'application/x-dosexec'];
|
|
10
11
|
|
|
@@ -19,8 +20,6 @@ const invalid = () => new PiAttachmentStoreError('ATTACHMENT_FAILED');
|
|
|
19
20
|
|
|
20
21
|
const sanitizeFilename = (value) => {
|
|
21
22
|
const filename = basename(typeof value === 'string' ? value : 'attachment')
|
|
22
|
-
// The explicit control range is intentional: client-supplied filenames
|
|
23
|
-
// must never produce an ambiguous temporary-file path.
|
|
24
23
|
// eslint-disable-next-line no-control-regex
|
|
25
24
|
.replace(/[\x00-\x1f\x7f]/g, '')
|
|
26
25
|
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
|
@@ -45,9 +44,9 @@ const normalizeMime = (value) => {
|
|
|
45
44
|
};
|
|
46
45
|
|
|
47
46
|
/**
|
|
48
|
-
* Process-lifetime upload map.
|
|
49
|
-
*
|
|
50
|
-
*
|
|
47
|
+
* Process-lifetime upload map. Available uploads count against the active cap.
|
|
48
|
+
* Accepted uploads move to a retired map so repeated sends free active slots,
|
|
49
|
+
* while their files remain until the original expiry for daemon access.
|
|
51
50
|
*/
|
|
52
51
|
export const createPiAttachmentStore = ({
|
|
53
52
|
directory = join(tmpdir(), 'pichamber-pi-attachments'),
|
|
@@ -55,44 +54,118 @@ export const createPiAttachmentStore = ({
|
|
|
55
54
|
ttlMs = ATTACHMENT_TTL_MS,
|
|
56
55
|
} = {}) => {
|
|
57
56
|
const entries = new Map();
|
|
57
|
+
const retiredEntries = new Map();
|
|
58
|
+
let pendingCreates = 0;
|
|
58
59
|
|
|
59
|
-
const
|
|
60
|
-
const expired = [...
|
|
60
|
+
const cleanupMap = async (map) => {
|
|
61
|
+
const expired = [...map.values()].filter((entry) => entry.expiresAt <= now());
|
|
61
62
|
await Promise.all(expired.map(async (entry) => {
|
|
62
|
-
|
|
63
|
+
map.delete(entry.id);
|
|
63
64
|
await rm(entry.path, { force: true });
|
|
64
65
|
}));
|
|
65
66
|
};
|
|
66
67
|
|
|
67
|
-
const
|
|
68
|
+
const cleanup = async () => {
|
|
69
|
+
await Promise.all([cleanupMap(entries), cleanupMap(retiredEntries)]);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const reserve = async (filename, mime) => {
|
|
68
73
|
await cleanup();
|
|
69
|
-
if (entries.size >= MAX_ATTACHMENT_COUNT) throw new PiAttachmentStoreError('ATTACHMENT_LIMIT_REACHED');
|
|
74
|
+
if (entries.size + pendingCreates >= MAX_ATTACHMENT_COUNT) throw new PiAttachmentStoreError('ATTACHMENT_LIMIT_REACHED');
|
|
70
75
|
const safeName = sanitizeFilename(filename);
|
|
71
76
|
const safeMime = normalizeMime(mime);
|
|
72
|
-
const bytes = decodeBase64(base64);
|
|
73
|
-
const extension = extname(safeName).slice(0, 20);
|
|
74
77
|
const id = randomUUID();
|
|
78
|
+
const extension = extname(safeName).slice(0, 20);
|
|
75
79
|
const path = join(directory, `pi-clipboard-${id}${extension}`);
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
80
|
+
pendingCreates += 1;
|
|
81
|
+
try {
|
|
82
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
83
|
+
return { id, name: safeName, mime: safeMime, path, expiresAt: now() + ttlMs };
|
|
84
|
+
} catch (error) {
|
|
85
|
+
pendingCreates -= 1;
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const commit = (entry, size) => {
|
|
91
|
+
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_ATTACHMENT_BYTES) {
|
|
92
|
+
throw new PiAttachmentStoreError(size > MAX_ATTACHMENT_BYTES ? 'ATTACHMENT_TOO_LARGE' : 'ATTACHMENT_FAILED');
|
|
93
|
+
}
|
|
94
|
+
pendingCreates -= 1;
|
|
95
|
+
const committed = { ...entry, size };
|
|
96
|
+
entries.set(entry.id, committed);
|
|
97
|
+
return { id: committed.id, name: committed.name, mime: committed.mime, size, expiresAt: committed.expiresAt };
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const create = async ({ filename, mime, base64 }) => {
|
|
101
|
+
const bytes = decodeBase64(base64);
|
|
102
|
+
const entry = await reserve(filename, mime);
|
|
103
|
+
try {
|
|
104
|
+
await writeFile(entry.path, bytes, { flag: 'wx', mode: 0o600 });
|
|
105
|
+
return commit(entry, bytes.length);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (!entries.has(entry.id)) pendingCreates = Math.max(0, pendingCreates - 1);
|
|
108
|
+
await rm(entry.path, { force: true });
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const createFromStream = async ({ filename, mime, stream }) => {
|
|
114
|
+
if (!stream || typeof stream[Symbol.asyncIterator] !== 'function') throw invalid();
|
|
115
|
+
const entry = await reserve(filename, mime);
|
|
116
|
+
let handle;
|
|
117
|
+
let size = 0;
|
|
118
|
+
try {
|
|
119
|
+
handle = await open(entry.path, 'wx', 0o600);
|
|
120
|
+
for await (const chunk of stream) {
|
|
121
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
122
|
+
size += bytes.length;
|
|
123
|
+
if (size > MAX_ATTACHMENT_BYTES) throw new PiAttachmentStoreError('ATTACHMENT_TOO_LARGE');
|
|
124
|
+
if (bytes.length > 0) await handle.write(bytes);
|
|
125
|
+
}
|
|
126
|
+
await handle.close();
|
|
127
|
+
handle = undefined;
|
|
128
|
+
return commit(entry, size);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (!entries.has(entry.id)) pendingCreates = Math.max(0, pendingCreates - 1);
|
|
131
|
+
await handle?.close().catch(() => undefined);
|
|
132
|
+
await rm(entry.path, { force: true });
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
81
135
|
};
|
|
82
136
|
|
|
83
137
|
const resolve = async (ids) => {
|
|
84
138
|
await cleanup();
|
|
85
|
-
if (!Array.isArray(ids) || ids.length >
|
|
86
|
-
const selected = ids.map((id) => entries.get(id));
|
|
139
|
+
if (!Array.isArray(ids) || ids.length > MAX_ATTACHMENTS_PER_MESSAGE || ids.some((id) => typeof id !== 'string' || id.length === 0)) throw invalid();
|
|
140
|
+
const selected = ids.map((id) => entries.get(id) ?? retiredEntries.get(id));
|
|
87
141
|
if (selected.some((entry) => !entry)) throw new PiAttachmentStoreError('ATTACHMENT_MISSING');
|
|
88
142
|
return selected.map(({ id, name, mime, size, path }) => ({ id, name, mime, size, path }));
|
|
89
143
|
};
|
|
90
144
|
|
|
145
|
+
const consume = async (ids) => {
|
|
146
|
+
for (const id of ids) {
|
|
147
|
+
const entry = entries.get(id);
|
|
148
|
+
if (!entry) continue;
|
|
149
|
+
entries.delete(id);
|
|
150
|
+
retiredEntries.set(id, entry);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const remove = async (id) => {
|
|
155
|
+
if (typeof id !== 'string' || id.length === 0) throw invalid();
|
|
156
|
+
const entry = entries.get(id);
|
|
157
|
+
if (!entry) return false;
|
|
158
|
+
entries.delete(id);
|
|
159
|
+
await rm(entry.path, { force: true });
|
|
160
|
+
return true;
|
|
161
|
+
};
|
|
162
|
+
|
|
91
163
|
const dispose = async () => {
|
|
92
|
-
const current = [...entries.values()];
|
|
164
|
+
const current = [...entries.values(), ...retiredEntries.values()];
|
|
93
165
|
entries.clear();
|
|
166
|
+
retiredEntries.clear();
|
|
94
167
|
await Promise.all(current.map((entry) => rm(entry.path, { force: true })));
|
|
95
168
|
};
|
|
96
169
|
|
|
97
|
-
return { create, resolve, cleanup, dispose };
|
|
170
|
+
return { create, createFromStream, resolve, consume, remove, cleanup, dispose };
|
|
98
171
|
};
|
|
@@ -26,12 +26,35 @@ describe('Pi attachment store', () => {
|
|
|
26
26
|
await expect(readFile(privateAttachment.path, 'utf8')).resolves.toBe('hello');
|
|
27
27
|
});
|
|
28
28
|
|
|
29
|
+
it('streams binary uploads, removes unused files, and frees active slots after prompt acceptance', async () => {
|
|
30
|
+
const directory = await mkdtemp(join(tmpdir(), 'pichamber-pi-attachments-'));
|
|
31
|
+
store = createPiAttachmentStore({ directory });
|
|
32
|
+
const streamed = await store.createFromStream({
|
|
33
|
+
filename: 'stream.txt',
|
|
34
|
+
mime: 'text/plain',
|
|
35
|
+
stream: (async function* () { yield Buffer.from('hel'); yield Buffer.from('lo'); })(),
|
|
36
|
+
});
|
|
37
|
+
expect(streamed).toEqual(expect.objectContaining({ name: 'stream.txt', size: 5 }));
|
|
38
|
+
const [resolved] = await store.resolve([streamed.id]);
|
|
39
|
+
await expect(readFile(resolved.path, 'utf8')).resolves.toBe('hello');
|
|
40
|
+
|
|
41
|
+
await store.consume([streamed.id]);
|
|
42
|
+
const [retired] = await store.resolve([streamed.id]);
|
|
43
|
+
expect(retired.path).toBe(resolved.path);
|
|
44
|
+
await expect(readFile(resolved.path, 'utf8')).resolves.toBe('hello');
|
|
45
|
+
|
|
46
|
+
const unused = await store.create({ filename: 'unused.txt', mime: 'text/plain', base64: base64('x') });
|
|
47
|
+
expect(await store.remove(unused.id)).toBe(true);
|
|
48
|
+
await expect(store.resolve([unused.id])).rejects.toMatchObject({ code: 'ATTACHMENT_MISSING' });
|
|
49
|
+
});
|
|
50
|
+
|
|
29
51
|
it('rejects malformed, executable, missing, and expired uploads explicitly', async () => {
|
|
30
52
|
let now = 0;
|
|
31
53
|
store = createPiAttachmentStore({ directory: await mkdtemp(join(tmpdir(), 'pichamber-pi-attachments-')), now: () => now, ttlMs: 1 });
|
|
32
54
|
await expect(store.create({ filename: 'bad', mime: 'text/plain', base64: 'not base64!' })).rejects.toMatchObject({ code: 'ATTACHMENT_FAILED' });
|
|
33
55
|
await expect(store.create({ filename: 'bad.exe', mime: 'application/x-msdownload', base64: base64('x') })).rejects.toMatchObject({ code: 'ATTACHMENT_FAILED' });
|
|
34
56
|
await expect(store.resolve(['missing'])).rejects.toBeInstanceOf(PiAttachmentStoreError);
|
|
57
|
+
await expect(store.resolve(Array.from({ length: 21 }, (_, index) => `attachment-${index}`))).rejects.toMatchObject({ code: 'ATTACHMENT_FAILED' });
|
|
35
58
|
|
|
36
59
|
const attachment = await store.create({ filename: 'note.txt', mime: 'text/plain', base64: base64('x') });
|
|
37
60
|
now = 2;
|
package/server/lib/pi/routes.js
CHANGED
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
|
|
6
6
|
import { createPiArchiveStore } from './archive-store.js';
|
|
7
7
|
import { createPiAttachmentStore } from './attachment-store.js';
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
checkForUpdates,
|
|
10
|
+
launchUpdateCommand,
|
|
11
|
+
resolveTrustedUpdatePackageManager,
|
|
12
|
+
} from '../package-manager.js';
|
|
9
13
|
import { listPiCustomThemes } from './custom-themes.js';
|
|
10
14
|
import { createPiSettingsStore } from './settings-store.js';
|
|
11
15
|
import { isPiThinkingLevel } from './thinking-levels.js';
|
|
@@ -39,7 +43,17 @@ const UNAVAILABLE_CODES = new Set([
|
|
|
39
43
|
|
|
40
44
|
const writeDaemonError = (res, error) => {
|
|
41
45
|
const code = typeof error?.code === 'string' ? error.code : 'DAEMON_REQUEST_FAILED';
|
|
42
|
-
const status = UNAVAILABLE_CODES.has(code)
|
|
46
|
+
const status = UNAVAILABLE_CODES.has(code)
|
|
47
|
+
? 503
|
|
48
|
+
: code === 'INVALID_SESSION'
|
|
49
|
+
? 404
|
|
50
|
+
: code === 'ATTACHMENT_TOO_LARGE'
|
|
51
|
+
? 413
|
|
52
|
+
: code === 'ATTACHMENT_LIMIT_REACHED'
|
|
53
|
+
? 429
|
|
54
|
+
: code === 'ATTACHMENT_MISSING'
|
|
55
|
+
? 410
|
|
56
|
+
: 400;
|
|
43
57
|
res.status(status).json({ error: { code } });
|
|
44
58
|
};
|
|
45
59
|
|
|
@@ -246,6 +260,7 @@ const projectSessionDetail = (value) => {
|
|
|
246
260
|
...(compaction ? { compaction } : {}),
|
|
247
261
|
...(Number.isFinite(value.runStartedAt) ? { runStartedAt: Math.floor(value.runStartedAt) } : {}),
|
|
248
262
|
...(Number.isFinite(value.serverNow) ? { serverNow: Math.floor(value.serverNow) } : {}),
|
|
263
|
+
...projectExtensionSnapshotState(value),
|
|
249
264
|
};
|
|
250
265
|
};
|
|
251
266
|
|
|
@@ -439,6 +454,48 @@ export const projectExtensionList = (result) => {
|
|
|
439
454
|
return { directory: result.directory, extensions, commands };
|
|
440
455
|
};
|
|
441
456
|
|
|
457
|
+
function projectExtensionSnapshotState(snapshot) {
|
|
458
|
+
const extensionStatuses = Array.isArray(snapshot.extensionStatuses)
|
|
459
|
+
? snapshot.extensionStatuses.filter((entry) => entry && typeof entry.key === 'string' && typeof entry.text === 'string' && entry.key.length > 0 && entry.key.length <= 128 && entry.text.length <= 1000).slice(0, 50).map((entry) => ({ key: entry.key.slice(0, 128), text: entry.text.slice(0, 1000) }))
|
|
460
|
+
: undefined;
|
|
461
|
+
const extensionWidgets = Array.isArray(snapshot.extensionWidgets)
|
|
462
|
+
? snapshot.extensionWidgets.filter((entry) => entry && typeof entry.key === 'string' && Array.isArray(entry.lines) && entry.key.length > 0 && entry.key.length <= 128 && entry.lines.length <= 100).slice(0, 50).map((entry) => ({
|
|
463
|
+
key: entry.key.slice(0, 128),
|
|
464
|
+
lines: entry.lines.filter((line) => typeof line === 'string').map((line) => line.slice(0, 2000)).slice(0, 100),
|
|
465
|
+
...(entry.placement === 'belowEditor' ? { placement: 'belowEditor' } : { placement: 'aboveEditor' }),
|
|
466
|
+
}))
|
|
467
|
+
: undefined;
|
|
468
|
+
const extensionDialogs = Array.isArray(snapshot.extensionDialogs)
|
|
469
|
+
? snapshot.extensionDialogs.filter((entry) => entry && typeof entry.requestId === 'string' && typeof entry.method === 'string' && typeof entry.title === 'string').slice(0, 20).map((entry) => ({
|
|
470
|
+
requestId: entry.requestId.slice(0, 512),
|
|
471
|
+
method: ['select', 'confirm', 'input', 'editor', 'form'].includes(entry.method) ? entry.method : 'confirm',
|
|
472
|
+
title: entry.title.slice(0, 512),
|
|
473
|
+
...(typeof entry.message === 'string' ? { message: entry.message.slice(0, 2000) } : {}),
|
|
474
|
+
...(Array.isArray(entry.options) ? { options: entry.options.filter((option) => typeof option === 'string').map((option) => option.slice(0, 256)).slice(0, 20) } : {}),
|
|
475
|
+
...(typeof entry.placeholder === 'string' ? { placeholder: entry.placeholder.slice(0, 512) } : {}),
|
|
476
|
+
...(typeof entry.prefill === 'string' ? { prefill: entry.prefill.slice(0, 10000) } : {}),
|
|
477
|
+
...(Array.isArray(entry.fields) ? { fields: sanitizeExtensionFormFields(entry.fields) } : {}),
|
|
478
|
+
...(Number.isFinite(entry.timeoutMs) ? { timeoutMs: Math.floor(entry.timeoutMs) } : {}),
|
|
479
|
+
}))
|
|
480
|
+
: undefined;
|
|
481
|
+
const extensionPanels = Array.isArray(snapshot.extensionPanels)
|
|
482
|
+
? snapshot.extensionPanels.filter((entry) => entry && typeof entry.id === 'string' && entry.id.length > 0).slice(0, 24).map(projectExtensionPanelPayload)
|
|
483
|
+
: undefined;
|
|
484
|
+
const extensionApps = Array.isArray(snapshot.extensionApps)
|
|
485
|
+
? snapshot.extensionApps.filter((entry) => entry && typeof entry.appId === 'string' && entry.appId.length > 0 && typeof entry.html === 'string' && entry.html.length > 0).slice(0, 8).map(projectExtensionAppPayload)
|
|
486
|
+
: undefined;
|
|
487
|
+
return {
|
|
488
|
+
...(extensionStatuses ? { extensionStatuses } : {}),
|
|
489
|
+
...(extensionWidgets ? { extensionWidgets } : {}),
|
|
490
|
+
...(extensionDialogs ? { extensionDialogs } : {}),
|
|
491
|
+
...(extensionPanels ? { extensionPanels } : {}),
|
|
492
|
+
...(extensionApps ? { extensionApps } : {}),
|
|
493
|
+
...(typeof snapshot.extensionTitle === 'string' && snapshot.extensionTitle.length > 0
|
|
494
|
+
? { extensionTitle: snapshot.extensionTitle.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 256) }
|
|
495
|
+
: {}),
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
442
499
|
export const projectEventFrame = (frame) => {
|
|
443
500
|
if (!frame || frame.kind !== 'event' || typeof frame.event !== 'string' || !Number.isSafeInteger(frame.sequence)
|
|
444
501
|
|| !frame.payload || typeof frame.payload.sessionId !== 'string' || typeof frame.payload.directory !== 'string') return null;
|
|
@@ -447,35 +504,7 @@ export const projectEventFrame = (frame) => {
|
|
|
447
504
|
switch (frame.event) {
|
|
448
505
|
case 'session.snapshot': {
|
|
449
506
|
const snapshot = frame.payload;
|
|
450
|
-
const
|
|
451
|
-
? snapshot.extensionStatuses.filter((entry) => entry && typeof entry.key === 'string' && typeof entry.text === 'string' && entry.key.length > 0 && entry.key.length <= 128 && entry.text.length <= 1000).slice(0, 50).map((entry) => ({ key: entry.key.slice(0, 128), text: entry.text.slice(0, 1000) }))
|
|
452
|
-
: undefined;
|
|
453
|
-
const snapshotExtensionWidgets = Array.isArray(snapshot.extensionWidgets)
|
|
454
|
-
? snapshot.extensionWidgets.filter((entry) => entry && typeof entry.key === 'string' && Array.isArray(entry.lines) && entry.key.length > 0 && entry.key.length <= 128 && entry.lines.length <= 100).slice(0, 50).map((entry) => ({
|
|
455
|
-
key: entry.key.slice(0, 128),
|
|
456
|
-
lines: entry.lines.filter((line) => typeof line === 'string').map((line) => line.slice(0, 2000)).slice(0, 100),
|
|
457
|
-
...(entry.placement === 'belowEditor' ? { placement: 'belowEditor' } : { placement: 'aboveEditor' }),
|
|
458
|
-
}))
|
|
459
|
-
: undefined;
|
|
460
|
-
const snapshotExtensionDialogs = Array.isArray(snapshot.extensionDialogs)
|
|
461
|
-
? snapshot.extensionDialogs.filter((entry) => entry && typeof entry.requestId === 'string' && typeof entry.method === 'string' && typeof entry.title === 'string').slice(0, 20).map((entry) => ({
|
|
462
|
-
requestId: entry.requestId.slice(0, 512),
|
|
463
|
-
method: ['select', 'confirm', 'input', 'editor', 'form'].includes(entry.method) ? entry.method : 'confirm',
|
|
464
|
-
title: entry.title.slice(0, 512),
|
|
465
|
-
...(typeof entry.message === 'string' ? { message: entry.message.slice(0, 2000) } : {}),
|
|
466
|
-
...(Array.isArray(entry.options) ? { options: entry.options.filter((option) => typeof option === 'string').map((option) => option.slice(0, 256)).slice(0, 20) } : {}),
|
|
467
|
-
...(typeof entry.placeholder === 'string' ? { placeholder: entry.placeholder.slice(0, 512) } : {}),
|
|
468
|
-
...(typeof entry.prefill === 'string' ? { prefill: entry.prefill.slice(0, 10000) } : {}),
|
|
469
|
-
...(Array.isArray(entry.fields) ? { fields: sanitizeExtensionFormFields(entry.fields) } : {}),
|
|
470
|
-
...(Number.isFinite(entry.timeoutMs) ? { timeoutMs: Math.floor(entry.timeoutMs) } : {}),
|
|
471
|
-
}))
|
|
472
|
-
: undefined;
|
|
473
|
-
const snapshotExtensionPanels = Array.isArray(snapshot.extensionPanels)
|
|
474
|
-
? snapshot.extensionPanels.filter((entry) => entry && typeof entry.id === 'string' && entry.id.length > 0).slice(0, 24).map(projectExtensionPanelPayload)
|
|
475
|
-
: undefined;
|
|
476
|
-
const snapshotExtensionApps = Array.isArray(snapshot.extensionApps)
|
|
477
|
-
? snapshot.extensionApps.filter((entry) => entry && typeof entry.appId === 'string' && entry.appId.length > 0 && typeof entry.html === 'string' && entry.html.length > 0).slice(0, 8).map(projectExtensionAppPayload)
|
|
478
|
-
: undefined;
|
|
507
|
+
const extensionSnapshot = projectExtensionSnapshotState(snapshot);
|
|
479
508
|
const lifecycle = ['idle', 'busy', 'retry', 'error', 'interrupted'].includes(snapshot.lifecycle) ? snapshot.lifecycle : 'idle';
|
|
480
509
|
const retry = lifecycle === 'retry' ? projectRetryInfo(snapshot.retry) : null;
|
|
481
510
|
const compaction = projectCompactionInfo(snapshot.compaction);
|
|
@@ -492,14 +521,7 @@ export const projectEventFrame = (frame) => {
|
|
|
492
521
|
...(Number.isFinite(snapshot.runStartedAt) ? { runStartedAt: Math.floor(snapshot.runStartedAt) } : {}),
|
|
493
522
|
...(Number.isFinite(snapshot.serverNow) ? { serverNow: Math.floor(snapshot.serverNow) } : {}),
|
|
494
523
|
lastSequence: Number.isSafeInteger(snapshot.lastSequence) ? snapshot.lastSequence : frame.sequence,
|
|
495
|
-
...
|
|
496
|
-
...(snapshotExtensionWidgets ? { extensionWidgets: snapshotExtensionWidgets } : {}),
|
|
497
|
-
...(snapshotExtensionDialogs ? { extensionDialogs: snapshotExtensionDialogs } : {}),
|
|
498
|
-
...(snapshotExtensionPanels ? { extensionPanels: snapshotExtensionPanels } : {}),
|
|
499
|
-
...(snapshotExtensionApps ? { extensionApps: snapshotExtensionApps } : {}),
|
|
500
|
-
...(typeof snapshot.extensionTitle === 'string' && snapshot.extensionTitle.length > 0
|
|
501
|
-
? { extensionTitle: snapshot.extensionTitle.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 256) }
|
|
502
|
-
: {}),
|
|
524
|
+
...extensionSnapshot,
|
|
503
525
|
} } };
|
|
504
526
|
}
|
|
505
527
|
case 'session.lifecycle': {
|
|
@@ -726,6 +748,8 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
726
748
|
uiSettingsStore = createPiUiSettingsStore(),
|
|
727
749
|
listCustomThemes = listPiCustomThemes,
|
|
728
750
|
updateChecker = checkForUpdates,
|
|
751
|
+
updateLauncher = launchUpdateCommand,
|
|
752
|
+
resolveUpdatePackageManager = resolveTrustedUpdatePackageManager,
|
|
729
753
|
smallModelGenerator = async (input) => (await import('./small-model-generation.js')).generateWithSmallModel(input),
|
|
730
754
|
eventHeartbeatMs = 15_000,
|
|
731
755
|
}) => {
|
|
@@ -775,12 +799,31 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
775
799
|
currentVersion: typeof req.query.currentVersion === 'string' ? req.query.currentVersion : undefined,
|
|
776
800
|
appType: typeof req.query.appType === 'string' ? req.query.appType : undefined,
|
|
777
801
|
platform: typeof req.query.platform === 'string' ? req.query.platform : undefined,
|
|
802
|
+
instanceMode: typeof req.query.instanceMode === 'string' ? req.query.instanceMode : undefined,
|
|
778
803
|
}));
|
|
779
804
|
} catch {
|
|
780
805
|
res.status(503).json({ error: 'Update check unavailable' });
|
|
781
806
|
}
|
|
782
807
|
});
|
|
783
808
|
|
|
809
|
+
app.post('/api/pi/update-install', (_req, res) => {
|
|
810
|
+
const packageManager = resolveUpdatePackageManager();
|
|
811
|
+
if (!packageManager) {
|
|
812
|
+
res.status(409).json({
|
|
813
|
+
success: false,
|
|
814
|
+
error: 'This PiChamber copy is not a supported global package-manager install. Run: pichamber update',
|
|
815
|
+
});
|
|
816
|
+
return;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const result = updateLauncher();
|
|
820
|
+
if (!result.success) {
|
|
821
|
+
res.status(409).json({ success: false, error: result.error });
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
res.json({ success: true, autoRestart: true });
|
|
825
|
+
});
|
|
826
|
+
|
|
784
827
|
app.get('/api/pi/runtime', async (_req, res) => {
|
|
785
828
|
const runtime = getPiSessionDaemonRuntime();
|
|
786
829
|
if (!runtime) {
|
|
@@ -1292,10 +1335,12 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1292
1335
|
for (const [suffix, command] of [['prompt', 'sessions.prompt'], ['steer', 'sessions.steer'], ['follow-up', 'sessions.followUp']]) {
|
|
1293
1336
|
app.post(`/api/pi/sessions/:sessionId/${suffix}`, async (req, res) => {
|
|
1294
1337
|
let payload = req.body && typeof req.body === 'object' ? req.body : {};
|
|
1338
|
+
let attachmentIds = [];
|
|
1295
1339
|
try {
|
|
1296
1340
|
if (payload.attachments !== undefined) {
|
|
1297
1341
|
if (!Array.isArray(payload.attachments) || payload.attachments.some((attachment) => !attachment || typeof attachment.id !== 'string')) throw protocolMismatch();
|
|
1298
|
-
|
|
1342
|
+
attachmentIds = payload.attachments.map((attachment) => attachment.id);
|
|
1343
|
+
const attachments = await attachmentStore.resolve(attachmentIds);
|
|
1299
1344
|
payload = { ...payload, attachments };
|
|
1300
1345
|
}
|
|
1301
1346
|
} catch (error) {
|
|
@@ -1308,6 +1353,7 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1308
1353
|
writeDaemonError(res, protocolMismatch());
|
|
1309
1354
|
return;
|
|
1310
1355
|
}
|
|
1356
|
+
await attachmentStore.consume?.(attachmentIds);
|
|
1311
1357
|
res.status(202).json({ accepted: true, messageId: result.messageId });
|
|
1312
1358
|
}
|
|
1313
1359
|
});
|
|
@@ -1332,10 +1378,41 @@ export const registerPiRuntimeRoutes = (app, {
|
|
|
1332
1378
|
|
|
1333
1379
|
app.post('/api/pi/attachments', async (req, res) => {
|
|
1334
1380
|
try {
|
|
1335
|
-
const
|
|
1381
|
+
const isBinary = req.is('application/octet-stream');
|
|
1382
|
+
let attachment;
|
|
1383
|
+
if (isBinary) {
|
|
1384
|
+
const encodedFilename = req.get('x-pichamber-filename');
|
|
1385
|
+
const mime = req.get('x-pichamber-mime');
|
|
1386
|
+
if (!encodedFilename || encodedFilename.length > 2_048 || !mime || mime.length > 200) throw Object.assign(new Error('Invalid attachment metadata'), { code: 'ATTACHMENT_FAILED' });
|
|
1387
|
+
let filename;
|
|
1388
|
+
try {
|
|
1389
|
+
filename = decodeURIComponent(encodedFilename);
|
|
1390
|
+
} catch {
|
|
1391
|
+
throw Object.assign(new Error('Invalid attachment metadata'), { code: 'ATTACHMENT_FAILED' });
|
|
1392
|
+
}
|
|
1393
|
+
attachment = await attachmentStore.createFromStream({ filename, mime, stream: req });
|
|
1394
|
+
} else {
|
|
1395
|
+
attachment = await attachmentStore.create(req.body ?? {});
|
|
1396
|
+
}
|
|
1336
1397
|
if (!attachment || typeof attachment.id !== 'string' || typeof attachment.name !== 'string'
|
|
1337
|
-
|| typeof attachment.mime !== 'string' || !Number.isSafeInteger(attachment.size)
|
|
1338
|
-
|
|
1398
|
+
|| typeof attachment.mime !== 'string' || !Number.isSafeInteger(attachment.size)
|
|
1399
|
+
|| !Number.isFinite(attachment.expiresAt)) throw protocolMismatch();
|
|
1400
|
+
res.status(201).json({ attachment: {
|
|
1401
|
+
id: attachment.id,
|
|
1402
|
+
name: attachment.name,
|
|
1403
|
+
mime: attachment.mime,
|
|
1404
|
+
size: attachment.size,
|
|
1405
|
+
expiresAt: attachment.expiresAt,
|
|
1406
|
+
} });
|
|
1407
|
+
} catch (error) {
|
|
1408
|
+
writeDaemonError(res, error);
|
|
1409
|
+
}
|
|
1410
|
+
});
|
|
1411
|
+
|
|
1412
|
+
app.delete('/api/pi/attachments/:attachmentId', async (req, res) => {
|
|
1413
|
+
try {
|
|
1414
|
+
await attachmentStore.remove(req.params.attachmentId);
|
|
1415
|
+
res.status(204).end();
|
|
1339
1416
|
} catch (error) {
|
|
1340
1417
|
writeDaemonError(res, error);
|
|
1341
1418
|
}
|
|
@@ -84,6 +84,8 @@ describe('Pi runtime route', () => {
|
|
|
84
84
|
},
|
|
85
85
|
listCustomThemes: async () => [{ metadata: { id: 'custom' } }],
|
|
86
86
|
updateChecker: async () => ({ available: false, currentVersion: '1.0.0' }),
|
|
87
|
+
resolveUpdatePackageManager: () => 'npm',
|
|
88
|
+
updateLauncher: () => ({ success: true }),
|
|
87
89
|
});
|
|
88
90
|
server = await listen(app);
|
|
89
91
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
@@ -98,6 +100,26 @@ describe('Pi runtime route', () => {
|
|
|
98
100
|
})).json()).resolves.toEqual({ exists: true, version: 1, foldersMap: {}, collapsedFolderIds: [], updatedAt: 1 });
|
|
99
101
|
await expect((await fetch(`${base}/api/pi/themes`)).json()).resolves.toEqual({ themes: [{ metadata: { id: 'custom' } }] });
|
|
100
102
|
await expect((await fetch(`${base}/api/pi/update-check`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0' });
|
|
103
|
+
const installResponse = await fetch(`${base}/api/pi/update-install`, { method: 'POST' });
|
|
104
|
+
expect(installResponse.status).toBe(200);
|
|
105
|
+
await expect(installResponse.json()).resolves.toEqual({ success: true, autoRestart: true });
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('rejects web updates when the current install is not owned by a trusted package manager', async () => {
|
|
109
|
+
const app = express();
|
|
110
|
+
registerPiRuntimeRoutes(app, {
|
|
111
|
+
getPiSessionDaemonRuntime: () => null,
|
|
112
|
+
resolveUpdatePackageManager: () => null,
|
|
113
|
+
updateLauncher: () => { throw new Error('must not run'); },
|
|
114
|
+
});
|
|
115
|
+
server = await listen(app);
|
|
116
|
+
|
|
117
|
+
const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/update-install`, { method: 'POST' });
|
|
118
|
+
expect(response.status).toBe(409);
|
|
119
|
+
await expect(response.json()).resolves.toEqual({
|
|
120
|
+
success: false,
|
|
121
|
+
error: 'This PiChamber copy is not a supported global package-manager install. Run: pichamber update',
|
|
122
|
+
});
|
|
101
123
|
});
|
|
102
124
|
|
|
103
125
|
it('generates a task name with the configured small model without exposing model details', async () => {
|
|
@@ -307,7 +329,7 @@ describe('Pi runtime route', () => {
|
|
|
307
329
|
it('uploads opaque attachments and resolves them only across the private prompt adapter', async () => {
|
|
308
330
|
const calls = [];
|
|
309
331
|
const attachmentStore = {
|
|
310
|
-
create: async (input) => ({ id: 'attachment-1', name: input.filename, mime: input.mime, size: 3, path: '/never-public' }),
|
|
332
|
+
create: async (input) => ({ id: 'attachment-1', name: input.filename, mime: input.mime, size: 3, expiresAt: 3_600_000, path: '/never-public' }),
|
|
311
333
|
resolve: async (ids) => {
|
|
312
334
|
expect(ids).toEqual(['attachment-1']);
|
|
313
335
|
return [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }];
|
|
@@ -327,12 +349,49 @@ describe('Pi runtime route', () => {
|
|
|
327
349
|
|
|
328
350
|
const upload = await fetch(`${base}/attachments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: 'note.txt', mime: 'text/plain', base64: 'YWJj' }) });
|
|
329
351
|
expect(upload.status).toBe(201);
|
|
330
|
-
await expect(upload.json()).resolves.toEqual({ attachment: { id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3 } });
|
|
352
|
+
await expect(upload.json()).resolves.toEqual({ attachment: { id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, expiresAt: 3_600_000 } });
|
|
331
353
|
const prompt = await fetch(`${base}/sessions/session-1/prompt`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'read this', attachments: [{ id: 'attachment-1' }] }) });
|
|
332
354
|
expect(prompt.status).toBe(202);
|
|
333
355
|
expect(calls).toEqual([{ command: 'sessions.prompt', payload: { sessionId: 'session-1', text: 'read this', attachments: [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }] } }]);
|
|
334
356
|
});
|
|
335
357
|
|
|
358
|
+
it('streams binary attachments with bounded metadata and deletes unused uploads', async () => {
|
|
359
|
+
const calls = [];
|
|
360
|
+
const attachmentStore = {
|
|
361
|
+
createFromStream: async ({ filename, mime, stream }) => {
|
|
362
|
+
const chunks = [];
|
|
363
|
+
for await (const chunk of stream) chunks.push(chunk);
|
|
364
|
+
calls.push({ filename, mime, body: Buffer.concat(chunks).toString('utf8') });
|
|
365
|
+
return { id: 'binary-1', name: filename, mime, size: 5, expiresAt: 4_000 };
|
|
366
|
+
},
|
|
367
|
+
remove: async (id) => calls.push({ removed: id }),
|
|
368
|
+
};
|
|
369
|
+
const app = express();
|
|
370
|
+
app.use(express.json());
|
|
371
|
+
registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => null, attachmentStore });
|
|
372
|
+
server = await listen(app);
|
|
373
|
+
const base = `http://127.0.0.1:${server.address().port}/api/pi/attachments`;
|
|
374
|
+
|
|
375
|
+
const upload = await fetch(base, {
|
|
376
|
+
method: 'POST',
|
|
377
|
+
headers: {
|
|
378
|
+
'Content-Type': 'application/octet-stream',
|
|
379
|
+
'X-PiChamber-Filename': encodeURIComponent('notes ü.txt'),
|
|
380
|
+
'X-PiChamber-Mime': 'text/plain',
|
|
381
|
+
},
|
|
382
|
+
body: 'hello',
|
|
383
|
+
});
|
|
384
|
+
expect(upload.status).toBe(201);
|
|
385
|
+
await expect(upload.json()).resolves.toEqual({
|
|
386
|
+
attachment: { id: 'binary-1', name: 'notes ü.txt', mime: 'text/plain', size: 5, expiresAt: 4_000 },
|
|
387
|
+
});
|
|
388
|
+
expect((await fetch(`${base}/binary-1`, { method: 'DELETE' })).status).toBe(204);
|
|
389
|
+
expect(calls).toEqual([
|
|
390
|
+
{ filename: 'notes ü.txt', mime: 'text/plain', body: 'hello' },
|
|
391
|
+
{ removed: 'binary-1' },
|
|
392
|
+
]);
|
|
393
|
+
});
|
|
394
|
+
|
|
336
395
|
it('proxies a cwd-scoped session collection without exposing private daemon details', async () => {
|
|
337
396
|
const runtime = {
|
|
338
397
|
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: ['sessions.list'] }),
|
|
@@ -452,6 +511,7 @@ describe('Pi runtime route', () => {
|
|
|
452
511
|
isStreaming: true,
|
|
453
512
|
lifecycle: 'retry',
|
|
454
513
|
retry: { attempt: 2, next: 5_000, message: 'provider request timed out' },
|
|
514
|
+
extensionStatuses: [{ key: 'mode', text: 'mode:economy/xhigh' }],
|
|
455
515
|
};
|
|
456
516
|
const runtime = {
|
|
457
517
|
health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
|
|
@@ -479,6 +539,7 @@ describe('Pi runtime route', () => {
|
|
|
479
539
|
isStreaming: true,
|
|
480
540
|
lifecycle: 'retry',
|
|
481
541
|
retry: { attempt: 2, next: 5_000, message: 'provider request timed out' },
|
|
542
|
+
extensionStatuses: [{ key: 'mode', text: 'mode:economy/xhigh' }],
|
|
482
543
|
});
|
|
483
544
|
const promptResponse = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-4/prompt`, {
|
|
484
545
|
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello' }),
|
|
@@ -10,7 +10,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
|
|
|
10
10
|
- `extension-bridge.js` owns extension UI bindings, pending dialog lifecycle, normalized status/widget/panel/app state, snapshot projection, and extension event publication. `session-daemon.js` supplies runtime lookup, publication, redaction, and directory dependencies through its narrow factory interface.
|
|
11
11
|
- `session-daemon.js`
|
|
12
12
|
- `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` in rpc-like mode with a daemon-owned UI bridge, so pi extensions load exactly as they do under the Pi CLI's RPC mode. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
|
|
13
|
-
- Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces;
|
|
13
|
+
- Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces; extension live state is kept in per-session maps and included in both `sessions.open` and `session.snapshot`. The open response must cover every extension event at or below its `lastSequence`, so first attach cannot skip one-time startup statuses before the browser stream connects; reconnect snapshots rebuild the same live panels. TUI-only component replacement, footers, and themes remain intentional no-ops; standard RPC editor replacement and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
|
|
14
14
|
- `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
|
|
15
15
|
- `daemon-process.js` is the detached private-process entrypoint. It reads the daemon credential from its owner-only sidecar, starts the socket, writes non-secret identity state only after readiness, and removes only its own state on signal shutdown.
|
|
16
16
|
- `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
|
|
@@ -295,6 +295,8 @@ describe('Pi session daemon extension bridging', () => {
|
|
|
295
295
|
ui.setStatus('my-ext', 'Processing…');
|
|
296
296
|
const status = await client.next((message) => message.event === 'extension.status');
|
|
297
297
|
expect(status.payload).toMatchObject({ key: 'my-ext', text: 'Processing…' });
|
|
298
|
+
const opened = await client.request('sessions.open', { sessionId: session.sessionId });
|
|
299
|
+
expect(opened.result.extensionStatuses).toEqual([{ key: 'my-ext', text: 'Processing…' }]);
|
|
298
300
|
ui.setStatus('my-ext', undefined);
|
|
299
301
|
const cleared = await client.next((message) => message.event === 'extension.status' && !message.payload?.text);
|
|
300
302
|
expect(cleared.payload.key).toBe('my-ext');
|
|
@@ -998,6 +998,7 @@ export function createSessionDaemon({
|
|
|
998
998
|
const isStreaming = session.isStreaming === true;
|
|
999
999
|
const retry = retryStateBySession.get(session.sessionId);
|
|
1000
1000
|
const compaction = compactionStateFor(session);
|
|
1001
|
+
const extensionSnapshot = extensionBridge.getSnapshotState(session.sessionId);
|
|
1001
1002
|
return {
|
|
1002
1003
|
session: {
|
|
1003
1004
|
id: session.sessionId, directory: targetDir, createdAt, updatedAt: createdAt,
|
|
@@ -1014,6 +1015,12 @@ export function createSessionDaemon({
|
|
|
1014
1015
|
...(compaction ? { compaction } : {}),
|
|
1015
1016
|
...(activeRunStartedAt.has(session.sessionId) ? { runStartedAt: activeRunStartedAt.get(session.sessionId) } : {}),
|
|
1016
1017
|
serverNow: Date.now(),
|
|
1018
|
+
...(extensionSnapshot.statuses ? { extensionStatuses: extensionSnapshot.statuses } : {}),
|
|
1019
|
+
...(extensionSnapshot.widgets ? { extensionWidgets: extensionSnapshot.widgets } : {}),
|
|
1020
|
+
...(extensionSnapshot.dialogs ? { extensionDialogs: extensionSnapshot.dialogs } : {}),
|
|
1021
|
+
...(extensionSnapshot.panels ? { extensionPanels: extensionSnapshot.panels } : {}),
|
|
1022
|
+
...(extensionSnapshot.apps ? { extensionApps: extensionSnapshot.apps } : {}),
|
|
1023
|
+
...(extensionSnapshot.title ? { extensionTitle: extensionSnapshot.title } : {}),
|
|
1017
1024
|
};
|
|
1018
1025
|
};
|
|
1019
1026
|
|