@pi-chamber/web 1.0.6-rc.3 → 1.0.6-rc.4

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 (129) hide show
  1. package/dist/assets/{DiagramView-Dq5w8TCG.js → DiagramView-BZ--w7Lh.js} +1 -1
  2. package/dist/assets/DiffView-Dtn6otnT.js +18 -0
  3. package/dist/assets/{FileSaveConflictDialog-dFqLbFzT.js → FileSaveConflictDialog-p1ik30al.js} +2 -2
  4. package/dist/assets/FilesView-D0Z0VmQm.js +6 -0
  5. package/dist/assets/{GitHubDetailScaffold-B2HRjT8V.js → GitHubDetailScaffold-a27RksFo.js} +4 -4
  6. package/dist/assets/{GitHubLinkPicker-D7I3J9_O.js → GitHubLinkPicker-B0CfzNfk.js} +1 -1
  7. package/dist/assets/GitHubListPrimitives-LFdR70l6.js +1 -0
  8. package/dist/assets/GitView-BNkoaVYl.js +9 -0
  9. package/dist/assets/{IssuesSurface-Bya7OsRl.js → IssuesSurface-D4kD7_VW.js} +3 -3
  10. package/dist/assets/{JsonTreeView-BJr5kBg4.js → JsonTreeView-CEiJsFnP.js} +1 -1
  11. package/dist/assets/MarkdownRendererImpl-418ChlsN.js +12 -0
  12. package/dist/assets/{PatchDiff-B6RBZULC.js → PatchDiff-BtOv_oLB.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-YJJQkE7t.js → PierreDiffViewer-CkuyY9ne.js} +15 -3
  14. package/dist/assets/{PullRequestsSurface-D8JpzP5l.js → PullRequestsSurface-PML07zr-.js} +2 -2
  15. package/dist/assets/SessionSwitcherContent-DkfjRgwv.js +1 -0
  16. package/dist/assets/{SessionSwitcherDropdown-CEAid1Bd.js → SessionSwitcherDropdown-CEw8BEs6.js} +2 -2
  17. package/dist/assets/SessionUnreadDot-DXUn8-ss.js +1 -0
  18. package/dist/assets/SettingsView-BvUeFUqw.js +6 -0
  19. package/dist/assets/{SettingsWindow-5dK-buUn.js → SettingsWindow-D03Z9QyW.js} +1 -1
  20. package/dist/assets/{StickyHorizontalScrollbar-p7EbL2-E.js → StickyHorizontalScrollbar-CONTbZgX.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-gITobhpo.js → ToolOutputDialog-DibddNlz.js} +5 -5
  22. package/dist/assets/{ToolPartDiffPreview-nOJxBl-Y.js → ToolPartDiffPreview-Bx7T1M2f.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-BmJk6XJm.js → VirtualizedFileDiff-BY-mDMT8.js} +4 -4
  24. package/dist/assets/{Virtualizer-DNJrJKVb.js → Virtualizer-cIf8dSOQ.js} +1 -1
  25. package/dist/assets/{collapsible-0yfy07W2.js → collapsible-BhQdnj8G.js} +1 -1
  26. package/dist/assets/{computeVirtualFileMetrics-BCFpa-1q.js → computeVirtualFileMetrics-CzkFqhaU.js} +1 -1
  27. package/dist/assets/{contextFileOpenGuard-BCi5nTZp.js → contextFileOpenGuard-CjCOK8EB.js} +1 -1
  28. package/dist/assets/fileTreeStatus-CPTpyKOV.js +7 -0
  29. package/dist/assets/gitStatusPredicates-_GNbGCCb.js +1 -0
  30. package/dist/assets/{githubLink-CCmFsyTF.js → githubLink-CwIFogWd.js} +2 -2
  31. package/dist/assets/index-Cfrwo5uQ.js +11 -0
  32. package/dist/assets/index-D7k62S9M.css +1 -0
  33. package/dist/assets/{index-BaeFf5Q8.js → index-DjOKW10B.js} +1 -1
  34. package/dist/assets/main-1wmEZ4Is.js +137 -0
  35. package/dist/assets/{main-CgXs2e27.js → main-C51a3z3b.js} +2 -2
  36. package/dist/assets/{markdownCore-DTNVLpYS.js → markdownCore-Dsr6dY5C.js} +1 -1
  37. package/dist/assets/{miniChat-CrAin_em.js → miniChat-DCxCx1fF.js} +2 -2
  38. package/dist/assets/{mobile-EK9oTupb.js → mobile-D6Ac2Mu3.js} +2 -2
  39. package/dist/assets/{nativeFileSave-Bhafll_7.js → nativeFileSave-P_Eg5Dgb.js} +1 -1
  40. package/dist/assets/{pi-session-focus-preference-BoN1cyoG.js → pi-session-focus-preference-DjDyjZ1C.js} +1 -1
  41. package/dist/assets/{renderDiffWithHighlighter-DixZh5Zd.js → renderDiffWithHighlighter-CK_inhQE.js} +1 -1
  42. package/dist/assets/renderElectronMiniChatApp-wBNgFl0U.js +2 -0
  43. package/dist/assets/{renderFileWithHighlighter-s6fQq9eg.js → renderFileWithHighlighter-B_PFeRW5.js} +1 -1
  44. package/dist/assets/renderMobileApp-B3mhxGnb.js +11 -0
  45. package/dist/assets/runtimeEndpointReset-D8lAOCUB.js +62 -0
  46. package/dist/assets/{runtimeSurface-CJN1oo_1.js → runtimeSurface-C3YPOBlg.js} +1 -1
  47. package/dist/assets/useAppFontEffects-CoFst31H.js +215 -0
  48. package/dist/assets/{useGitHubRemoteSearch-CZ92xKSw.js → useGitHubRemoteSearch-C0-6hhMJ.js} +1 -1
  49. package/dist/assets/useSwitcherItems-DHCCg4GF.js +1 -0
  50. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js → vendor-aparajita-capacitor-secure-storage-B9_YeZyx.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-C7vVMZTg.js → vendor-base-ui-CKSCJw-4.js} +1 -1
  52. package/dist/assets/{vendor-boot-CoTxysn6.js → vendor-boot-Ciu-Edvy.js} +18 -18
  53. package/dist/assets/{vendor-capacitor-app-NX6DULfp.js → vendor-capacitor-app-Bpy_aPMq.js} +1 -1
  54. package/dist/assets/{vendor-capacitor-keyboard-DJD81I9f.js → vendor-capacitor-keyboard-DO8AIjrZ.js} +1 -1
  55. package/dist/assets/{vendor-capacitor-status-bar-DV24OoQV.js → vendor-capacitor-status-bar-SQkytwUW.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-autocomplete-qsuH4Dh-.js → vendor-codemirror-autocomplete-CInQsE8a.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-ZHWyBf7j.js → vendor-codemirror-lang-angular-QbsN3LGE.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-cpp-pCTOmv-k.js → vendor-codemirror-lang-cpp-BT5U7lxV.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-css-2bFuyM70.js → vendor-codemirror-lang-css-dF-Dxbty.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-go-DrG_c7D7.js → vendor-codemirror-lang-go-e4dp1bar.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-html-BV8lrR8v.js → vendor-codemirror-lang-html-DKcbBVQ4.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-java-DrsvH6T2.js → vendor-codemirror-lang-java-CB2-FWv6.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-javascript-Dkzl3s07.js → vendor-codemirror-lang-javascript-B1zJk7xE.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-jinja-8Nn3bnoP.js → vendor-codemirror-lang-jinja-BsERjdSd.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-json-CsdmtHhi.js → vendor-codemirror-lang-json-C0pZ0NhY.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-less-DJuZ4cZe.js → vendor-codemirror-lang-less-_N9HmR4h.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-liquid-D2RO-Pzr.js → vendor-codemirror-lang-liquid-D02xJRCD.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-markdown-C0Zu3b3n.js → vendor-codemirror-lang-markdown-_6ojeUuZ.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-php-CuDtt2Zj.js → vendor-codemirror-lang-php-DguCnbJA.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-python-Cv2exx_M.js → vendor-codemirror-lang-python-Byr5gw5f.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-rust-C4TxJ6Rg.js → vendor-codemirror-lang-rust-DN6Wh0eK.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sass-BmtPz8kf.js → vendor-codemirror-lang-sass-DOlEW7q1.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-sql-BF1ZaXqJ.js → vendor-codemirror-lang-sql-BJzE9Dby.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-vue-DZgXrP2k.js → vendor-codemirror-lang-vue-DR8E-2nr.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-wast-DsnaGtL_.js → vendor-codemirror-lang-wast-n6lcDH5S.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-xml-D8DzzFat.js → vendor-codemirror-lang-xml-Cf2lmlmY.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-yaml-D5hBv7m6.js → vendor-codemirror-lang-yaml-DSR_E0yh.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-language-data-vn2RyN9T.js → vendor-codemirror-language-data-CSid5JuX.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-search-BVCYIV0D.js → vendor-codemirror-search-8lY3lt6q.js} +1 -1
  80. package/dist/assets/{vendor-lezer-cpp-vqXSn3lv.js → vendor-lezer-cpp-DZYTDKiD.js} +1 -1
  81. package/dist/assets/{vendor-lezer-css-JnEzSyZR.js → vendor-lezer-css-6qV4fYNQ.js} +1 -1
  82. package/dist/assets/{vendor-lezer-go-dD2gQMIL.js → vendor-lezer-go-BDi_Iblq.js} +1 -1
  83. package/dist/assets/{vendor-lezer-html-Cr3U-1pu.js → vendor-lezer-html-BjqcY-oJ.js} +1 -1
  84. package/dist/assets/{vendor-lezer-java-CRM0IMCo.js → vendor-lezer-java-J2BXqz1h.js} +1 -1
  85. package/dist/assets/{vendor-lezer-javascript-B3s21DIS.js → vendor-lezer-javascript-CiQ9F8yX.js} +1 -1
  86. package/dist/assets/{vendor-lezer-json-DPFM6EBV.js → vendor-lezer-json-BxN83KKR.js} +1 -1
  87. package/dist/assets/{vendor-lezer-lr-Bllrq8hY.js → vendor-lezer-lr-BVsDua_K.js} +1 -1
  88. package/dist/assets/{vendor-lezer-markdown-6-3PLvXG.js → vendor-lezer-markdown-BkMtRQ3X.js} +1 -1
  89. package/dist/assets/{vendor-lezer-php-DOyzfHRl.js → vendor-lezer-php-B3XqnXdP.js} +1 -1
  90. package/dist/assets/{vendor-lezer-python-CdHdN5qt.js → vendor-lezer-python-D342CidI.js} +1 -1
  91. package/dist/assets/{vendor-lezer-rust-CqnW8EMH.js → vendor-lezer-rust-Dbfg_4LA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-sass-BbcF4y6A.js → vendor-lezer-sass-ClxPaFt1.js} +1 -1
  93. package/dist/assets/{vendor-lezer-xml-C31AyWoo.js → vendor-lezer-xml-I_S6FQ1u.js} +1 -1
  94. package/dist/assets/{vendor-lezer-yaml-Cv908yC2.js → vendor-lezer-yaml-COA6HWLP.js} +1 -1
  95. package/dist/assets/{vendor-replit-codemirror-vim-Cwhyn_5f.js → vendor-replit-codemirror-vim-7IE2zVmx.js} +1 -1
  96. package/dist/assets/{web-components-Bz5oGa3p.js → web-components-CzkvK_V5.js} +1 -1
  97. package/dist/index.html +4 -4
  98. package/dist/mini-chat.html +3 -3
  99. package/dist/mobile.html +3 -3
  100. package/package.json +1 -1
  101. package/server/lib/git/DOCUMENTATION.md +1 -0
  102. package/server/lib/git/routes.js +14 -0
  103. package/server/lib/git/routes.test.js +37 -0
  104. package/server/lib/git/service.js +27 -0
  105. package/server/lib/git/service.test.js +32 -0
  106. package/server/lib/pi/routes.js +63 -1
  107. package/server/lib/pi/routes.test.js +77 -0
  108. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  109. package/server/lib/pi/session-shelf-store.js +181 -0
  110. package/server/lib/pi/session-shelf-store.test.js +73 -0
  111. package/server/lib/pi/ui-settings-store.js +1 -0
  112. package/dist/assets/DiffView-CFIjN2zy.js +0 -18
  113. package/dist/assets/FilesView-D0b2mEKA.js +0 -6
  114. package/dist/assets/GitHubListPrimitives-Dw5LAmzm.js +0 -1
  115. package/dist/assets/GitView-Dhr7qVeI.js +0 -9
  116. package/dist/assets/MarkdownRendererImpl-DadkFPCz.js +0 -12
  117. package/dist/assets/SessionSwitcherContent-CJ6C2ZKG.js +0 -1
  118. package/dist/assets/SessionUnreadDot-I1_tmqY9.js +0 -1
  119. package/dist/assets/SettingsView-B-b76XDV.js +0 -6
  120. package/dist/assets/gitStatusPredicates-BQOqDJU1.js +0 -1
  121. package/dist/assets/index-C2ISrmRR.js +0 -11
  122. package/dist/assets/index-DgwThEwf.css +0 -1
  123. package/dist/assets/main-DoVzQV56.js +0 -137
  124. package/dist/assets/renderElectronMiniChatApp-0MqKeGfI.js +0 -2
  125. package/dist/assets/renderMobileApp-BLoXL_J8.js +0 -11
  126. package/dist/assets/runtimeEndpointReset-Bv2Y1fMm.js +0 -62
  127. package/dist/assets/useAppFontEffects-D2xXdmYC.js +0 -215
  128. package/dist/assets/useFilesViewSearch-BKotcAUN.js +0 -7
  129. package/dist/assets/useSwitcherItems-BfA4omGb.js +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "1.0.6-rc.3",
