@pi-chamber/web 0.9.1 → 0.9.3

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.
Files changed (55) hide show
  1. package/README.md +2 -2
  2. package/bin/lib/cli-paths.js +22 -6
  3. package/dist/assets/{DiagramEditor-DoEOH0hY.js → DiagramEditor-DuGmiPZ5.js} +1 -1
  4. package/dist/assets/{DiagramView-y9Ystuhv.js → DiagramView-CV-iReyY.js} +1 -1
  5. package/dist/assets/{DiffView-ScM4XoqZ.js → DiffView-DVd1MLPB.js} +1 -1
  6. package/dist/assets/{FilesView-CjkhMFqJ.js → FilesView-CPnW4I90.js} +1 -1
  7. package/dist/assets/{GitView-Bqi6H8I-.js → GitView-Dj_7hgX_.js} +3 -3
  8. package/dist/assets/{JsonTreeView-DWhlH6NK.js → JsonTreeView-Cyy0lEZR.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-CEOKZ1qH.js → MarkdownRendererImpl-BXN78Wu_.js} +1 -1
  10. package/dist/assets/{PatchDiff-ClnfJJ2J.js → PatchDiff-C7dA3U29.js} +1 -1
  11. package/dist/assets/{SessionSwitcherContent-e6JzUXD_.js → SessionSwitcherContent-dr3g9DR7.js} +1 -1
  12. package/dist/assets/{SessionSwitcherDropdown-C4etG8dv.js → SessionSwitcherDropdown-C3zdd82V.js} +2 -2
  13. package/dist/assets/{SessionUnreadDot-BVTSwRiG.js → SessionUnreadDot-qeik5qtT.js} +1 -1
  14. package/dist/assets/{SettingsView-C0S0Sx-S.js → SettingsView-C57uV1YS.js} +2 -2
  15. package/dist/assets/{SettingsWindow-Cy9tmnMg.js → SettingsWindow-Bbay2W76.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-Csrc0Uk2.js → ToolOutputDialog-CRTiN1CH.js} +1 -1
  17. package/dist/assets/{ToolPartDiffPreview-6oH6KD44.js → ToolPartDiffPreview-CqnNcLPk.js} +1 -1
  18. package/dist/assets/{VirtualizedFileDiff-DJNcTQNp.js → VirtualizedFileDiff-iqwryMNU.js} +1 -1
  19. package/dist/assets/{collapsible-DxgVLhi9.js → collapsible-szfZ0Syc.js} +1 -1
  20. package/dist/assets/{computeVirtualFileMetrics-B-WoeBMW.js → computeVirtualFileMetrics-Bbugxxtp.js} +1 -1
  21. package/dist/assets/{contextFileOpenGuard-DQ4U9xRH.js → contextFileOpenGuard-BC3ie230.js} +1 -1
  22. package/dist/assets/{gitStatusPredicates-CIFSGjJs.js → gitStatusPredicates-DbThKVSf.js} +1 -1
  23. package/dist/assets/{index-D2C3q2xD.js → index-KIdiBFJs.js} +1 -1
  24. package/dist/assets/{index-DmNPBaSo.js → index-v6K3L94m.js} +1 -1
  25. package/dist/assets/{isDiffPlainText-CrvpUauF.js → isDiffPlainText-Dl0RBjPZ.js} +1 -1
  26. package/dist/assets/{isFilePlainText-CKvhS32g.js → isFilePlainText-CbrmvrM6.js} +1 -1
  27. package/dist/assets/{main-CjM7g4Gq.js → main-4PkIvzf4.js} +3 -3
  28. package/dist/assets/{main-BFv8slLp.js → main-DMyWi0qs.js} +2 -2
  29. package/dist/assets/{markdownCore-DKrraAqT.js → markdownCore-BD5WkOKU.js} +1 -1
  30. package/dist/assets/{miniChat-hQnLS5mt.js → miniChat-CLMNhna4.js} +2 -2
  31. package/dist/assets/{mobile-DuXOBGs_.js → mobile-rWMDwhtQ.js} +2 -2
  32. package/dist/assets/{renderElectronMiniChatApp-ClJBZVGy.js → renderElectronMiniChatApp-BRhGNRJ8.js} +2 -2
  33. package/dist/assets/{renderMobileApp-DofX2wjB.js → renderMobileApp-DLy2YoQg.js} +3 -3
  34. package/dist/assets/{runtimeEndpointReset-BZeYg6eN.js → runtimeEndpointReset-Z9YtcHxZ.js} +15 -15
  35. package/dist/assets/{runtimeSurface-C7CBxDbh.js → runtimeSurface-CySRuLbN.js} +1 -1
  36. package/dist/assets/{useAppFontEffects-Cs0f1dKn.js → useAppFontEffects-DfuJVB15.js} +85 -85
  37. package/dist/assets/{useFilesViewSearch-D1hcbBEc.js → useFilesViewSearch-BZBHrZ90.js} +1 -1
  38. package/dist/assets/{usePushVisibilityBeacon-DqHkuVS5.js → usePushVisibilityBeacon-BxTkEajM.js} +1 -1
  39. package/dist/assets/{useSwitcherItems-BEoW7LlC.js → useSwitcherItems-jITqE8PV.js} +1 -1
  40. package/dist/assets/{vendor-codemirror-language-data-B8Ac62S_.js → vendor-codemirror-language-data-CDdfwzlS.js} +2 -2
  41. package/dist/assets/{web-components-Dy-Tz_LJ.js → web-components-C9wXMuCp.js} +1 -1
  42. package/dist/index.html +3 -3
  43. package/dist/mini-chat.html +2 -2
  44. package/dist/mobile.html +2 -2
  45. package/package.json +1 -1
  46. package/server/lib/pi/routes.js +35 -1
  47. package/server/lib/pi/routes.test.js +53 -0
  48. package/server/lib/pi/session-daemon/DOCUMENTATION.md +4 -4
  49. package/server/lib/pi/session-daemon/ipc-client.js +20 -9
  50. package/server/lib/pi/session-daemon/ipc-client.test.js +88 -0
  51. package/server/lib/pi/session-daemon/ipc-protocol.js +9 -0
  52. package/server/lib/pi/session-daemon/session-daemon.js +127 -26
  53. package/server/lib/pi/session-daemon/session-daemon.test.js +141 -0
  54. package/server/lib/pi/ui-settings-store.js +130 -25
  55. package/server/lib/pi/ui-settings-store.test.js +58 -7
