@pi-chamber/web 0.7.0 → 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-BL61C8nr.js → CommitSection-DfAlM30E.js} +1 -1
- package/dist/assets/{DiagramEditor-CH_gE8Ho.js → DiagramEditor-TeJ1G_NN.js} +1 -1
- package/dist/assets/{DiagramView-D5PsfvzH.js → DiagramView-DKLIwNth.js} +1 -1
- package/dist/assets/{DiffView-CP49mbz0.js → DiffView-CZyqSs5W.js} +3 -3
- package/dist/assets/{FilesView-DQ0jIXPf.js → FilesView-rftA7fEL.js} +4 -4
- package/dist/assets/{GitView-BvIVUn8p.js → GitView-D5LMTT2M.js} +3 -3
- package/dist/assets/{JsonTreeView-4xkZ1oUB.js → JsonTreeView-DMI3-Smy.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-BYiITelR.js → MarkdownRendererImpl-gdd-5n9J.js} +1 -1
- package/dist/assets/{PatchDiff-cYVpwvLs.js → PatchDiff-GNB1NlAN.js} +1 -1
- package/dist/assets/{PierreDiffViewer-CxTRnaw4.js → PierreDiffViewer-DmJv2AoJ.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-C_kE1AkY.js → SessionSwitcherContent-CWdDPll7.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CCXNg-hd.js → SessionSwitcherDropdown-Cx-Jfmvo.js} +2 -2
- package/dist/assets/{SessionUnreadDot-DcLebnEm.js → SessionUnreadDot-CKe4uVcf.js} +1 -1
- package/dist/assets/SettingsView-DaxkNy5C.js +4 -0
- package/dist/assets/{SettingsWindow-BCfEIGLV.js → SettingsWindow-D1M_rRDo.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CG3Djpaw.js → ToolOutputDialog-CUKcp77A.js} +5 -5
- package/dist/assets/{ToolPartDiffPreview-Bno_Kf_v.js → ToolPartDiffPreview-CkzwXAC5.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CtTCV9aT.js → VirtualizedFileDiff-sRc4lN0B.js} +3 -3
- package/dist/assets/{WindowsWindowControls-C1cyCACC.js → WindowsWindowControls-CCnU0ckO.js} +122 -122
- package/dist/assets/{collapsible-Y0lXAGWU.js → collapsible-B0cIItyf.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-Ygq8IDgM.js → computeVirtualFileMetrics-B1uVA58l.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-CdZD2lzt.js → contextFileOpenGuard-BuedQ5EQ.js} +1 -1
- package/dist/assets/{index-Cl-EsRzi.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-BOtu3iWK.js → isDiffPlainText-DLDFLL6P.js} +1 -1
- package/dist/assets/{isFilePlainText-DZkgwQ85.js → isFilePlainText-B2wwrpRU.js} +1 -1
- package/dist/assets/main-B5k0qpHJ.js +133 -0
- package/dist/assets/{main-hi9Mn-Bi.js → main-Bepu8Jr9.js} +2 -2
- package/dist/assets/{markdownCore-BnziCWjq.js → markdownCore-BfuFM7mg.js} +2 -2
- package/dist/assets/{miniChat-jlNYy4Yo.js → miniChat-Co0Snpgl.js} +2 -2
- package/dist/assets/{mobile-B2J6RZei.js → mobile-CSvL_Zyu.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-D2j7dJjx.js → renderElectronMiniChatApp-DrMJ1RXX.js} +2 -2
- package/dist/assets/{renderMobileApp-DRMRL_Rc.js → renderMobileApp-B2toAnMW.js} +4 -4
- package/dist/assets/{runtimeSurface-DRCRpZ4U.js → runtimeSurface-DF3VwUlO.js} +1 -1
- package/dist/assets/{useInlineCommentController-BafZc9gs.js → useInlineCommentController-CxMP78jg.js} +2 -2
- package/dist/assets/usePanelSlide-DUuoQt5X.js +56 -0
- package/dist/assets/{usePushVisibilityBeacon-C6yhoKax.js → usePushVisibilityBeacon-CSPdFBaA.js} +2 -2
- package/dist/assets/{useSwitcherItems-D4fvD6XH.js → useSwitcherItems-zOeC2Cta.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-DOlAvLSI.js → vendor-codemirror-language-data-C7_BPMCr.js} +2 -2
- package/dist/assets/{web-components-CDndDwR4.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 +32 -3
- package/dist/assets/SettingsView-CfpCOseW.js +0 -4
- package/dist/assets/index--zDkVFU6.css +0 -1
- package/dist/assets/index-CiQblNLS.js +0 -8
- package/dist/assets/main-BlGDTFM8.js +0 -133
- package/dist/assets/usePanelSlide-C4DKnekW.js +0 -56
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { spawnSync } from 'child_process';
|
|
1
|
+
import { spawn, spawnSync } from 'child_process';
|
|
2
2
|
import fs from 'fs';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { fileURLToPath } from 'url';
|
|
@@ -775,6 +775,37 @@ export async function checkForUpdates(options = {}) {
|
|
|
775
775
|
/**
|
|
776
776
|
* Execute the update (used by CLI)
|
|
777
777
|
*/
|
|
778
|
+
export function launchUpdateCommand(options = {}) {
|
|
779
|
+
const isContainer = options.isContainer ?? (fs.existsSync('/.dockerenv') || Boolean(process.env.CONTAINER) || process.env.container === 'docker');
|
|
780
|
+
const isSystemd = options.isSystemd ?? Boolean(process.env.INVOCATION_ID || process.env.PICHAMBER_SYSTEMD_UNIT);
|
|
781
|
+
if (isContainer) {
|
|
782
|
+
return {
|
|
783
|
+
success: false,
|
|
784
|
+
error: 'Docker deployments must be updated by deploying a new container image. Run: pichamber update',
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
if (isSystemd) {
|
|
788
|
+
return {
|
|
789
|
+
success: false,
|
|
790
|
+
error: 'This PiChamber server runs as a systemd service. Run from a terminal: pichamber update',
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const cliPath = path.resolve(__dirname, '..', '..', 'bin', 'cli.js');
|
|
795
|
+
try {
|
|
796
|
+
const child = (options.spawnProcess || spawn)(process.execPath, [cliPath, 'update', '--quiet'], {
|
|
797
|
+
detached: true,
|
|
798
|
+
stdio: 'ignore',
|
|
799
|
+
windowsHide: true,
|
|
800
|
+
});
|
|
801
|
+
child.once?.('error', () => {});
|
|
802
|
+
child.unref();
|
|
803
|
+
return { success: true };
|
|
804
|
+
} catch {
|
|
805
|
+
return { success: false, error: 'Could not start the updater. Run: pichamber update' };
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
778
809
|
export function executeUpdate(pm = detectPackageManager(), options = {}) {
|
|
779
810
|
const command = getUpdateCommand(pm);
|
|
780
811
|
if (!options?.silent) {
|
|
@@ -11,6 +11,7 @@ const {
|
|
|
11
11
|
detectPackageManager,
|
|
12
12
|
executeUpdate,
|
|
13
13
|
getCurrentVersion,
|
|
14
|
+
launchUpdateCommand,
|
|
14
15
|
resolveTrustedUpdatePackageManager,
|
|
15
16
|
} = await import('./package-manager.js');
|
|
16
17
|
|
|
@@ -363,6 +364,26 @@ describe('getCurrentVersion', () => {
|
|
|
363
364
|
});
|
|
364
365
|
});
|
|
365
366
|
|
|
367
|
+
describe('launchUpdateCommand', () => {
|
|
368
|
+
it('starts the CLI updater detached so the live server can respond before shutdown', () => {
|
|
369
|
+
const unref = vi.fn();
|
|
370
|
+
const spawnProcess = vi.fn(() => ({ unref }));
|
|
371
|
+
|
|
372
|
+
expect(launchUpdateCommand({ isContainer: false, isSystemd: false, spawnProcess })).toEqual({ success: true });
|
|
373
|
+
expect(spawnProcess).toHaveBeenCalledWith(
|
|
374
|
+
process.execPath,
|
|
375
|
+
[expect.stringMatching(/bin[\\/]cli\.js$/), 'update', '--quiet'],
|
|
376
|
+
{ detached: true, stdio: 'ignore', windowsHide: true },
|
|
377
|
+
);
|
|
378
|
+
expect(unref).toHaveBeenCalledOnce();
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
it('refuses deployment types that the CLI cannot safely replace in-process', () => {
|
|
382
|
+
expect(launchUpdateCommand({ isContainer: true, isSystemd: false }).success).toBe(false);
|
|
383
|
+
expect(launchUpdateCommand({ isContainer: false, isSystemd: true }).success).toBe(false);
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
|
|
366
387
|
describe('CLI update exports', () => {
|
|
367
388
|
it('exports package-manager helpers used by the update command', () => {
|
|
368
389
|
expect(typeof detectPackageManager).toBe('function');
|
|
@@ -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' }),
|