3
+ "version": "1.0.6-rc.4",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -31,6 +31,7 @@ The following functions are exported and used by the web server:
31
31
  ### Repository Operations
32
32
  - `isGitRepository(directory)`: Check if a directory is a Git repository.
33
33
  - `getCurrentIdentity(directory)`: Read-only read of the local Git `user.name`/`user.email` (falling back to global when unset). Never writes config.
34
+ - `initRepository(directory)`: Run `git init` in an existing folder. Returns `{ created: true }`, or `{ created: false }` without running git when the folder already holds its own `.git` (a parent repository does not count). Throws for a missing path or a file. Exposed as `POST /api/git/init?directory=…`, which answers failures with 400; the Add folder dialog's new-project step calls it after creating the folder.
34
35
  - `getRemoteUrl(directory, remoteName)`: Get URL for a specific remote.
35
36
 
36
37
  ### Status and Diff Operations
@@ -57,6 +57,20 @@ export function registerGitRoutes(app) {
57
57
  }
58
58
  });
59
59
 
60
+ app.post('/api/git/init', async (req, res) => {
61
+ const { initRepository } = await getGitLibraries();
62
+ try {
63
+ const directory = resolveDirectoryQuery(req.query.directory);
64
+ if (!directory) {
65
+ return res.status(400).json({ error: 'directory parameter is required' });
66
+ }
67
+ res.json(await initRepository(directory));
68
+ } catch (error) {
69
+ console.error('Failed to initialize git repository:', error);
70
+ res.status(400).json({ error: error.message || 'Failed to initialize Git repository' });
71
+ }
72
+ });
73
+
60
74
  app.get('/api/git/remote-url', async (req, res) => {
61
75
  const { getRemoteUrl } = await getGitLibraries();
62
76
  try {
@@ -13,6 +13,7 @@ const gitLibraries = {
13
13
  getWorktreeBootstrapStatus: vi.fn(),
14
14
  getDiff: vi.fn(),
15
15
  resolveDiffSource: vi.fn(),
16
+ initRepository: vi.fn(),
16
17
  };
17
18
 
18
19
  vi.mock('./index.js', () => ({
@@ -28,6 +29,7 @@ vi.mock('./index.js', () => ({
28
29
  getWorktreeBootstrapStatus: gitLibraries.getWorktreeBootstrapStatus,
29
30
  getDiff: gitLibraries.getDiff,
30
31
  resolveDiffSource: gitLibraries.resolveDiffSource,
32
+ initRepository: gitLibraries.initRepository,
31
33
  }));
32
34
 
33
35
  const { registerGitRoutes } = await import('./routes.js');
@@ -464,3 +466,38 @@ describe('git routes diff', () => {
464
466
  expect(gitLibraries.getDiff).not.toHaveBeenCalled();
465
467
  });
466
468
  });
469
+
470
+ describe('git routes init', () => {
471
+ beforeEach(() => {
472
+ gitLibraries.initRepository.mockReset();
473
+ });
474
+
475
+ it('initializes the folder named by the directory query', async () => {
476
+ const { app, getRoute } = createRouteRegistry();
477
+ registerGitRoutes(app);
478
+ gitLibraries.initRepository.mockResolvedValue({ created: true });
479
+ const response = createMockResponse();
480
+
481
+ await getRoute('POST', '/api/git/init')({ query: { directory: '/projects/demo' } }, response);
482
+
483
+ expect(gitLibraries.initRepository).toHaveBeenCalledWith('/projects/demo');
484
+ expect(response.statusCode).toBe(200);
485
+ expect(response.body).toEqual({ created: true });
486
+ });
487
+
488
+ it('requires a directory and reports failures instead of success', async () => {
489
+ const { app, getRoute } = createRouteRegistry();
490
+ registerGitRoutes(app);
491
+
492
+ const missing = createMockResponse();
493
+ await getRoute('POST', '/api/git/init')({ query: {} }, missing);
494
+ expect(missing.statusCode).toBe(400);
495
+ expect(gitLibraries.initRepository).not.toHaveBeenCalled();
496
+
497
+ gitLibraries.initRepository.mockRejectedValueOnce(new Error('Folder does not exist'));
498
+ const failed = createMockResponse();
499
+ await getRoute('POST', '/api/git/init')({ query: { directory: '/nope' } }, failed);
500
+ expect(failed.statusCode).toBe(400);
501
+ expect(failed.body).toEqual({ error: 'Folder does not exist' });
502
+ });
503
+ });
@@ -1932,6 +1932,33 @@ export async function isGitRepository(directory) {
1932
1932
  return result.success;
1933
1933
  }
1934
1934
 
1935
+ /**
1936
+ * Makes an existing folder a Git repository. A folder that already holds its
1937
+ * own `.git` is left alone (`created: false`), so a retry after a partial
1938
+ * failure is safe. Only the folder's own `.git` counts: a new project inside
1939
+ * another repository's tree still gets a repository of its own.
1940
+ */
1941
+ export async function initRepository(directory) {
1942
+ const directoryPath = normalizeDirectoryPath(directory);
1943
+ if (!directoryPath) {
1944
+ throw new Error('Folder path is required');
1945
+ }
1946
+ let stats;
1947
+ try {
1948
+ stats = await fs.promises.stat(directoryPath);
1949
+ } catch {
1950
+ throw new Error('Folder does not exist');
1951
+ }
1952
+ if (!stats.isDirectory()) {
1953
+ throw new Error('Path is not a folder');
1954
+ }
1955
+ if (fs.existsSync(path.join(directoryPath, '.git'))) {
1956
+ return { created: false };
1957
+ }
1958
+ await runGitCommandOrThrow(directoryPath, ['init'], 'Failed to initialize Git repository');
1959
+ return { created: true };
1960
+ }
1961
+
1935
1962
  export async function getRemoteUrl(directory, remoteName = 'origin') {
1936
1963
  const git = await createGit(directory);
1937
1964
 
@@ -31,6 +31,7 @@ import {
31
31
  getDiff,
32
32
  getFileDiff,
33
33
  resolveDiffSource,
34
+ initRepository,
34
35
  } from './service.js';
35
36
 
36
37
  // ---------------------------------------------------------------------------
@@ -1500,3 +1501,34 @@ describe.runIf(canRunGit())('getRangeDiff', () => {
1500
1501
  expect(diff).toContain('feature.txt');
1501
1502
  });
1502
1503
  });
1504
+
1505
+ describe.skipIf(!canRunGit())('initRepository', () => {
1506
+ it('makes a plain folder a repository and leaves an existing one alone', async () => {
1507
+ const folder = createTempDir();
1508
+
1509
+ expect(await initRepository(folder)).toEqual({ created: true });
1510
+ expect(fs.existsSync(path.join(folder, '.git'))).toBe(true);
1511
+ expect(await isGitRepository(folder)).toBe(true);
1512
+
1513
+ expect(await initRepository(folder)).toEqual({ created: false });
1514
+ });
1515
+
1516
+ it('gives a folder inside another repository its own repository', async () => {
1517
+ const parent = createTempDir();
1518
+ runGit(parent, ['init']);
1519
+ const child = path.join(parent, 'new-project');
1520
+ fs.mkdirSync(child);
1521
+
1522
+ expect(await initRepository(child)).toEqual({ created: true });
1523
+ expect(fs.existsSync(path.join(child, '.git'))).toBe(true);
1524
+ });
1525
+
1526
+ it('rejects a missing path and a file', async () => {
1527
+ const folder = createTempDir();
1528
+ const file = path.join(folder, 'notes.txt');
1529
+ fs.writeFileSync(file, 'x');
1530
+
1531
+ await expect(initRepository(path.join(folder, 'missing'))).rejects.toThrow('Folder does not exist');
1532
+ await expect(initRepository(file)).rejects.toThrow('Path is not a folder');
1533
+ });
1534
+ });
@@ -17,6 +17,7 @@ import { readUpdateJob } from '../update-job-store.js';
17
17
  import { createPiSettingsStore } from './settings-store.js';
18
18
  import { isPiThinkingLevel } from './thinking-levels.js';
19
19
  import { createPiSessionFoldersStore } from './session-folders-store.js';
20
+ import { createPiSessionShelfStore } from './session-shelf-store.js';
20
21
  import {
21
22
  MAX_EXTENSION_APP_HTML_CHARS,
22
23
  isValidCustomInputItems,
@@ -60,6 +61,7 @@ const UNAVAILABLE_CODES = new Set([
60
61
  'MALFORMED_SESSION_JSONL',
61
62
  'SESSION_JSONL_UNREADABLE',
62
63
  'ARCHIVE_METADATA_INVALID',
64
+ 'SESSION_SHELF_INVALID',
63
65
  ]);
64
66
 
65
67
  const BAD_GATEWAY_CODES = new Set([
@@ -1119,6 +1121,7 @@ export const registerPiRuntimeRoutes = (app, {
1119
1121
  attachmentStore = createPiAttachmentStore(),
1120
1122
  settingsStore = createPiSettingsStore(),
1121
1123
  sessionFoldersStore = createPiSessionFoldersStore(),
1124
+ sessionShelfStore = createPiSessionShelfStore(),
1122
1125
  uiSettingsStore = createPiUiSettingsStore(),
1123
1126
  snippetsStore = createPiSnippetsStore(),
1124
1127
  listCustomThemes = listPiCustomThemes,
@@ -1132,6 +1135,15 @@ export const registerPiRuntimeRoutes = (app, {
1132
1135
  eventStreamMaxBufferedBytes = DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
1133
1136
  }) => {
1134
1137
  const eventStreamRegistry = createPiEventStreamRegistry();
1138
+ // A message or command the user sends ends a snooze and drops a settled
1139
+ // override. The send already succeeded, so a shelf write failure only logs.
1140
+ const clearShelfForActivity = async (sessionId) => {
1141
+ try {
1142
+ await sessionShelfStore.clearForActivity(sessionId);
1143
+ } catch (error) {
1144
+ console.warn('[pi] could not clear the session shelf after a send', error?.code ?? error);
1145
+ }
1146
+ };
1135
1147
  app.get('/api/pi/ui-settings', async (_req, res) => {
1136
1148
  try {
1137
1149
  res.json(await uiSettingsStore.read());
@@ -2006,7 +2018,55 @@ export const registerPiRuntimeRoutes = (app, {
2006
2018
 
2007
2019
  app.delete('/api/pi/sessions/:sessionId', async (req, res) => {
2008
2020
  const result = await requestSessionOperation(req, res, getPiSessionDaemonRuntime, 'sessions.delete');
2009
- if (result !== undefined) res.status(204).end();
2021
+ if (result === undefined) return;
2022
+ try {
2023
+ await sessionShelfStore.remove(req.params.sessionId);
2024
+ } catch (error) {
2025
+ console.warn('[pi] could not remove a deleted session from the shelf', error?.code ?? error);
2026
+ }
2027
+ res.status(204).end();
2028
+ });
2029
+
2030
+ app.get('/api/pi/session-shelf', async (_req, res) => {
2031
+ try {
2032
+ res.json({ sessions: await sessionShelfStore.read() });
2033
+ } catch (error) {
2034
+ writeDaemonError(res, error);
2035
+ }
2036
+ });
2037
+
2038
+ app.post('/api/pi/sessions/:sessionId/shelf', async (req, res) => {
2039
+ const { sessionId } = req.params;
2040
+ const body = req.body && typeof req.body === 'object' ? req.body : {};
2041
+ const directory = typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined;
2042
+ const patch = {
2043
+ ...(Object.hasOwn(body, 'settled') ? { settled: body.settled } : {}),
2044
+ ...(Object.hasOwn(body, 'snoozedUntil') ? { snoozedUntil: body.snoozedUntil } : {}),
2045
+ };
2046
+ const settledValid = !Object.hasOwn(patch, 'settled') || patch.settled === null || patch.settled === 'settled' || patch.settled === 'active';
2047
+ const snoozeValid = !Object.hasOwn(patch, 'snoozedUntil') || patch.snoozedUntil === null
2048
+ || (Number.isSafeInteger(patch.snoozedUntil) && patch.snoozedUntil > 0);
2049
+ if (!sessionId || Object.keys(patch).length === 0 || !settledValid || !snoozeValid) {
2050
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2051
+ return;
2052
+ }
2053
+ try {
2054
+ // Same membership check as archive: shelf state is PiChamber metadata
2055
+ // for a session that exists, not a Pi session mutation.
2056
+ const result = await getDaemonRuntime(getPiSessionDaemonRuntime).request(
2057
+ 'sessions.list',
2058
+ directory ? { directory } : undefined,
2059
+ );
2060
+ const items = projectSessionList(result?.sessions);
2061
+ if (!items.some((item) => item.session.id === sessionId)) {
2062
+ const error = new Error('The Pi session does not exist.');
2063
+ error.code = 'INVALID_SESSION';
2064
+ throw error;
2065
+ }
2066
+ res.json({ entry: await sessionShelfStore.update(sessionId, patch) });
2067
+ } catch (error) {
2068
+ writeDaemonError(res, error);
2069
+ }
2010
2070
  });
2011
2071
 
2012
2072
  app.post('/api/pi/sessions/:sessionId/archive', async (req, res) => {
@@ -2220,6 +2280,7 @@ export const registerPiRuntimeRoutes = (app, {
2220
2280
  return;
2221
2281
  }
2222
2282
  await attachmentStore.consume?.(attachmentIds);
2283
+ await clearShelfForActivity(req.params.sessionId);
2223
2284
  res.status(202).json({
2224
2285
  accepted: true,
2225
2286
  messageId: result.messageId,
@@ -2294,6 +2355,7 @@ export const registerPiRuntimeRoutes = (app, {
2294
2355
  writeDaemonError(res, protocolMismatch());
2295
2356
  return;
2296
2357
  }
2358
+ await clearShelfForActivity(req.params.sessionId);
2297
2359
  res.status(202).json({ accepted: true, id: result.id });
2298
2360
  });
2299
2361
 
@@ -1546,6 +1546,83 @@ describe('Pi runtime route', () => {
1546
1546
  }
1547
1547
  });
1548
1548
 
1549
+ it('serves the session shelf, checks membership on writes, and clears it when the user sends', async () => {
1550
+ const calls = [];
1551
+ const session = { id: 'pi-session-7', directory: '/workspace', createdAt: 1, updatedAt: 2 };
1552
+ let shelf = { 'pi-session-7': { settled: 'settled', settledAt: 3 } };
1553
+ const sessionShelfStore = {
1554
+ read: async () => shelf,
1555
+ update: async (sessionId, patch) => {
1556
+ calls.push({ command: 'shelf.update', payload: [sessionId, patch] });
1557
+ return { settled: 'active' };
1558
+ },
1559
+ clearForActivity: async (sessionId) => {
1560
+ calls.push({ command: 'shelf.clear', payload: sessionId });
1561
+ shelf = {};
1562
+ return null;
1563
+ },
1564
+ remove: async (sessionId) => calls.push({ command: 'shelf.remove', payload: sessionId }),
1565
+ };
1566
+ const runtime = {
1567
+ health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
1568
+ request: async (command, payload) => {
1569
+ calls.push({ command, payload });
1570
+ if (command === 'sessions.list') return { sessions: [{ session, updatedAt: 2 }] };
1571
+ if (command === 'sessions.prompt') return { accepted: true, messageId: 'message-1' };
1572
+ if (command === 'sessions.bash') return { accepted: true, id: 'bash-1' };
1573
+ return {};
1574
+ },
1575
+ };
1576
+ const app = express();
1577
+ app.use(express.json());
1578
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) }, sessionShelfStore });
1579
+ server = await listen(app);
1580
+ const origin = `http://127.0.0.1:${server.address().port}`;
1581
+ const post = (path, body) => fetch(`${origin}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
1582
+
1583
+ await expect((await fetch(`${origin}/api/pi/session-shelf`)).json()).resolves.toEqual({ sessions: { 'pi-session-7': { settled: 'settled', settledAt: 3 } } });
1584
+
1585
+ const updated = await post('/api/pi/sessions/pi-session-7/shelf', { settled: 'active', directory: '/workspace' });
1586
+ expect(updated.status).toBe(200);
1587
+ await expect(updated.json()).resolves.toEqual({ entry: { settled: 'active' } });
1588
+ expect(calls).toContainEqual({ command: 'sessions.list', payload: { directory: '/workspace' } });
1589
+ expect(calls).toContainEqual({ command: 'shelf.update', payload: ['pi-session-7', { settled: 'active' }] });
1590
+
1591
+ expect((await post('/api/pi/sessions/missing/shelf', { settled: 'settled' })).status).toBe(404);
1592
+ expect((await post('/api/pi/sessions/pi-session-7/shelf', {})).status).toBe(400);
1593
+ expect((await post('/api/pi/sessions/pi-session-7/shelf', { settled: 'done' })).status).toBe(400);
1594
+ expect((await post('/api/pi/sessions/pi-session-7/shelf', { snoozedUntil: 'tomorrow' })).status).toBe(400);
1595
+ expect(calls.filter((call) => call.command === 'shelf.update')).toHaveLength(1);
1596
+
1597
+ expect((await post('/api/pi/sessions/pi-session-7/prompt', { text: 'hello', streamEpoch: 'epoch-routes' })).status).toBe(202);
1598
+ expect((await post('/api/pi/sessions/pi-session-7/bash', { command: 'ls' })).status).toBe(202);
1599
+ expect(calls.filter((call) => call.command === 'shelf.clear')).toEqual([
1600
+ { command: 'shelf.clear', payload: 'pi-session-7' },
1601
+ { command: 'shelf.clear', payload: 'pi-session-7' },
1602
+ ]);
1603
+ expect((await fetch(`${origin}/api/pi/sessions/pi-session-7`, { method: 'DELETE' })).status).toBe(204);
1604
+ expect(calls).toContainEqual({ command: 'shelf.remove', payload: 'pi-session-7' });
1605
+ });
1606
+
1607
+ it('keeps a send accepted when clearing the shelf fails', async () => {
1608
+ const runtime = {
1609
+ health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
1610
+ request: async (command) => (command === 'sessions.prompt' ? { accepted: true, messageId: 'message-1' } : {}),
1611
+ };
1612
+ const sessionShelfStore = { clearForActivity: async () => { throw Object.assign(new Error('bad'), { code: 'SESSION_SHELF_INVALID' }); } };
1613
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
1614
+ const app = express();
1615
+ app.use(express.json());
1616
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, sessionShelfStore });
1617
+ server = await listen(app);
1618
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-7/prompt`, {
1619
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'hello', streamEpoch: 'epoch-routes' }),
1620
+ });
1621
+ expect(response.status).toBe(202);
1622
+ expect(warn).toHaveBeenCalled();
1623
+ warn.mockRestore();
1624
+ });
1625
+
1549
1626
  it('creates a session and projects the created detail like a session read', async () => {
1550
1627
  const calls = [];
1551
1628
  let created;
@@ -34,7 +34,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
34
34
  - `../server/server-profile.js` derives one stable daemon profile per server: installed web is `web-p<port>`, development web is `web-dev-p<port>`, installed desktop is `desktop`, and development desktop is `desktop-dev`. `PICHAMBER_SERVER_PROFILE` overrides the derivation with a hashed `custom-<hash>` key so raw input never becomes a path, while preserving whether the launcher is a development build for stale-code replacement. The profile key is stable across restarts; the server instance id is a fresh UUID per launch. Development launchers (`scripts/dev-web-hmr.mjs`, `scripts/dev-web-full.mjs`, `cross-env` in the `dev:server` scripts, `PICHAMBER_ELECTRON_DEV`) explicitly mark themselves so stopping development can never terminate the installed daemon.
35
35
  - `../server/cross-process-lock.js` serializes critical sections across servers sharing one data directory (exclusive create, owner nonce, dead-pid steal, bounded wait). It backs the daemon operation lock pattern and every shared read-modify-write store below.
36
36
  - `session-lease.js` owns exclusive cross-daemon residency of one Pi session, keyed by canonical agent directory, cwd, and session id under `<agentDir>/.pichamber/locks/sessions/`. The lease is acquired before a resident `AgentSessionRuntime` is created and released after idle disposal, deletion, replacement, or daemon shutdown. Opening or deleting a session leased by another live daemon returns `SESSION_IN_USE` (HTTP 409) while the session stays visible in listings; different sessions remain fully concurrent. Lease files from different `PICHAMBER_DATA_DIR` values still coordinate because they live under the shared agent directory.
37
- - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `POST /api/pi/sessions` projects the created detail through the same session-detail projector as `GET /api/pi/sessions/:id`, so extension items appended from `session_start`, the `streamEpoch` stamp, and extension UI snapshot state are returned rather than rejected; only a malformed detail is `DAEMON_PROTOCOL_MISMATCH`. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` owns portable PiChamber preferences at data-root `settings.json` and host, device, and secret-bearing values at `runtime-state.json`. `/api/pi/ui-settings` merges both views for existing clients and splits writes through explicit field allowlists. It migrates an unscoped flat file once; after the portable scope marker exists, local fields found in `settings.json` are ignored rather than applied to the host. The route is not available through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
37
+ - `../routes.js` registers authenticated public adapters before the generic proxy. It exposes only whitelisted runtime, project, session, provider-auth/configuration, settings, resource, small-model utility, and SSE event shapes; no browser response contains daemon paths, credentials, PIDs, headers, or socket framing. Session actions are path-selected, so an identity supplied in a request body cannot redirect a mutation. `POST /api/pi/sessions` projects the created detail through the same session-detail projector as `GET /api/pi/sessions/:id`, so extension items appended from `session_start`, the `streamEpoch` stamp, and extension UI snapshot state are returned rather than rejected; only a malformed detail is `DAEMON_PROTOCOL_MISMATCH`. `archive-store.js` persists PiChamber-only opaque session archive metadata atomically beneath the PiChamber data root and never edits Pi JSONL. `settings-store.js` keeps PiChamber new-session defaults separate from Pi settings.json. `/api/pi/small-model/generate` reads that sidecar and runs a bounded in-memory no-tools Pi session, so utility generation creates no visible or persisted session and exposes no model or credential details. `GET /api/pi/settings` copies leftover UI/desktop `defaultModel` / small / walkthrough strings into that sidecar when those sidecar fields are unset, then Sessions settings is the only editor. Sidecar `defaultThinkingByModel` is the per-model thinking map (`provider/model` keys). A stored global `defaultThinking` with a default model is copied onto that map key and dropped; global thinking without a default model remains a clamp-only fallback. `ui-settings-store.js` owns portable PiChamber preferences at data-root `settings.json` and host, device, and secret-bearing values at `runtime-state.json`. `/api/pi/ui-settings` merges both views for existing clients and splits writes through explicit field allowlists. It migrates an unscoped flat file once; after the portable scope marker exists, local fields found in `settings.json` are ignored rather than applied to the host. The route is not available through removed `/api/config/*` aliases. `session-folders-store.js` validates and atomically persists the restored sidebar's folder snapshot at `/api/pi/session-folders`; a missing snapshot is distinct from an empty one. `session-shelf-store.js` persists PiChamber-only sidebar shelf state (a settled or un-settled override with its time, and a snooze wake time) per session id at data-root `pi/session-shelf.json`, read through `GET /api/pi/session-shelf` and changed through `POST /api/pi/sessions/:id/shelf`, which checks that the session exists like archive does. A message or command the user sends clears that session's entry, and deleting a session removes it; a failed shelf write after a successful send only logs. A malformed file is `SESSION_SHELF_INVALID`, never an empty shelf. `custom-themes.js` serves validated custom-theme candidates from `/api/pi/themes` with per-file partial-failure isolation. `model-config-store.js` atomically updates Pi's credential-blind `models.json`; literal keys continue through Pi auth and headers are write-only. `providers.config.get` returns `config: null` for a provider that is not in `models.json` (built-in catalog entries) and fails only when that file is present but malformed.
38
38
  - `../event-stream.js` owns the `/api/pi/events` SSE connection lifecycle so `../routes.js` stays a thin adapter. Per connection it installs cleanup before `subscribe` is awaited (a client that leaves during the opening window cannot leak a daemon subscription; a late subscription is closed exactly once), funnels client disconnect, subscription error, and server shutdown through one idempotent cleanup, hands an `AbortSignal` through the supervisor to the private IPC subscriber, never writes a named heartbeat or a late frame to a dead response, and byte-bounds the response socket buffer (`res.writableLength`, default 8 MiB, aligned with the daemon replay budget) with the bound enforced BEFORE each write so no single frame overshoots it. A client that stops reading is disconnected recoverably — the stream ends and the client reconnects from its last accepted sequence for replay or an authoritative snapshot, so no event is silently removed from an otherwise contiguous stream, but frames still buffered when the disconnect fires are not promised as delivered; the reconnect replay is the delivery guarantee — while a healthy client's connection stays independent of the slow one. Every teardown is bounded: a `write()` that returns false starts a drain deadline (default 5s) that ends even a quiet never-draining client, and after `res.end()` a terminate deadline (default 5s) destroys the response, because `end()` alone only queues the FIN behind unflushed data and would otherwise leave a stalled socket open forever and hang server shutdown/close. The response `'error'` guard stays attached for the response's lifetime (idempotent; cleanup can complete while data is still in flight and a late unhandled `'error'` would crash the process). The registry tracks live connections so `registerPiRuntimeRoutes` can expose `closeEventStreams()` for server shutdown, ending active and still-opening streams (and their daemon subscriptions) before the HTTP server closes. The IPC subscriber removes its abort listener and destroys the opening or active daemon socket on cancellation.
39
39
  - `*.test.js` uses temporary cwd, agent, data, and runtime directories; it never loads a developer's Pi home, credentials, or sessions. On Windows the private endpoint is a named pipe, not a `.sock` file, and POSIX mode-bit assertions are skipped.
40
40
 
@@ -0,0 +1,181 @@
1
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { dirname, join } from 'node:path';
3
+
4
+ import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
5
+ import { withCrossProcessLock } from '../server/cross-process-lock.js';
6
+
7
+ const MAX_FILE_BYTES = 4 * 1024 * 1024;
8
+ const MAX_SESSION_ID_LENGTH = 512;
9
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'prototype', 'constructor']);
10
+ const SETTLED_STATES = new Set(['settled', 'active']);
11
+
12
+ const invalidShelf = () => {
13
+ const error = new Error('Pi session shelf metadata is invalid.');
14
+ error.code = 'SESSION_SHELF_INVALID';
15
+ return error;
16
+ };
17
+
18
+ const invalidArgument = () => {
19
+ const error = new Error('The session shelf request is invalid.');
20
+ error.code = 'INVALID_ARGUMENT';
21
+ return error;
22
+ };
23
+
24
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
25
+ const isTimestamp = (value) => Number.isSafeInteger(value) && value > 0;
26
+ const isSessionId = (value) => typeof value === 'string' && value.length > 0
27
+ && value.length <= MAX_SESSION_ID_LENGTH && !FORBIDDEN_KEYS.has(value);
28
+
29
+ // One session's entry, or null when it holds nothing. Fields only travel in
30
+ // pairs: a settled override without its time, or a snooze without its wake,
31
+ // is malformed.
32
+ const validateEntry = (value) => {
33
+ if (!isRecord(value)) throw invalidShelf();
34
+ const entry = {};
35
+ if (value.settled !== undefined) {
36
+ if (!SETTLED_STATES.has(value.settled)) throw invalidShelf();
37
+ entry.settled = value.settled;
38
+ if (value.settled === 'settled') {
39
+ if (!isTimestamp(value.settledAt)) throw invalidShelf();
40
+ entry.settledAt = value.settledAt;
41
+ }
42
+ }
43
+ if (value.snoozedUntil !== undefined) {
44
+ if (!isTimestamp(value.snoozedUntil) || !isTimestamp(value.snoozedAt)) throw invalidShelf();
45
+ entry.snoozedUntil = value.snoozedUntil;
46
+ entry.snoozedAt = value.snoozedAt;
47
+ }
48
+ return Object.keys(entry).length > 0 ? entry : null;
49
+ };
50
+
51
+ const validateShelf = (value) => {
52
+ if (!isRecord(value)) throw invalidShelf();
53
+ const shelf = {};
54
+ for (const [sessionId, raw] of Object.entries(value)) {
55
+ if (!isSessionId(sessionId)) throw invalidShelf();
56
+ const entry = validateEntry(raw);
57
+ if (entry) shelf[sessionId] = entry;
58
+ }
59
+ return shelf;
60
+ };
61
+
62
+ /**
63
+ * PiChamber-owned sidebar shelf metadata: whether a session was settled or
64
+ * kept active by hand, and when a snoozed session wakes. Like the archive
65
+ * sidecar, it is keyed only by opaque Pi session IDs, leaves Pi JSONL
66
+ * untouched, and every write is atomic under a cross-process lock.
67
+ *
68
+ * - `settled: 'settled'` moves a session to Settled; `settled: 'active'`
69
+ * keeps it out of Settled even when it would auto-settle. `null` clears
70
+ * the override so the client's auto-settle rule applies again.
71
+ * - `snoozedUntil` hides a session until that time. Snoozing clears a
72
+ * settled override, so the session wakes into the active list.
73
+ * - Settling clears a snooze.
74
+ * - `clearForActivity` drops both when the user sends to the session.
75
+ */
76
+ export const createPiSessionShelfStore = ({
77
+ file = join(resolvePiChamberDataDir(), 'pi', 'session-shelf.json'),
78
+ now = () => Date.now(),
79
+ } = {}) => {
80
+ let writeChain = Promise.resolve();
81
+
82
+ const read = async () => {
83
+ let raw;
84
+ try {
85
+ raw = await readFile(file, 'utf8');
86
+ } catch (error) {
87
+ if (error?.code === 'ENOENT') return {};
88
+ throw invalidShelf();
89
+ }
90
+ if (Buffer.byteLength(raw) > MAX_FILE_BYTES) throw invalidShelf();
91
+ try {
92
+ return validateShelf(JSON.parse(raw));
93
+ } catch {
94
+ throw invalidShelf();
95
+ }
96
+ };
97
+
98
+ // Serializes writes in this process and across processes sharing the
99
+ // data directory. `change` receives the current entry (or null) and
100
+ // returns the next entry (or null to remove it).
101
+ const mutate = (sessionId, change) => {
102
+ const operation = writeChain.then(() => withCrossProcessLock(`${file}.lock`, async () => {
103
+ const current = await read();
104
+ const previous = current[sessionId] ?? null;
105
+ const next = change(previous);
106
+ if (next) current[sessionId] = next;
107
+ else delete current[sessionId];
108
+ if (JSON.stringify(previous) === JSON.stringify(next ?? null)) return next ?? null;
109
+ const serialized = JSON.stringify(current);
110
+ if (Buffer.byteLength(serialized) > MAX_FILE_BYTES) throw invalidShelf();
111
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
112
+ const temporary = `${file}.tmp`;
113
+ await writeFile(temporary, serialized, { mode: 0o600 });
114
+ await rename(temporary, file);
115
+ return next ?? null;
116
+ }));
117
+ writeChain = operation.catch(() => {});
118
+ return operation;
119
+ };
120
+
121
+ /**
122
+ * Apply `{ settled?, snoozedUntil? }`. An omitted field is left alone;
123
+ * `null` clears it. Returns the session's entry after the write, or null.
124
+ */
125
+ const update = async (sessionId, patch) => {
126
+ if (!isSessionId(sessionId) || !isRecord(patch)) throw invalidArgument();
127
+ const hasSettled = Object.hasOwn(patch, 'settled');
128
+ const hasSnooze = Object.hasOwn(patch, 'snoozedUntil');
129
+ if (!hasSettled && !hasSnooze) throw invalidArgument();
130
+ if (hasSettled && patch.settled !== null && !SETTLED_STATES.has(patch.settled)) throw invalidArgument();
131
+ if (hasSnooze && patch.snoozedUntil !== null && !isTimestamp(patch.snoozedUntil)) throw invalidArgument();
132
+ if (hasSettled && hasSnooze && patch.settled === 'settled' && patch.snoozedUntil !== null) throw invalidArgument();
133
+
134
+ return mutate(sessionId, (previous) => {
135
+ const at = now();
136
+ const next = { ...previous };
137
+ if (hasSettled) {
138
+ delete next.settled;
139
+ delete next.settledAt;
140
+ if (patch.settled === 'settled') {
141
+ next.settled = 'settled';
142
+ next.settledAt = previous?.settled === 'settled' && previous.settledAt ? previous.settledAt : at;
143
+ delete next.snoozedUntil;
144
+ delete next.snoozedAt;
145
+ } else if (patch.settled === 'active') {
146
+ next.settled = 'active';
147
+ }
148
+ }
149
+ if (hasSnooze) {
150
+ delete next.snoozedUntil;
151
+ delete next.snoozedAt;
152
+ if (patch.snoozedUntil !== null) {
153
+ next.snoozedUntil = patch.snoozedUntil;
154
+ next.snoozedAt = at;
155
+ if (next.settled === 'settled') {
156
+ delete next.settled;
157
+ delete next.settledAt;
158
+ }
159
+ }
160
+ }
161
+ return Object.keys(next).length > 0 ? next : null;
162
+ });
163
+ };
164
+
165
+ /** A message the user sent ends a snooze and drops any settled override. */
166
+ const clearForActivity = async (sessionId) => {
167
+ if (!isSessionId(sessionId)) return null;
168
+ const shelf = await read();
169
+ if (!shelf[sessionId]) return null;
170
+ return mutate(sessionId, () => null);
171
+ };
172
+
173
+ const remove = async (sessionId) => {
174
+ if (!isSessionId(sessionId)) return;
175
+ const shelf = await read();
176
+ if (!shelf[sessionId]) return;
177
+ await mutate(sessionId, () => null);
178
+ };
179
+
180
+ return { read, update, clearForActivity, remove };
181
+ };
@@ -0,0 +1,73 @@
1
+ import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { describe, expect, it } from 'vitest';
5
+
6
+ import { createPiSessionShelfStore } from './session-shelf-store.js';
7
+
8
+ const createStore = async (clock = { now: 1_000 }) => {
9
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-shelf-'));
10
+ const file = join(root, 'pi', 'session-shelf.json');
11
+ return { file, clock, store: createPiSessionShelfStore({ file, now: () => clock.now }) };
12
+ };
13
+
14
+ describe('Pi session shelf sidecar', () => {
15
+ it('reads a missing file as an empty shelf', async () => {
16
+ const { store } = await createStore();
17
+ await expect(store.read()).resolves.toEqual({});
18
+ });
19
+
20
+ it('settles, keeps active, and clears an override', async () => {
21
+ const { store, clock } = await createStore();
22
+ await expect(store.update('s1', { settled: 'settled' })).resolves.toEqual({ settled: 'settled', settledAt: 1_000 });
23
+ clock.now = 2_000;
24
+ // Settling again keeps the first settle time.
25
+ await expect(store.update('s1', { settled: 'settled' })).resolves.toEqual({ settled: 'settled', settledAt: 1_000 });
26
+ await expect(store.update('s1', { settled: 'active' })).resolves.toEqual({ settled: 'active' });
27
+ await expect(store.update('s1', { settled: null })).resolves.toBeNull();
28
+ await expect(store.read()).resolves.toEqual({});
29
+ });
30
+
31
+ it('snoozing clears a settled override and settling clears a snooze', async () => {
32
+ const { store, clock } = await createStore();
33
+ await store.update('s1', { settled: 'settled' });
34
+ clock.now = 5_000;
35
+ await expect(store.update('s1', { snoozedUntil: 9_000 })).resolves.toEqual({ snoozedUntil: 9_000, snoozedAt: 5_000 });
36
+ await expect(store.update('s1', { settled: 'settled' })).resolves.toEqual({ settled: 'settled', settledAt: 5_000 });
37
+ await store.update('s2', { settled: 'active' });
38
+ await expect(store.update('s2', { snoozedUntil: 9_000 })).resolves.toEqual({ settled: 'active', snoozedUntil: 9_000, snoozedAt: 5_000 });
39
+ await expect(store.update('s2', { snoozedUntil: null })).resolves.toEqual({ settled: 'active' });
40
+ });
41
+
42
+ it('clears both on activity and on delete without touching other sessions', async () => {
43
+ const { store } = await createStore();
44
+ await store.update('s1', { snoozedUntil: 9_000 });
45
+ await store.update('s2', { settled: 'settled' });
46
+ await store.update('s3', { settled: 'active' });
47
+ await expect(store.clearForActivity('s1')).resolves.toBeNull();
48
+ await expect(store.clearForActivity('missing')).resolves.toBeNull();
49
+ await store.remove('s2');
50
+ await expect(store.read()).resolves.toEqual({ s3: { settled: 'active' } });
51
+ });
52
+
53
+ it('rejects invalid requests', async () => {
54
+ const { store } = await createStore();
55
+ await expect(store.update('s1', {})).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
56
+ await expect(store.update('s1', { settled: 'done' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
57
+ await expect(store.update('s1', { snoozedUntil: -1 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
58
+ await expect(store.update('s1', { settled: 'settled', snoozedUntil: 9_000 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
59
+ await expect(store.update('__proto__', { settled: 'settled' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
60
+ });
61
+
62
+ it('fails on malformed metadata instead of reading it as empty', async () => {
63
+ const { store, file } = await createStore();
64
+ await store.update('s1', { settled: 'settled' });
65
+ await writeFile(file, 'not-json');
66
+ await expect(store.read()).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
67
+ await writeFile(file, JSON.stringify({ s1: { settled: 'settled' } }));
68
+ await expect(store.read()).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
69
+ // A failed read must not overwrite the file.
70
+ await expect(store.update('s2', { settled: 'active' })).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
71
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ s1: { settled: 'settled' } });
72
+ });
73
+ });
@@ -38,6 +38,7 @@ const PORTABLE_FIELDS = new Set([
38
38
  'timeFormatPreference',
39
39
  'weekStartPreference',
40
40
  'sidebarViewMode',
41
+ 'sidebarAutoSettleAfterDays',
41
42
  'expandedEditorToolbar',
42
43
  'wrapLinesByDefault',
43
44
  'fontSize', 'terminalFontSize', 'editorFontSize', 'uiFont', 'monoFont', 'padding',