@@ -6,6 +6,7 @@ import { homedir, tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
  import { StringDecoder } from 'node:string_decoder';
8
8
 
9
+ import { requestSessionDaemon } from './ipc-client.js';
9
10
  import { createMessageEntryAliases } from './message-entry-aliases.js';
10
11
  import { createSessionDaemon as createSessionDaemonImpl, isLocalSessionDaemonEndpoint } from './session-daemon.js';
11
12
 
@@ -1241,6 +1242,146 @@ describe('Pi session daemon spike', () => {
1241
1242
  await client.close();
1242
1243
  }, 2_000);
1243
1244
 
1245
+ it('opens a transcript whose complete projection exceeds the IPC frame limit', async () => {
1246
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-paged-transcript-'));
1247
+ const endpoint = testDaemonEndpoint(root);
1248
+ const persistedSessionFile = join(root, 'persisted.jsonl');
1249
+ await writeFile(persistedSessionFile, `{"type":"session","id":"pi-session-paged","cwd":"${root}"}\n`);
1250
+ const session = new FakeSession('pi-session-paged', persistedSessionFile);
1251
+ const largeOutput = 'A'.repeat(1_100_000);
1252
+ session.entries = [{
1253
+ type: 'message',
1254
+ id: 'user-0',
1255
+ timestamp: '2026-01-01T00:00:00.000Z',
1256
+ message: { role: 'user', content: 'Inspect the large fixture.' },
1257
+ }, ...Array.from({ length: 17 }, (_, index) => [{
1258
+ type: 'message',
1259
+ id: `assistant-${index}`,
1260
+ timestamp: new Date(Date.UTC(2026, 0, 1, 0, 0, index * 2)).toISOString(),
1261
+ message: {
1262
+ role: 'assistant',
1263
+ provider: 'test',
1264
+ model: 'model',
1265
+ content: [{ type: 'toolCall', id: `tool-${index}`, name: 'read', arguments: { index } }],
1266
+ },
1267
+ }, {
1268
+ type: 'message',
1269
+ id: `result-${index}`,
1270
+ timestamp: new Date(Date.UTC(2026, 0, 1, 0, 0, index * 2 + 1)).toISOString(),
1271
+ message: {
1272
+ role: 'toolResult',
1273
+ toolCallId: `tool-${index}`,
1274
+ toolName: 'read',
1275
+ content: [{ type: 'text', text: largeOutput }],
1276
+ isError: false,
1277
+ },
1278
+ }]).flat()];
1279
+ const runtime = new FakeRuntime({ cwd: root, session });
1280
+ daemon = createSessionDaemon({
1281
+ endpoint,
1282
+ credential,
1283
+ cwd: root,
1284
+ createRuntime: async () => runtime,
1285
+ listSessions: async () => [{
1286
+ path: persistedSessionFile,
1287
+ id: 'pi-session-paged',
1288
+ cwd: root,
1289
+ created: new Date('2026-01-01T00:00:00.000Z'),
1290
+ modified: new Date('2026-01-01T00:00:01.000Z'),
1291
+ messageCount: session.entries.length,
1292
+ }],
1293
+ });
1294
+ await daemon.start();
1295
+
1296
+ const opened = await requestSessionDaemon({
1297
+ endpoint,
1298
+ credential,
1299
+ command: 'sessions.open',
1300
+ payload: { sessionId: 'pi-session-paged', directory: root },
1301
+ });
1302
+
1303
+ expect(opened.messages.length).toBeLessThan(17);
1304
+ expect(opened.hasMoreBefore).toBe(true);
1305
+ expect(typeof opened.beforeCursor).toBe('string');
1306
+ expect(Buffer.byteLength(JSON.stringify(opened))).toBeLessThan(16 * 1024 * 1024);
1307
+
1308
+ const pages = [opened.messages];
1309
+ let before = opened.beforeCursor;
1310
+ while (before) {
1311
+ const page = await requestSessionDaemon({
1312
+ endpoint,
1313
+ credential,
1314
+ command: 'sessions.messages',
1315
+ payload: { sessionId: 'pi-session-paged', directory: root, before },
1316
+ });
1317
+ pages.unshift(page.messages);
1318
+ before = page.beforeCursor;
1319
+ }
1320
+ const messages = pages.flat();
1321
+ const uniqueMessages = [...new Map(messages.map((entry) => [entry.message.id, entry])).values()];
1322
+ expect(uniqueMessages.map((entry) => entry.message.id)).toEqual([
1323
+ 'user-0',
1324
+ ...Array.from({ length: 17 }, (_, index) => `assistant-${index}`),
1325
+ ]);
1326
+ expect(uniqueMessages.filter((entry) => entry.message.role === 'assistant')
1327
+ .every((entry) => entry.parts[0].output === largeOutput)).toBe(true);
1328
+ expect(opened.messages.some((entry) => entry.message.id === 'user-0')).toBe(true);
1329
+ }, 30_000);
1330
+
1331
+ it('reports a single unpageable message as too large instead of malformed', async () => {
1332
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-oversized-'));
1333
+ const endpoint = testDaemonEndpoint(root);
1334
+ const persistedSessionFile = join(root, 'persisted.jsonl');
1335
+ await writeFile(persistedSessionFile, `{"type":"session","id":"pi-session-oversized","cwd":"${root}"}\n`);
1336
+ const session = new FakeSession('pi-session-oversized', persistedSessionFile);
1337
+ const hugeOutput = 'B'.repeat(17 * 1024 * 1024);
1338
+ session.entries = [{
1339
+ type: 'message',
1340
+ id: 'assistant-huge',
1341
+ timestamp: '2026-01-01T00:00:02.000Z',
1342
+ message: {
1343
+ role: 'assistant',
1344
+ provider: 'test',
1345
+ model: 'model',
1346
+ content: [{ type: 'toolCall', id: 'huge-tool', name: 'read', arguments: {} }],
1347
+ },
1348
+ }, {
1349
+ type: 'message',
1350
+ id: 'result-huge',
1351
+ timestamp: '2026-01-01T00:00:03.000Z',
1352
+ message: {
1353
+ role: 'toolResult',
1354
+ toolCallId: 'huge-tool',
1355
+ toolName: 'read',
1356
+ content: [{ type: 'text', text: hugeOutput }],
1357
+ isError: false,
1358
+ },
1359
+ }];
1360
+ const runtime = new FakeRuntime({ cwd: root, session });
1361
+ daemon = createSessionDaemon({
1362
+ endpoint,
1363
+ credential,
1364
+ cwd: root,
1365
+ createRuntime: async () => runtime,
1366
+ listSessions: async () => [{
1367
+ path: persistedSessionFile,
1368
+ id: 'pi-session-oversized',
1369
+ cwd: root,
1370
+ created: new Date('2026-01-01T00:00:00.000Z'),
1371
+ modified: new Date('2026-01-01T00:00:01.000Z'),
1372
+ messageCount: 1,
1373
+ }],
1374
+ });
1375
+ await daemon.start();
1376
+
1377
+ await expect(requestSessionDaemon({
1378
+ endpoint,
1379
+ credential,
1380
+ command: 'sessions.open',
1381
+ payload: { sessionId: 'pi-session-oversized', directory: root },
1382
+ })).rejects.toMatchObject({ code: 'DAEMON_RESPONSE_TOO_LARGE' });
1383
+ }, 30_000);
1384
+
1244
1385
  it('keeps Pi global/project defaults and trust decisions authoritative', async () => {
1245
1386
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-settings-'));
1246
1387
  const cwd = join(root, 'project');
@@ -6,6 +6,58 @@ import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
6
6
  import { withCrossProcessLock } from '../server/cross-process-lock.js';
7
7
 
8
8
  const MAX_SETTINGS_BYTES = 2 * 1024 * 1024;
9
+ const PORTABLE_SETTINGS_MARKER = '__pichamberSettingsScope';
10
+ const PORTABLE_SETTINGS_VERSION = 'portable-v1';
11
+
12
+ // Keep this list explicit. settings.json is intended to be copied between hosts.
13
+ const PORTABLE_FIELDS = new Set([
14
+ 'themeId', 'useSystemTheme', 'themeVariant', 'lightThemeId', 'darkThemeId',
15
+ 'splashBgLight', 'splashFgLight', 'splashBgDark', 'splashFgDark',
16
+ 'showReasoningTraces', 'collapsibleThinkingBlocks', 'collapseThinkingByDefault',
17
+ 'showDeletionDialog', 'nativeNotificationsEnabled', 'notificationMode',
18
+ 'notifyOnSubtasks', 'notifyOnCompletion', 'notifyOnError', 'notifyOnQuestion',
19
+ 'notificationTemplates', 'summarizeLastMessage', 'summaryThreshold', 'summaryLength',
20
+ 'maxLastMessageLength', 'usageAutoRefresh', 'usageRefreshIntervalMs',
21
+ 'usageDisplayMode', 'usageShowPredValues', 'usageDropdownProviders',
22
+ 'usageSelectedModels', 'usageCollapsedFamilies', 'usageExpandedFamilies', 'usageModelGroups',
23
+ 'autoDeleteEnabled', 'autoSaveEnabled', 'autoDeleteAfterDays', 'sessionRetentionAction',
24
+ 'defaultModel', 'defaultVariant', 'smallModelUseDefault', 'smallModelOverride',
25
+ 'walkthroughModelOverride', 'followUpBehavior', 'queueModeEnabled', 'gitmojiEnabled',
26
+ 'defaultFileViewerPreview', 'zenModel', 'gitProviderId', 'gitModelId',
27
+ 'inputSpellcheckEnabled', 'showToolFileIcons', 'codeBlockLineWrap', 'showTurnChangedFiles',
28
+ 'showExpandedBashTools', 'showExpandedEditTools', 'timeFormatPreference',
29
+ 'weekStartPreference', 'mermaidRenderingMode', 'userMessageRenderingMode',
30
+ 'collapsibleUserMessages', 'stickyUserHeader', 'promptNavigatorEnabled',
31
+ 'expandedEditorToolbar', 'wideChatLayoutEnabled', 'showSplitAssistantMessageActions',
32
+ 'fontSize', 'terminalFontSize', 'editorFontSize', 'uiFont', 'monoFont', 'padding',
33
+ 'cornerRadius', 'inputBarOffset', 'shortcutOverrides', 'commandTriggers',
34
+ 'favoriteModels', 'hiddenModels', 'collapsedModelProviders', 'recentModels',
35
+ 'recentAgents', 'recentEfforts', 'diffLayoutPreference', 'gitChangesViewMode',
36
+ 'directoryShowHidden', 'filesViewShowGitignored', 'messageLimit',
37
+ 'responseStyleEnabled', 'responseStylePreset', 'responseStyleCustomInstructions',
38
+ 'draftStarters', 'draftStartersVisible', 'draftStartersScheduleTaskAdded',
39
+ 'autoCreateWorktree', 'globalBehaviorPrompt', 'skillCatalogs', 'messageStreamTransport',
40
+ ]);
41
+
42
+ // These values describe one host or device. Secrets are local too, so they can
43
+ // still be consumed by the existing authenticated API without entering the
44
+ // portable file.
45
+ const LOCAL_FIELDS = new Set([
46
+ 'lastDirectory', 'homeDirectory', 'projects', 'activeProjectId',
47
+ 'securityScopedBookmarks', 'pinnedDirectories', 'defaultGitIdentityId', 'openInAppId',
48
+ 'terminalShell', 'terminalLoginShells', 'desktopLanAccessEnabled',
49
+ 'desktopKeepAwakeEnabled', 'desktopProcessPerformanceRecordingEnabled',
50
+ 'desktopMinimizeToTrayEnabled', 'desktopMacMenuBarEnabled',
51
+ 'desktopWindowControlsPosition', 'desktopWindowControlsStyle',
52
+ 'desktopWindowState', 'desktopLocalPort', 'desktopInstallId', 'desktopHosts',
53
+ 'desktopDefaultHostId', 'desktopInitialHostChoiceCompleted',
54
+ 'pwaAppName', 'pwaOrientation', 'mobileKeyboardMode',
55
+ 'tunnelProvider', 'tunnelMode', 'tunnelBootstrapTtlMs', 'tunnelSessionTtlMs',
56
+ 'managedLocalTunnelConfigPath', 'managedRemoteTunnelHostname',
57
+ 'managedRemoteTunnelPresets', 'managedRemoteTunnelSelectedPresetId',
58
+ 'managedRemoteTunnelToken', 'managedRemoteTunnelPresetTokens',
59
+ 'hasManagedRemoteTunnelToken', 'desktopUiPassword', 'desktopLocalClientToken',
60
+ ]);
9
61
 
10
62
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
11
63
 
@@ -28,42 +80,95 @@ const validateRecord = (value) => {
28
80
  return value;
29
81
  };
30
82
 
83
+ const selectFields = (value, fields) => Object.fromEntries(
84
+ Object.entries(value).filter(([key]) => fields.has(key)),
85
+ );
86
+
87
+ const readRecord = async (file, fs) => {
88
+ try {
89
+ const raw = await fs.readFile(file, 'utf8');
90
+ if (Buffer.byteLength(raw) > MAX_SETTINGS_BYTES) throw new Error('UI_SETTINGS_INVALID');
91
+ return validateRecord(JSON.parse(raw));
92
+ } catch (error) {
93
+ if (error?.code === 'ENOENT') return {};
94
+ if (error?.message === 'UI_SETTINGS_INVALID') throw error;
95
+ throw new Error('UI_SETTINGS_INVALID');
96
+ }
97
+ };
98
+
99
+ const writeRecord = async (file, value, fs) => {
100
+ const serialized = `${JSON.stringify(value, null, 2)}\n`;
101
+ if (Buffer.byteLength(serialized) > MAX_SETTINGS_BYTES) throw new Error('UI_SETTINGS_INVALID');
102
+ const parent = dirname(file);
103
+ await fs.mkdir(parent, { recursive: true, mode: 0o700 });
104
+ const temporary = `${file}.tmp-${process.pid}-${randomUUID()}`;
105
+ await fs.writeFile(temporary, serialized, { encoding: 'utf8', mode: 0o600 });
106
+ await fs.rename(temporary, file);
107
+ if (process.platform !== 'win32') await fs.chmod(file, 0o600);
108
+ };
109
+
31
110
  export const createPiUiSettingsStore = ({
32
111
  file = join(resolvePiChamberDataDir(), 'settings.json'),
112
+ runtimeFile = join(dirname(file), 'runtime-state.json'),
33
113
  fs = { chmod, mkdir, readFile, rename, writeFile },
34
114
  } = {}) => {
35
115
  let mutation = Promise.resolve();
36
116
 
37
- const read = async () => {
38
- try {
39
- const raw = await fs.readFile(file, 'utf8');
40
- if (Buffer.byteLength(raw) > MAX_SETTINGS_BYTES) throw new Error('UI_SETTINGS_INVALID');
41
- return validateRecord(JSON.parse(raw));
42
- } catch (error) {
43
- if (error?.code === 'ENOENT') return {};
44
- if (error?.message === 'UI_SETTINGS_INVALID') throw error;
45
- throw new Error('UI_SETTINGS_INVALID');
117
+ const readLocked = async () => {
118
+ const portableRoot = await readRecord(file, fs);
119
+ const runtimeRoot = await readRecord(runtimeFile, fs);
120
+ const migrated = portableRoot[PORTABLE_SETTINGS_MARKER] === PORTABLE_SETTINGS_VERSION;
121
+
122
+ if (!migrated) {
123
+ const migratedRuntime = {
124
+ ...selectFields(runtimeRoot, LOCAL_FIELDS),
125
+ ...selectFields(portableRoot, LOCAL_FIELDS),
126
+ };
127
+ const migratedPortable = {
128
+ [PORTABLE_SETTINGS_MARKER]: PORTABLE_SETTINGS_VERSION,
129
+ ...selectFields(portableRoot, PORTABLE_FIELDS),
130
+ };
131
+ // Local state goes first. A failure cannot strand host state only in a
132
+ // portable file that a later successful write might replace.
133
+ await writeRecord(runtimeFile, migratedRuntime, fs);
134
+ await writeRecord(file, migratedPortable, fs);
135
+ return { ...selectFields(migratedPortable, PORTABLE_FIELDS), ...selectFields(migratedRuntime, LOCAL_FIELDS) };
46
136
  }
137
+
138
+ return {
139
+ ...selectFields(portableRoot, PORTABLE_FIELDS),
140
+ ...selectFields(runtimeRoot, LOCAL_FIELDS),
141
+ };
47
142
  };
48
143
 
144
+ const runMutation = (operation) => {
145
+ const next = mutation.then(() => withCrossProcessLock(`${file}.lock`, operation));
146
+ mutation = next.catch(() => {});
147
+ return next;
148
+ };
149
+
150
+ const read = () => runMutation(readLocked);
151
+
49
152
  const write = async (changes) => {
50
153
  validateRecord(changes);
51
- const operation = mutation.then(() => withCrossProcessLock(`${file}.lock`, async () => {
52
- const current = await read();
53
- const next = { ...current, ...changes };
54
- const serialized = `${JSON.stringify(next, null, 2)}\n`;
55
- if (Buffer.byteLength(serialized) > MAX_SETTINGS_BYTES) throw new Error('UI_SETTINGS_INVALID');
56
- const parent = dirname(file);
57
- await fs.mkdir(parent, { recursive: true, mode: 0o700 });
58
- const temporary = `${file}.tmp-${process.pid}-${randomUUID()}`;
59
- await fs.writeFile(temporary, serialized, { encoding: 'utf8', mode: 0o600 });
60
- await fs.rename(temporary, file);
61
- if (process.platform !== 'win32') await fs.chmod(file, 0o600);
62
- return next;
63
- }));
64
- mutation = operation.catch(() => {});
65
- return operation;
154
+ return runMutation(async () => {
155
+ const current = await readLocked();
156
+ const portableChanges = selectFields(changes, PORTABLE_FIELDS);
157
+ const localChanges = selectFields(changes, LOCAL_FIELDS);
158
+ const nextPortable = {
159
+ [PORTABLE_SETTINGS_MARKER]: PORTABLE_SETTINGS_VERSION,
160
+ ...selectFields(current, PORTABLE_FIELDS),
161
+ ...portableChanges,
162
+ };
163
+ const nextRuntime = {
164
+ ...selectFields(current, LOCAL_FIELDS),
165
+ ...localChanges,
166
+ };
167
+ await writeRecord(runtimeFile, nextRuntime, fs);
168
+ await writeRecord(file, nextPortable, fs);
169
+ return { ...selectFields(nextPortable, PORTABLE_FIELDS), ...selectFields(nextRuntime, LOCAL_FIELDS) };
170
+ });
66
171
  };
67
172
 
68
- return { file, read, write };
173
+ return { file, runtimeFile, read, write };
69
174
  };
@@ -8,28 +8,79 @@ import { createPiUiSettingsStore } from './ui-settings-store.js';
8
8
  const makeStore = async () => {
9
9
  const root = await mkdtemp(join(tmpdir(), 'pichamber-ui-settings-'));
10
10
  const file = join(root, 'settings.json');
11
- return { file, store: createPiUiSettingsStore({ file }) };
11
+ const runtimeFile = join(root, 'runtime-state.json');
12
+ return { file, runtimeFile, store: createPiUiSettingsStore({ file, runtimeFile }) };
12
13
  };
13
14
 
15
+ const readJson = async (file) => JSON.parse(await readFile(file, 'utf8'));
16
+
14
17
  describe('Pi UI settings store', () => {
15
- it('distinguishes a missing file from malformed persisted settings', async () => {
18
+ it('distinguishes malformed persisted settings from a fresh store', async () => {
16
19
  const { file, store } = await makeStore();
17
20
  await expect(store.read()).resolves.toEqual({});
18
21
  await writeFile(file, '{broken');
19
22
  await expect(store.read()).rejects.toThrow('UI_SETTINGS_INVALID');
20
23
  });
21
24
 
22
- it('serializes merge writes without dropping unrelated fields', async () => {
23
- const { file, store } = await makeStore();
25
+ it('migrates a flat settings file into portable and local allowlists', async () => {
26
+ const { file, runtimeFile, store } = await makeStore();
27
+ await writeFile(file, JSON.stringify({
28
+ themeId: 'nord',
29
+ homeDirectory: '/old-home',
30
+ projects: [{ id: 'old', path: '/old-home/project' }],
31
+ desktopUiPassword: 'secret',
32
+ unknownField: 'drop-me',
33
+ }));
34
+
35
+ await expect(store.read()).resolves.toMatchObject({
36
+ themeId: 'nord',
37
+ homeDirectory: '/old-home',
38
+ projects: [{ id: 'old', path: '/old-home/project' }],
39
+ desktopUiPassword: 'secret',
40
+ });
41
+ await expect(readJson(file)).resolves.toEqual({
42
+ __pichamberSettingsScope: 'portable-v1',
43
+ themeId: 'nord',
44
+ });
45
+ await expect(readJson(runtimeFile)).resolves.toEqual({
46
+ homeDirectory: '/old-home',
47
+ projects: [{ id: 'old', path: '/old-home/project' }],
48
+ desktopUiPassword: 'secret',
49
+ });
50
+ });
51
+
52
+ it('does not apply local fields copied in from another home', async () => {
53
+ const source = await makeStore();
54
+ await source.store.write({ themeId: 'nord', homeDirectory: '/mnt/data', projects: [{ id: 'one', path: '/mnt/data/project' }] });
55
+
56
+ const target = await makeStore();
57
+ await target.store.write({ homeDirectory: '/root', projects: [{ id: 'two', path: '/root/project' }] });
58
+ await writeFile(target.file, await readFile(source.file));
59
+
60
+ await expect(target.store.read()).resolves.toEqual({
61
+ themeId: 'nord',
62
+ homeDirectory: '/root',
63
+ projects: [{ id: 'two', path: '/root/project' }],
64
+ });
65
+ });
66
+
67
+ it('serializes scoped merge writes without dropping unrelated fields', async () => {
68
+ const { file, runtimeFile, store } = await makeStore();
24
69
  await Promise.all([
25
- store.write({ themeMode: 'dark' }),
70
+ store.write({ themeId: 'dark' }),
26
71
  store.write({ projects: [{ id: 'one', path: '/one' }] }),
27
72
  ]);
28
73
  await expect(store.read()).resolves.toEqual({
29
- themeMode: 'dark',
74
+ themeId: 'dark',
75
+ projects: [{ id: 'one', path: '/one' }],
76
+ });
77
+ await expect(readJson(file)).resolves.toEqual({
78
+ __pichamberSettingsScope: 'portable-v1',
79
+ themeId: 'dark',
80
+ });
81
+ await expect(readJson(runtimeFile)).resolves.toEqual({
30
82
  projects: [{ id: 'one', path: '/one' }],
31
83
  });
32
- expect(JSON.parse(await readFile(file, 'utf8'))).toMatchObject({ themeMode: 'dark' });
33
84
  });
34
85
 
35
86
  it('rejects prototype-polluting keys', async () => {