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

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 (137) hide show
  1. package/dist/assets/{DiagramView-Dq5w8TCG.js → DiagramView--XO16VPB.js} +1 -1
  2. package/dist/assets/DiffView-Duy2_7Gp.js +18 -0
  3. package/dist/assets/{FileSaveConflictDialog-dFqLbFzT.js → FileSaveConflictDialog-B1DvL9zy.js} +2 -2
  4. package/dist/assets/FilesView-CjjPpE4c.js +6 -0
  5. package/dist/assets/{GitHubDetailScaffold-B2HRjT8V.js → GitHubDetailScaffold-DqxAKqCT.js} +4 -4
  6. package/dist/assets/{GitHubLinkPicker-D7I3J9_O.js → GitHubLinkPicker-ELF_chia.js} +1 -1
  7. package/dist/assets/GitHubListPrimitives-C2nGTntk.js +1 -0
  8. package/dist/assets/GitView-5fIq2nzM.js +9 -0
  9. package/dist/assets/IssuesSurface-Dq5A_bWq.js +7 -0
  10. package/dist/assets/{JsonTreeView-BJr5kBg4.js → JsonTreeView-BjFFSUwi.js} +1 -1
  11. package/dist/assets/MarkdownRendererImpl-B9Cu4TCh.js +12 -0
  12. package/dist/assets/{PatchDiff-B6RBZULC.js → PatchDiff-CTqTTcg7.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-YJJQkE7t.js → PierreDiffViewer-H2f4pJ1k.js} +15 -3
  14. package/dist/assets/PullRequestsSurface-DPpb2RW_.js +2 -0
  15. package/dist/assets/SessionSwitcherContent-B5DaBWZU.js +1 -0
  16. package/dist/assets/{SessionSwitcherDropdown-CEAid1Bd.js → SessionSwitcherDropdown-D86FaZg_.js} +2 -2
  17. package/dist/assets/SessionUnreadDot-CY9-1iV2.js +1 -0
  18. package/dist/assets/SettingsView-CiIuOi_E.js +6 -0
  19. package/dist/assets/{SettingsWindow-5dK-buUn.js → SettingsWindow-Bw1dUoJ1.js} +1 -1
  20. package/dist/assets/{StickyHorizontalScrollbar-p7EbL2-E.js → StickyHorizontalScrollbar-DNsbTLS7.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-gITobhpo.js → ToolOutputDialog-aR4kcgKL.js} +5 -5
  22. package/dist/assets/{ToolPartDiffPreview-nOJxBl-Y.js → ToolPartDiffPreview-B_wWmhtE.js} +1 -1
  23. package/dist/assets/{VirtualizedFileDiff-BmJk6XJm.js → VirtualizedFileDiff-BYby097w.js} +4 -4
  24. package/dist/assets/{Virtualizer-DNJrJKVb.js → Virtualizer-okhy9Aq3.js} +1 -1
  25. package/dist/assets/{collapsible-0yfy07W2.js → collapsible-Dz0bPrJ_.js} +1 -1
  26. package/dist/assets/{computeVirtualFileMetrics-BCFpa-1q.js → computeVirtualFileMetrics-8MuwxSC6.js} +1 -1
  27. package/dist/assets/{contextFileOpenGuard-BCi5nTZp.js → contextFileOpenGuard-fZ2NIQMQ.js} +1 -1
  28. package/dist/assets/fileTreeStatus-BzhMMLA9.js +7 -0
  29. package/dist/assets/gitStatusPredicates-Cyh9UhYX.js +1 -0
  30. package/dist/assets/{githubLink-CCmFsyTF.js → githubLink-D2PznPcI.js} +2 -2
  31. package/dist/assets/{index-BaeFf5Q8.js → index-BX5pAOQX.js} +1 -1
  32. package/dist/assets/index-Cs2nBW_t.js +11 -0
  33. package/dist/assets/index-tmO0fZa4.css +1 -0
  34. package/dist/assets/main-7vBNPBMb.js +137 -0
  35. package/dist/assets/{main-CgXs2e27.js → main-BI6qe8pz.js} +2 -2
  36. package/dist/assets/{markdownCore-DTNVLpYS.js → markdownCore-D5jiabKe.js} +1 -1
  37. package/dist/assets/{miniChat-CrAin_em.js → miniChat-B3up4Bnz.js} +2 -2
  38. package/dist/assets/{mobile-EK9oTupb.js → mobile-B4vLFgBc.js} +2 -2
  39. package/dist/assets/{nativeFileSave-Bhafll_7.js → nativeFileSave-DpBH1Sa3.js} +1 -1
  40. package/dist/assets/{pi-session-focus-preference-BoN1cyoG.js → pi-session-focus-preference-BrB72skF.js} +3 -3
  41. package/dist/assets/{renderDiffWithHighlighter-DixZh5Zd.js → renderDiffWithHighlighter-B6T04JGG.js} +1 -1
  42. package/dist/assets/renderElectronMiniChatApp-CX10w321.js +2 -0
  43. package/dist/assets/{renderFileWithHighlighter-s6fQq9eg.js → renderFileWithHighlighter-DtAcGyJr.js} +1 -1
  44. package/dist/assets/renderMobileApp-C9n-BhPZ.js +11 -0
  45. package/dist/assets/runtimeEndpointReset-aGyXPXPs.js +62 -0
  46. package/dist/assets/{runtimeSurface-CJN1oo_1.js → runtimeSurface-DiP2a57a.js} +1 -1
  47. package/dist/assets/useAppFontEffects-Oyin3dgQ.js +215 -0
  48. package/dist/assets/useGitHubRemoteSearch-CZ9Hauw0.js +1 -0
  49. package/dist/assets/useSwitcherItems-BSqDA1IF.js +1 -0
  50. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BLsm9T1Y.js → vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-C7vVMZTg.js → vendor-base-ui-BCqPBzDj.js} +1 -1
  52. package/dist/assets/{vendor-boot-CoTxysn6.js → vendor-boot-3SaHYVb1.js} +18 -18
  53. package/dist/assets/{vendor-capacitor-app-NX6DULfp.js → vendor-capacitor-app-NbQ-WiPS.js} +1 -1
  54. package/dist/assets/{vendor-capacitor-keyboard-DJD81I9f.js → vendor-capacitor-keyboard-CgrHt8iN.js} +1 -1
  55. package/dist/assets/{vendor-capacitor-status-bar-DV24OoQV.js → vendor-capacitor-status-bar-CWt0OF5t.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-autocomplete-qsuH4Dh-.js → vendor-codemirror-autocomplete-WThuuUAz.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-ZHWyBf7j.js → vendor-codemirror-lang-angular-BbLGCxF6.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-cpp-pCTOmv-k.js → vendor-codemirror-lang-cpp-Cceks-9O.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-css-2bFuyM70.js → vendor-codemirror-lang-css-D1wpUg3Z.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-go-DrG_c7D7.js → vendor-codemirror-lang-go-Cv0zXHHM.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-html-BV8lrR8v.js → vendor-codemirror-lang-html-DbL8oT9H.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-java-DrsvH6T2.js → vendor-codemirror-lang-java-CNugenuC.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-javascript-Dkzl3s07.js → vendor-codemirror-lang-javascript-Bx_FIyZF.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-jinja-8Nn3bnoP.js → vendor-codemirror-lang-jinja-DDGjB3Zq.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-json-CsdmtHhi.js → vendor-codemirror-lang-json-DIvqf9Pb.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-less-DJuZ4cZe.js → vendor-codemirror-lang-less-D8r9dGG1.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-liquid-D2RO-Pzr.js → vendor-codemirror-lang-liquid-B24mguYi.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-markdown-C0Zu3b3n.js → vendor-codemirror-lang-markdown-v3yG2sbf.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-php-CuDtt2Zj.js → vendor-codemirror-lang-php-BcZGalqy.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-python-Cv2exx_M.js → vendor-codemirror-lang-python-b-JqEwQy.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-rust-C4TxJ6Rg.js → vendor-codemirror-lang-rust-B1uZxDW-.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sass-BmtPz8kf.js → vendor-codemirror-lang-sass-DqPrngKp.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-sql-BF1ZaXqJ.js → vendor-codemirror-lang-sql-UyCnpt-k.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-vue-DZgXrP2k.js → vendor-codemirror-lang-vue-xDwYkovV.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-wast-DsnaGtL_.js → vendor-codemirror-lang-wast-CF3169p_.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-xml-D8DzzFat.js → vendor-codemirror-lang-xml-FCtVhuOb.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-yaml-D5hBv7m6.js → vendor-codemirror-lang-yaml-g0sPmAnv.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-language-data-vn2RyN9T.js → vendor-codemirror-language-data-B03xgzP2.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-search-BVCYIV0D.js → vendor-codemirror-search-Dw3Wpu15.js} +1 -1
  80. package/dist/assets/{vendor-lezer-cpp-vqXSn3lv.js → vendor-lezer-cpp-Cu3E-KUI.js} +1 -1
  81. package/dist/assets/{vendor-lezer-css-JnEzSyZR.js → vendor-lezer-css-Cb8vp67u.js} +1 -1
  82. package/dist/assets/{vendor-lezer-go-dD2gQMIL.js → vendor-lezer-go-BTsIaOm7.js} +1 -1
  83. package/dist/assets/{vendor-lezer-html-Cr3U-1pu.js → vendor-lezer-html-UQMsUwj-.js} +1 -1
  84. package/dist/assets/{vendor-lezer-java-CRM0IMCo.js → vendor-lezer-java-BIWrFrAx.js} +1 -1
  85. package/dist/assets/{vendor-lezer-javascript-B3s21DIS.js → vendor-lezer-javascript-BH2Etgoy.js} +1 -1
  86. package/dist/assets/{vendor-lezer-json-DPFM6EBV.js → vendor-lezer-json-CE-QUCwM.js} +1 -1
  87. package/dist/assets/{vendor-lezer-lr-Bllrq8hY.js → vendor-lezer-lr-HY6Yc0Vr.js} +1 -1
  88. package/dist/assets/{vendor-lezer-markdown-6-3PLvXG.js → vendor-lezer-markdown-xFL3Evwf.js} +1 -1
  89. package/dist/assets/{vendor-lezer-php-DOyzfHRl.js → vendor-lezer-php-Cr_mQGrG.js} +1 -1
  90. package/dist/assets/{vendor-lezer-python-CdHdN5qt.js → vendor-lezer-python-BNRFWCb0.js} +1 -1
  91. package/dist/assets/{vendor-lezer-rust-CqnW8EMH.js → vendor-lezer-rust-BvfOK5cU.js} +1 -1
  92. package/dist/assets/{vendor-lezer-sass-BbcF4y6A.js → vendor-lezer-sass-qoxiLisk.js} +1 -1
  93. package/dist/assets/{vendor-lezer-xml-C31AyWoo.js → vendor-lezer-xml--x8SSpqU.js} +1 -1
  94. package/dist/assets/{vendor-lezer-yaml-Cv908yC2.js → vendor-lezer-yaml-BDo1JaEr.js} +1 -1
  95. package/dist/assets/{vendor-replit-codemirror-vim-Cwhyn_5f.js → vendor-replit-codemirror-vim-D1Fe7FiY.js} +1 -1
  96. package/dist/assets/{web-components-Bz5oGa3p.js → web-components-CkTNGkJ2.js} +4 -4
  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/archive-store.js +38 -10
  107. package/server/lib/pi/archive-store.test.js +10 -0
  108. package/server/lib/pi/routes.js +107 -2
  109. package/server/lib/pi/routes.test.js +255 -0
  110. package/server/lib/pi/session-daemon/DOCUMENTATION.md +5 -1
  111. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +18 -0
  112. package/server/lib/pi/session-daemon/session-daemon.js +24 -1
  113. package/server/lib/pi/session-shelf-store.js +252 -0
  114. package/server/lib/pi/session-shelf-store.test.js +174 -0
  115. package/server/lib/pi/ui-settings-store.js +60 -0
  116. package/server/lib/pi/ui-settings-store.test.js +105 -6
  117. package/dist/assets/DiffView-CFIjN2zy.js +0 -18
  118. package/dist/assets/FilesView-D0b2mEKA.js +0 -6
  119. package/dist/assets/GitHubListPrimitives-Dw5LAmzm.js +0 -1
  120. package/dist/assets/GitView-Dhr7qVeI.js +0 -9
  121. package/dist/assets/IssuesSurface-Bya7OsRl.js +0 -7
  122. package/dist/assets/MarkdownRendererImpl-DadkFPCz.js +0 -12
  123. package/dist/assets/PullRequestsSurface-D8JpzP5l.js +0 -2
  124. package/dist/assets/SessionSwitcherContent-CJ6C2ZKG.js +0 -1
  125. package/dist/assets/SessionUnreadDot-I1_tmqY9.js +0 -1
  126. package/dist/assets/SettingsView-B-b76XDV.js +0 -6
  127. package/dist/assets/gitStatusPredicates-BQOqDJU1.js +0 -1
  128. package/dist/assets/index-C2ISrmRR.js +0 -11
  129. package/dist/assets/index-DgwThEwf.css +0 -1
  130. package/dist/assets/main-DoVzQV56.js +0 -137
  131. package/dist/assets/renderElectronMiniChatApp-0MqKeGfI.js +0 -2
  132. package/dist/assets/renderMobileApp-BLoXL_J8.js +0 -11
  133. package/dist/assets/runtimeEndpointReset-Bv2Y1fMm.js +0 -62
  134. package/dist/assets/useAppFontEffects-D2xXdmYC.js +0 -215
  135. package/dist/assets/useFilesViewSearch-BKotcAUN.js +0 -7
  136. package/dist/assets/useGitHubRemoteSearch-CZ92xKSw.js +0 -1
  137. package/dist/assets/useSwitcherItems-BfA4omGb.js +0 -1
@@ -0,0 +1,174 @@
1
+ import { mkdtemp, readFile, writeFile, mkdir } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { describe, expect, it, vi } from 'vitest';
5
+
6
+ import { createPiArchiveStore } from './archive-store.js';
7
+ import { createPiSessionShelfStore } from './session-shelf-store.js';
8
+
9
+ const createStore = async (clock = { now: 1_000 }, { archiveStore } = {}) => {
10
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-shelf-'));
11
+ const file = join(root, 'pi', 'session-shelf.json');
12
+ const archiveFile = join(root, 'pi', 'session-archive.json');
13
+ const archive = archiveStore ?? createPiArchiveStore({ file: archiveFile });
14
+ return {
15
+ file,
16
+ archiveFile,
17
+ archive,
18
+ clock,
19
+ store: createPiSessionShelfStore({ file, now: () => clock.now, archiveStore: archive }),
20
+ };
21
+ };
22
+
23
+ const writeLegacyShelf = async (file, shelf) => {
24
+ await mkdir(join(file, '..'), { recursive: true });
25
+ await writeFile(file, JSON.stringify(shelf));
26
+ };
27
+
28
+ describe('Pi session shelf sidecar', () => {
29
+ it('reads a missing file as an empty shelf', async () => {
30
+ const { store } = await createStore();
31
+ await expect(store.read()).resolves.toEqual({});
32
+ });
33
+
34
+ it('snoozes and wakes a session', async () => {
35
+ const { store, clock } = await createStore();
36
+ await expect(store.update('s1', { snoozedUntil: 9_000 })).resolves.toEqual({ snoozedUntil: 9_000, snoozedAt: 1_000 });
37
+ clock.now = 2_000;
38
+ await expect(store.update('s1', { snoozedUntil: 12_000 })).resolves.toEqual({ snoozedUntil: 12_000, snoozedAt: 2_000 });
39
+ await expect(store.update('s1', { snoozedUntil: null })).resolves.toBeNull();
40
+ await expect(store.read()).resolves.toEqual({});
41
+ });
42
+
43
+ it('clears on activity and on delete without touching other sessions', async () => {
44
+ const { store } = await createStore();
45
+ await store.update('s1', { snoozedUntil: 9_000 });
46
+ await store.update('s2', { snoozedUntil: 9_000 });
47
+ await store.update('s3', { snoozedUntil: 9_000 });
48
+ await expect(store.clearForActivity('s1')).resolves.toBeNull();
49
+ await expect(store.clearForActivity('missing')).resolves.toBeNull();
50
+ await store.remove('s2');
51
+ await expect(store.read()).resolves.toEqual({ s3: { snoozedUntil: 9_000, snoozedAt: 1_000 } });
52
+ });
53
+
54
+ it('rejects invalid requests, including the retired settled field', async () => {
55
+ const { store } = await createStore();
56
+ await expect(store.update('s1', {})).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
57
+ await expect(store.update('s1', { settled: 'settled' })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
58
+ await expect(store.update('s1', { snoozedUntil: -1 })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
59
+ await expect(store.update('__proto__', { snoozedUntil: 9_000 })).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', { snoozedUntil: 9_000 });
65
+ await writeFile(file, 'not-json');
66
+ await expect(store.read()).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
67
+ await writeFile(file, JSON.stringify({ s1: { snoozedUntil: 9_000 } }));
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', { snoozedUntil: 9_000 })).rejects.toMatchObject({ code: 'SESSION_SHELF_INVALID' });
71
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ s1: { snoozedUntil: 9_000 } });
72
+ });
73
+
74
+ describe('settled migration', () => {
75
+ it('archives hand-settled sessions at their settle time and drops the settled fields', async () => {
76
+ const { store, file, archive } = await createStore();
77
+ await writeLegacyShelf(file, {
78
+ settledOnly: { settled: 'settled', settledAt: 500 },
79
+ keptActive: { settled: 'active' },
80
+ keptActiveSnoozed: { settled: 'active', snoozedUntil: 9_000, snoozedAt: 700 },
81
+ snoozed: { snoozedUntil: 9_000, snoozedAt: 800 },
82
+ });
83
+
84
+ await expect(store.read()).resolves.toEqual({
85
+ keptActiveSnoozed: { snoozedUntil: 9_000, snoozedAt: 700 },
86
+ snoozed: { snoozedUntil: 9_000, snoozedAt: 800 },
87
+ });
88
+ await expect(archive.read()).resolves.toEqual({ settledOnly: 500 });
89
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
90
+ keptActiveSnoozed: { snoozedUntil: 9_000, snoozedAt: 700 },
91
+ snoozed: { snoozedUntil: 9_000, snoozedAt: 800 },
92
+ });
93
+ });
94
+
95
+ it('keeps an existing archive time and leaves other archived sessions alone', async () => {
96
+ const { store, file, archive, archiveFile } = await createStore();
97
+ await mkdir(join(archiveFile, '..'), { recursive: true });
98
+ await writeFile(archiveFile, JSON.stringify({ settled: 300, other: 400 }));
99
+ await writeLegacyShelf(file, { settled: { settled: 'settled', settledAt: 500 } });
100
+ await store.read();
101
+ await expect(archive.read()).resolves.toEqual({ settled: 300, other: 400 });
102
+ });
103
+
104
+ it('runs once: an unarchive after the migration sticks', async () => {
105
+ const { store, file, archive } = await createStore();
106
+ await writeLegacyShelf(file, { s1: { settled: 'settled', settledAt: 500 } });
107
+ await store.read();
108
+ await archive.set('s1', false);
109
+ await store.read();
110
+ await store.update('s2', { snoozedUntil: 9_000 });
111
+ await expect(archive.read()).resolves.toEqual({});
112
+ });
113
+
114
+ it('keeps settled marks while the archive write fails, lets snooze writes through, and retries on the next read', async () => {
115
+ const real = createPiArchiveStore({ file: join(await mkdtemp(join(tmpdir(), 'pichamber-pi-archive-')), 'a.json') });
116
+ let failing = true;
117
+ const archiveStore = {
118
+ read: real.read,
119
+ set: real.set,
120
+ archiveMissing: async (entries) => {
121
+ if (failing) throw Object.assign(new Error('disk full'), { code: 'EIO' });
122
+ return real.archiveMissing(entries);
123
+ },
124
+ };
125
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
126
+ const { store, file, clock } = await createStore(undefined, { archiveStore });
127
+ const legacy = {
128
+ s1: { settled: 'settled', settledAt: 500 },
129
+ s2: { snoozedUntil: 9_000, snoozedAt: 800 },
130
+ s4: { settled: 'settled', settledAt: 600, snoozedUntil: 9_500, snoozedAt: 700 },
131
+ };
132
+ await writeLegacyShelf(file, legacy);
133
+
134
+ // Reads answer with the snooze state; the file keeps the legacy data.
135
+ await expect(store.read()).resolves.toEqual({
136
+ s2: { snoozedUntil: 9_000, snoozedAt: 800 },
137
+ s4: { snoozedUntil: 9_500, snoozedAt: 700 },
138
+ });
139
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(legacy);
140
+
141
+ // Snooze and wake still write and leave the settled fields as they
142
+ // were. A send or a delete drops that session's settled mark too, so
143
+ // the retried migration never archives a session the user just used.
144
+ clock.now = 2_000;
145
+ await expect(store.update('s3', { snoozedUntil: 9_000 })).resolves.toEqual({ snoozedUntil: 9_000, snoozedAt: 2_000 });
146
+ await expect(store.update('s1', { snoozedUntil: 8_000 })).resolves.toEqual({ snoozedUntil: 8_000, snoozedAt: 2_000 });
147
+ await expect(store.clearForActivity('s4')).resolves.toBeNull();
148
+ await expect(store.update('s2', { snoozedUntil: null })).resolves.toBeNull();
149
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
150
+ s1: { settled: 'settled', settledAt: 500, snoozedUntil: 8_000, snoozedAt: 2_000 },
151
+ s3: { snoozedUntil: 9_000, snoozedAt: 2_000 },
152
+ });
153
+ await expect(real.read()).resolves.toEqual({});
154
+ expect(warn).toHaveBeenCalled();
155
+
156
+ failing = false;
157
+ await store.read();
158
+ await expect(real.read()).resolves.toEqual({ s1: 500 });
159
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({
160
+ s1: { snoozedUntil: 8_000, snoozedAt: 2_000 },
161
+ s3: { snoozedUntil: 9_000, snoozedAt: 2_000 },
162
+ });
163
+ warn.mockRestore();
164
+ });
165
+
166
+ it('migrates before a write so settled sessions are never dropped unarchived', async () => {
167
+ const { store, file, archive } = await createStore();
168
+ await writeLegacyShelf(file, { s1: { settled: 'settled', settledAt: 500 } });
169
+ await store.update('s2', { snoozedUntil: 9_000 });
170
+ await expect(archive.read()).resolves.toEqual({ s1: 500 });
171
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ s2: { snoozedUntil: 9_000, snoozedAt: 1_000 } });
172
+ });
173
+ });
174
+ });
@@ -38,6 +38,8 @@ const PORTABLE_FIELDS = new Set([
38
38
  'timeFormatPreference',
39
39
  'weekStartPreference',
40
40
  'sidebarViewMode',
41
+ 'sidebarAutoSettleAfterDays',
42
+ 'sessionAutoArchiveAfterDays', 'sessionAutoDeleteAfterDays',
41
43
  'expandedEditorToolbar',
42
44
  'wrapLinesByDefault',
43
45
  'fontSize', 'terminalFontSize', 'editorFontSize', 'uiFont', 'monoFont', 'padding',
@@ -70,6 +72,17 @@ const LOCAL_FIELDS = new Set([
70
72
  'hasManagedRemoteTunnelToken', 'desktopUiPassword', 'desktopLocalClientToken',
71
73
  ]);
72
74
 
75
+ const RETENTION_FIELDS = ['sessionAutoArchiveAfterDays', 'sessionAutoDeleteAfterDays'];
76
+ const MAX_RETENTION_DAYS = 365;
77
+ const NEW_INSTALL_AUTO_ARCHIVE_DAYS = 7;
78
+ // Old "delete after N days" now archives at N and deletes this long after
79
+ // archiving, so nothing is deleted sooner than it used to be.
80
+ const MIGRATED_DELETE_AFTER_ARCHIVE_DAYS = 30;
81
+ // The old client's default when autoDeleteAfterDays was never saved.
82
+ const LEGACY_RETENTION_DAYS = 30;
83
+
84
+ const isRetentionDays = (value) => Number.isInteger(value) && value >= 0 && value <= MAX_RETENTION_DAYS;
85
+
73
86
  const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
74
87
 
75
88
  const validateValue = (value, depth = 0) => {
@@ -107,6 +120,34 @@ const readRecord = async (file, fs) => {
107
120
  }
108
121
  };
109
122
 
123
+ const legacyRetentionDays = (value) => {
124
+ if (typeof value !== 'number' || !Number.isFinite(value)) return LEGACY_RETENTION_DAYS;
125
+ return Math.max(1, Math.min(MAX_RETENTION_DAYS, Math.round(value)));
126
+ };
127
+
128
+ // Starting values for the auto-archive and auto-delete settings. Runs once:
129
+ // after this the portable file holds both fields and they are never removed.
130
+ // A new install (nothing saved in either file) gets 7/0. An existing install
131
+ // keeps what the old retention fields did, except "delete after N days" now
132
+ // archives at N and deletes 30 days after that.
133
+ const decideRetention = ({ portable, runtime }) => {
134
+ const isNewInstall = Object.keys(selectFields(portable, PORTABLE_FIELDS)).length === 0
135
+ && Object.keys(selectFields(portable, LOCAL_FIELDS)).length === 0
136
+ && Object.keys(selectFields(runtime, LOCAL_FIELDS)).length === 0;
137
+ if (isNewInstall) {
138
+ return { sessionAutoArchiveAfterDays: NEW_INSTALL_AUTO_ARCHIVE_DAYS, sessionAutoDeleteAfterDays: 0 };
139
+ }
140
+ if (portable.autoDeleteEnabled !== true) {
141
+ return { sessionAutoArchiveAfterDays: 0, sessionAutoDeleteAfterDays: 0 };
142
+ }
143
+ return {
144
+ sessionAutoArchiveAfterDays: legacyRetentionDays(portable.autoDeleteAfterDays),
145
+ sessionAutoDeleteAfterDays: portable.sessionRetentionAction === 'delete' ? MIGRATED_DELETE_AFTER_ARCHIVE_DAYS : 0,
146
+ };
147
+ };
148
+
149
+ const hasRetentionDecision = (portable) => RETENTION_FIELDS.every((field) => isRetentionDays(portable[field]));
150
+
110
151
  export const createDockerInitialLocalSettings = () => {
111
152
  const projectId = `path_${Buffer.from(DOCKER_WORKSPACE).toString('base64url')}`;
112
153
  return {
@@ -133,6 +174,9 @@ export const createPiUiSettingsStore = ({
133
174
  const portableRoot = await readRecord(file, fs);
134
175
  const runtimeRoot = await readRecord(runtimeFile, fs);
135
176
  const migrated = portableRoot[PORTABLE_SETTINGS_MARKER] === PORTABLE_SETTINGS_VERSION;
177
+ const retention = hasRetentionDecision(portableRoot)
178
+ ? null
179
+ : decideRetention({ portable: portableRoot, runtime: runtimeRoot });
136
180
 
137
181
  if (!migrated) {
138
182
  const isFreshStore = Object.keys(portableRoot).length === 0 && Object.keys(runtimeRoot).length === 0;
@@ -144,6 +188,7 @@ export const createPiUiSettingsStore = ({
144
188
  const migratedPortable = {
145
189
  [PORTABLE_SETTINGS_MARKER]: PORTABLE_SETTINGS_VERSION,
146
190
  ...selectFields(portableRoot, PORTABLE_FIELDS),
191
+ ...retention,
147
192
  };
148
193
  // Local state goes first. A failure cannot strand host state only in a
149
194
  // portable file that a later successful write might replace.
@@ -152,6 +197,16 @@ export const createPiUiSettingsStore = ({
152
197
  return { ...selectFields(migratedPortable, PORTABLE_FIELDS), ...selectFields(migratedRuntime, LOCAL_FIELDS) };
153
198
  }
154
199
 
200
+ if (retention) {
201
+ // Rewrite only the portable file; local state is already in its own file.
202
+ const decidedPortable = { ...portableRoot, ...retention };
203
+ await writeRecord(file, decidedPortable, fs);
204
+ return {
205
+ ...selectFields(decidedPortable, PORTABLE_FIELDS),
206
+ ...selectFields(runtimeRoot, LOCAL_FIELDS),
207
+ };
208
+ }
209
+
155
210
  return {
156
211
  ...selectFields(portableRoot, PORTABLE_FIELDS),
157
212
  ...selectFields(runtimeRoot, LOCAL_FIELDS),
@@ -175,6 +230,11 @@ export const createPiUiSettingsStore = ({
175
230
  throw new Error('UI_SETTINGS_INVALID');
176
231
  }
177
232
  }
233
+ for (const field of RETENTION_FIELDS) {
234
+ if (Object.hasOwn(changes, field) && !isRetentionDays(changes[field])) {
235
+ throw new Error('UI_SETTINGS_INVALID');
236
+ }
237
+ }
178
238
  return runMutation(async () => {
179
239
  const current = await readLocked();
180
240
  const portableChanges = selectFields(changes, PORTABLE_FIELDS);
@@ -12,12 +12,17 @@ const makeStore = async () => {
12
12
  return { file, runtimeFile, store: createPiUiSettingsStore({ file, runtimeFile }) };
13
13
  };
14
14
 
15
+ // What a fresh store decides for the auto-archive and auto-delete settings,
16
+ // and what an existing install with retention off maps to.
17
+ const NEW_INSTALL_RETENTION = { sessionAutoArchiveAfterDays: 7, sessionAutoDeleteAfterDays: 0 };
18
+ const RETENTION_OFF = { sessionAutoArchiveAfterDays: 0, sessionAutoDeleteAfterDays: 0 };
19
+
15
20
  const readJson = async (file) => JSON.parse(await readFile(file, 'utf8'));
16
21
 
17
22
  describe('Pi UI settings store', () => {
18
23
  it('distinguishes malformed persisted settings from a fresh store', async () => {
19
24
  const { file, store } = await makeStore();
20
- await expect(store.read()).resolves.toEqual({});
25
+ await expect(store.read()).resolves.toEqual(NEW_INSTALL_RETENTION);
21
26
  await writeFile(file, '{broken');
22
27
  await expect(store.read()).rejects.toThrow('UI_SETTINGS_INVALID');
23
28
  });
@@ -65,7 +70,7 @@ describe('Pi UI settings store', () => {
65
70
  runtimeFile: existingRuntimeFile,
66
71
  initialLocalSettings,
67
72
  });
68
- await expect(existingStore.read()).resolves.toEqual({ themeId: 'nord' });
73
+ await expect(existingStore.read()).resolves.toEqual({ themeId: 'nord', ...RETENTION_OFF });
69
74
  });
70
75
 
71
76
  it('migrates a flat settings file into portable and local allowlists', async () => {
@@ -87,6 +92,7 @@ describe('Pi UI settings store', () => {
87
92
  await expect(readJson(file)).resolves.toEqual({
88
93
  __pichamberSettingsScope: 'portable-v1',
89
94
  themeId: 'nord',
95
+ ...RETENTION_OFF,
90
96
  });
91
97
  await expect(readJson(runtimeFile)).resolves.toEqual({
92
98
  homeDirectory: '/old-home',
@@ -105,6 +111,7 @@ describe('Pi UI settings store', () => {
105
111
 
106
112
  await expect(target.store.read()).resolves.toEqual({
107
113
  themeId: 'nord',
114
+ ...NEW_INSTALL_RETENTION,
108
115
  homeDirectory: '/root',
109
116
  projects: [{ id: 'two', path: '/root/project' }],
110
117
  });
@@ -118,12 +125,14 @@ describe('Pi UI settings store', () => {
118
125
  ]);
119
126
  await expect(store.read()).resolves.toEqual({
120
127
  themeId: 'dark',
128
+ ...NEW_INSTALL_RETENTION,
121
129
  projects: [{ id: 'one', path: '/one' }],
122
130
  desktopCloseToTrayEnabled: false,
123
131
  });
124
132
  await expect(readJson(file)).resolves.toEqual({
125
133
  __pichamberSettingsScope: 'portable-v1',
126
134
  themeId: 'dark',
135
+ ...NEW_INSTALL_RETENTION,
127
136
  });
128
137
  await expect(readJson(runtimeFile)).resolves.toEqual({
129
138
  projects: [{ id: 'one', path: '/one' }],
@@ -142,6 +151,7 @@ describe('Pi UI settings store', () => {
142
151
  await expect(readJson(file)).resolves.toEqual({
143
152
  __pichamberSettingsScope: 'portable-v1',
144
153
  themeId: 'dark',
154
+ ...NEW_INSTALL_RETENTION,
145
155
  });
146
156
  await expect(readJson(runtimeFile)).resolves.toEqual({ desktopUpdateChannel: 'rc', serverUpdateChannel: 'stable' });
147
157
  await expect(store.write({ desktopUpdateChannel: 'beta' })).rejects.toThrow('UI_SETTINGS_INVALID');
@@ -242,26 +252,28 @@ describe('Pi UI settings store', () => {
242
252
  const { file, runtimeFile, store } = await makeStore();
243
253
 
244
254
  const writeResult = await store.write({ sidebarViewMode: 'folder', unknownField: 'drop-me' });
245
- expect(writeResult).toEqual({ sidebarViewMode: 'folder' });
255
+ expect(writeResult).toEqual({ sidebarViewMode: 'folder', ...NEW_INSTALL_RETENTION });
246
256
 
247
257
  const readResult = await store.read();
248
- expect(readResult).toEqual({ sidebarViewMode: 'folder' });
258
+ expect(readResult).toEqual({ sidebarViewMode: 'folder', ...NEW_INSTALL_RETENTION });
249
259
 
250
260
  const portable = await readJson(file);
251
261
  expect(portable).toEqual({
252
262
  __pichamberSettingsScope: 'portable-v1',
253
263
  sidebarViewMode: 'folder',
264
+ ...NEW_INSTALL_RETENTION,
254
265
  });
255
266
 
256
267
  const runtime = await readJson(runtimeFile);
257
268
  expect(runtime).toEqual({});
258
269
 
259
270
  const updatedResult = await store.write({ sidebarViewMode: 'timeline' });
260
- expect(updatedResult).toEqual({ sidebarViewMode: 'timeline' });
261
- expect(await store.read()).toEqual({ sidebarViewMode: 'timeline' });
271
+ expect(updatedResult).toEqual({ sidebarViewMode: 'timeline', ...NEW_INSTALL_RETENTION });
272
+ expect(await store.read()).toEqual({ sidebarViewMode: 'timeline', ...NEW_INSTALL_RETENTION });
262
273
  expect(await readJson(file)).toEqual({
263
274
  __pichamberSettingsScope: 'portable-v1',
264
275
  sidebarViewMode: 'timeline',
276
+ ...NEW_INSTALL_RETENTION,
265
277
  });
266
278
  });
267
279
 
@@ -274,6 +286,7 @@ describe('Pi UI settings store', () => {
274
286
  expect(await readJson(file)).toEqual({
275
287
  __pichamberSettingsScope: 'portable-v1',
276
288
  notifyOnInputNeeded: false,
289
+ ...NEW_INSTALL_RETENTION,
277
290
  });
278
291
 
279
292
  await expect(store.write({ notifyOnInputNeeded: true })).resolves.toMatchObject({
@@ -290,6 +303,92 @@ describe('Pi UI settings store', () => {
290
303
  await expect(store.write(changes)).rejects.toThrow('UI_SETTINGS_INVALID');
291
304
  });
292
305
 
306
+ describe('session retention starting values', () => {
307
+ const seed = async (portable, runtime) => {
308
+ const target = await makeStore();
309
+ if (portable !== undefined) await writeFile(target.file, JSON.stringify(portable));
310
+ if (runtime !== undefined) await writeFile(target.runtimeFile, JSON.stringify(runtime));
311
+ return target;
312
+ };
313
+
314
+ it('starts a new install at auto-archive 7 and auto-delete 0, and writes it', async () => {
315
+ for (const portable of [undefined, {}, { __pichamberSettingsScope: 'portable-v1' }]) {
316
+ const { file, store } = await seed(portable);
317
+ await expect(store.read()).resolves.toEqual({
318
+ sessionAutoArchiveAfterDays: 7,
319
+ sessionAutoDeleteAfterDays: 0,
320
+ });
321
+ expect(await readJson(file)).toEqual({
322
+ __pichamberSettingsScope: 'portable-v1',
323
+ sessionAutoArchiveAfterDays: 7,
324
+ sessionAutoDeleteAfterDays: 0,
325
+ });
326
+ }
327
+ });
328
+
329
+ it('maps each old retention combination on an existing install', async () => {
330
+ const cases = [
331
+ [{ themeId: 'nord' }, 0, 0],
332
+ [{ autoDeleteEnabled: false, sessionRetentionAction: 'delete', autoDeleteAfterDays: 10 }, 0, 0],
333
+ [{ autoDeleteEnabled: true, sessionRetentionAction: 'archive', autoDeleteAfterDays: 14 }, 14, 0],
334
+ [{ autoDeleteEnabled: true, sessionRetentionAction: 'delete', autoDeleteAfterDays: 21 }, 21, 30],
335
+ [{ autoDeleteEnabled: true }, 30, 0],
336
+ [{ autoDeleteEnabled: true, sessionRetentionAction: 'delete', autoDeleteAfterDays: 900 }, 365, 30],
337
+ ];
338
+ for (const [old, archive, del] of cases) {
339
+ for (const marked of [false, true]) {
340
+ const portable = marked ? { __pichamberSettingsScope: 'portable-v1', ...old } : old;
341
+ const { file, store } = await seed(portable);
342
+ const settings = await store.read();
343
+ expect([settings.sessionAutoArchiveAfterDays, settings.sessionAutoDeleteAfterDays]).toEqual([archive, del]);
344
+ const saved = await readJson(file);
345
+ expect([saved.sessionAutoArchiveAfterDays, saved.sessionAutoDeleteAfterDays]).toEqual([archive, del]);
346
+ }
347
+ }
348
+ });
349
+
350
+ it('treats saved local state as an existing install', async () => {
351
+ const { store } = await seed({ __pichamberSettingsScope: 'portable-v1' }, { projects: [{ id: 'one', path: '/one' }] });
352
+ await expect(store.read()).resolves.toMatchObject({
353
+ sessionAutoArchiveAfterDays: 0,
354
+ sessionAutoDeleteAfterDays: 0,
355
+ });
356
+ });
357
+
358
+ it('decides once and keeps later choices', async () => {
359
+ const { store } = await seed({ autoDeleteEnabled: true, sessionRetentionAction: 'delete', autoDeleteAfterDays: 5 });
360
+ await expect(store.read()).resolves.toMatchObject({ sessionAutoArchiveAfterDays: 5, sessionAutoDeleteAfterDays: 30 });
361
+ await store.write({ sessionAutoArchiveAfterDays: 0, sessionAutoDeleteAfterDays: 0, autoDeleteAfterDays: 60 });
362
+ await expect(store.read()).resolves.toMatchObject({
363
+ sessionAutoArchiveAfterDays: 0,
364
+ sessionAutoDeleteAfterDays: 0,
365
+ autoDeleteEnabled: true,
366
+ autoDeleteAfterDays: 60,
367
+ });
368
+ });
369
+
370
+ it('decides before the first write', async () => {
371
+ const { store } = await seed({ autoDeleteEnabled: true, sessionRetentionAction: 'archive', autoDeleteAfterDays: 9 });
372
+ await expect(store.write({ themeId: 'dark' })).resolves.toMatchObject({
373
+ themeId: 'dark',
374
+ sessionAutoArchiveAfterDays: 9,
375
+ sessionAutoDeleteAfterDays: 0,
376
+ });
377
+ });
378
+
379
+ it('rejects values outside off or 1 to 365 days', async () => {
380
+ const { store } = await makeStore();
381
+ for (const value of [-1, 366, 1.5, '7', null]) {
382
+ await expect(store.write({ sessionAutoArchiveAfterDays: value })).rejects.toThrow('UI_SETTINGS_INVALID');
383
+ await expect(store.write({ sessionAutoDeleteAfterDays: value })).rejects.toThrow('UI_SETTINGS_INVALID');
384
+ }
385
+ await expect(store.write({ sessionAutoArchiveAfterDays: 365, sessionAutoDeleteAfterDays: 1 })).resolves.toMatchObject({
386
+ sessionAutoArchiveAfterDays: 365,
387
+ sessionAutoDeleteAfterDays: 1,
388
+ });
389
+ });
390
+ });
391
+
293
392
  it('keeps a symlinked settings.json and writes through to its target', async () => {
294
393
  const root = await mkdtemp(join(tmpdir(), 'pichamber-ui-settings-'));
295
394
  const dotfiles = join(root, 'dotfiles');
@@ -1,18 +0,0 @@
1
- import{j as t,aP as Nt}from"./vendor-boot-CoTxysn6.js";import{R as r}from"./vendor-react-Bz1tRBxM.js";import{f as ne,h as Y,b as et,q as ze}from"./index-C2ISrmRR.js";import{eh as Ct,dW as St,ef as Lt,aO as tt,cG as nt,dv as Dt,d0 as De,B as je,I as W,z as st,bh as ce,t as it,e7 as rt,a$ as kt,b0 as Rt,b1 as Et,bu as Ge,dl as At,ei as Tt,ej as Mt,y as It,as as Pt,bw as $t,cH as Wt,dT as _t,h as Bt,b9 as Ot,aB as zt,aQ as Gt,aR as Ht,aS as Ut}from"./useAppFontEffects-D2xXdmYC.js";import{d as ot,b as Vt,i as He,a as Ue,c as Kt,C as qt}from"./gitStatusPredicates-BQOqDJU1.js";import{p as Xt}from"./VirtualizedFileDiff-BmJk6XJm.js";import{P as Qt}from"./PierreDiffViewer-YJJQkE7t.js";import{v as Yt,g as Jt}from"./contextFileOpenGuard-BCi5nTZp.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-zustand-CXhN0IMY.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-tailwind-merge-BKkUfl9q.js";import"./vendor-fuse.js-t_7AcMTv.js";import"./runtimeSurface-CJN1oo_1.js";import"./nativeFileSave-Bhafll_7.js";import"./web-components-Bz5oGa3p.js";import"./computeVirtualFileMetrics-BCFpa-1q.js";import"./vendor-shiki-BEwTOAFg.js";import"./vendor-shikijs-core-Ck_OPM_T.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-DPFxvYtK.js";import"./vendor-hast-util-to-html-O3stl53j.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-C40bX6nM.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-DrfmQi8i.js";import"./vendor-pierre-theming-BO6EPniU.js";import"./vendor-shikijs-engine-javascript-DL394yyj.js";import"./vendor-oniguruma-to-es-DgwFOwdE.js";import"./vendor-oniguruma-parser-BrbMHgHx.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./renderDiffWithHighlighter-DixZh5Zd.js";import"./vendor-diff-C3JhlQdm.js";import"./StickyHorizontalScrollbar-p7EbL2-E.js";import"./runtimeEndpointReset-Bv2Y1fMm.js";import"./SessionUnreadDot-I1_tmqY9.js";/* empty css */import"./permissionStore-zIpxq9Pq.js";import"./appThemeRegistry-Ca8eGRB9.js";import"./registerCustomTheme-C-h6lsYW.js";function Zt(n,s=10){const e=[];let i;for(const l of n.split(`
2
- `)){const f=l.match(Ct);if(f!=null){i!=null&&(i.hunkLines.length>0&&(Ee(i,s,"trailing"),Ie(i,e)),i=void 0);const d=parseInt(f[3]),y=parseInt(f[1]),m=parseInt(f[4]??"1"),c=parseInt(f[2]??"1");isNaN(d)||isNaN(y)||isNaN(m)||isNaN(c)?e.push(l):i={additionStart:d,deletionStart:y,additionCount:0,deletionCount:0,hunkLines:[],contextLines:[]};continue}if(i==null){e.push(l);continue}if(l.startsWith(" "))i.contextLines.push(l);else if(l!==""){if(i.hunkLines.length>0&&i.contextLines.length>s*2){const d=i.contextLines.length-s*2,y=i.contextLines.slice(-s);Ee(i,s,"trailing");const{additionCount:m,deletionCount:c}=i;Ie(i,e),i={additionStart:i.additionStart+m+d,deletionStart:i.deletionStart+c+d,deletionCount:0,additionCount:0,contextLines:y,hunkLines:[]}}Ee(i,s,i.hunkLines.length===0?"leading":"before-change"),i.hunkLines.push(l),l.startsWith("+")?i.additionCount+=1:l.startsWith("-")&&(i.deletionCount+=1)}}i!=null&&i.hunkLines.length>0&&(Ee(i,s,"trailing"),Ie(i,e));const a=e.join(`
3
- `);return n.endsWith(`
4
- `)?`${a}
5
- `:a}function Ee(n,s,e){if(e==="leading"&&n.contextLines.length>s){const i=n.contextLines.length-s;n.contextLines.splice(0,i),n.additionStart+=i,n.deletionStart+=i}return e==="trailing"&&n.contextLines.length>s&&(n.contextLines.length=s),n.contextLines.length>0&&(n.hunkLines.push(...n.contextLines),n.additionCount+=n.contextLines.length,n.deletionCount+=n.contextLines.length,n.contextLines.length=0),n}function Ie(n,s){s.push(`@@ -${Ve(n.deletionStart,n.deletionCount)} +${Ve(n.additionStart,n.additionCount)} @@`),s.push(...n.hunkLines)}function Ve(n,s){return s===1?`${n}`:`${n},${s}`}const en=64,tn=3,pe=new Map,nn=(n,s,e=tn)=>{const i=`${n}\0${e}\0${s}`,a=pe.get(i);if(a)return pe.delete(i),pe.set(i,a),a;const l=rn(s),f=l?St(Zt(s,e),{oldFile:{name:n,contents:l.before},newFile:{name:n,contents:l.after}})??qe(n):Lt(sn(n,s))[0]?.files[0]??qe(n);for(pe.set(i,f);pe.size>en;){const d=pe.keys().next().value;if(!d)break;pe.delete(d)}return f},sn=(n,s)=>!s.trim()||s.startsWith("diff --git ")||/^--- [^\n]*\r?\n\+\+\+ /m.test(s)?s:`Index: ${n}
6
- ===================================================================
7
- --- ${n}
8
- +++ ${n}
9
- ${s}`,rn=n=>{if(!n.startsWith("diff --git ")&&!/^--- [^\n]*\t?\r?\n\+\+\+ [^\n]*\t?(?:\r?\n|$)/m.test(n))return;const s=[...n.matchAll(/^@@\s+-(\d+)(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s+@@[^\n]*(?:\r?\n|$)/gm)];if(s.length!==1)return;const e=s[0],i=Number.parseInt(e[1]??"",10),a=Number.parseInt(e[2]??"",10);if(i>1||a>1||!Number.isFinite(i)||!Number.isFinite(a))return;const l=(e.index??0)+e[0].length,f=n.slice(l),d=[],y=[];let m;for(const c of f.split(/\r?\n/)){if(c.startsWith("diff --git ")||c.startsWith("@@ "))break;if(c.startsWith("\\")){if(m==="-"||m===" "){const p=d.at(-1);p&&(p.newline=!1)}if(m==="+"||m===" "){const p=y.at(-1);p&&(p.newline=!1)}continue}if(c.startsWith("-")){d.push({text:c.slice(1),newline:!0}),m="-";continue}if(c.startsWith("+")){y.push({text:c.slice(1),newline:!0}),m="+";continue}c.startsWith(" ")&&(d.push({text:c.slice(1),newline:!0}),y.push({text:c.slice(1),newline:!0}),m=" ")}return{before:Ke(d),after:Ke(y)}},Ke=n=>n.map(s=>s.text+(s.newline?`
10
- `:"")).join(""),qe=n=>Xt({name:n,contents:""},{name:n,contents:""}),on=n=>/^Binary files .+ differ$/m.test(n)||/^GIT binary patch$/m.test(n),$e=(n,s,e)=>on(s)?{original:"",modified:"",isBinary:!0,patch:s,contextMode:e}:{original:"",modified:"",patch:s,fileDiff:nn(n,s),contextMode:e},at=(n,s,e)=>{const i=n??0,a=s??0;return!i&&!a?null:t.jsxs("span",{className:ne("typography-meta flex items-center gap-1 text-xs whitespace-nowrap","flex-shrink-0",e?.className),children:[i?t.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i]}):null,a?t.jsxs("span",{style:{color:"var(--status-error)"},children:["-",a]}):null]})},an=r.memo(function({changedFiles:s,selectedFile:e,onSelectFile:i}){return s.length===0?null:t.jsx(tt,{outerClassName:"flex-1 min-h-0",className:"px-1 py-2",children:t.jsx("ul",{className:"flex flex-col gap-1",children:s.map(a=>{const l=ot(a),f=e===a.path;return t.jsx("li",{children:t.jsxs("button",{type:"button",onClick:()=>i(a.path),className:ne("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",f?"bg-interactive-selection text-interactive-selection-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[t.jsx(nt,{filePath:a.path,className:"h-3.5 w-3.5 flex-shrink-0"}),t.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:l.color},title:l.description,"aria-label":l.description,children:l.code}),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:a.path,children:a.path}),at(a.insertions,a.deletions)]})},a.path)})})})});function ln(n,s,e){return n==="staged"?{source:"staged",staged:!0}:n==="working"?{source:"unstaged",staged:!1}:{source:"head",staged:e.staged&&s.path===e.path||Vt(s)}}const cn=r.memo(function(){return t.jsx("div",{className:"rounded-lg border border-border/60 bg-background px-3 py-2",children:t.jsx("div",{className:"typography-meta text-muted-foreground",children:"Content of this file cannot be viewed."})})}),un=r.memo(function({filePath:s,diff:e,renderSideBySide:i}){const a=e.original.length>0,l=e.modified.length>0,f=i?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",d=i?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return t.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:t.jsxs("div",{className:f,children:[a&&t.jsxs("div",{className:d,children:[t.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),t.jsx("img",{src:e.original,alt:`Original: ${s}`,className:i?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),l&&t.jsxs("div",{className:d,children:[t.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:a?"Modified":"New"}),t.jsx("img",{src:e.modified,alt:`Modified: ${s}`,className:i?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),dn=r.memo(function({filePath:s,diff:e,renderSideBySide:i,wrapLines:a}){const l=r.useMemo(()=>Dt(s)||"text",[s]);return e.isBinary?t.jsx(cn,{}):De(s)?t.jsx(un,{filePath:s,diff:e,renderSideBySide:i}):t.jsx("div",{className:"w-full",style:{contain:"layout"},children:t.jsx(Qt,{original:e.original,modified:e.modified,fileDiff:e.fileDiff,language:l,fileName:s,renderSideBySide:i,wrapLines:a,layout:"inline"})})}),Pe=({label:n,icon:s,loading:e,disabled:i,tone:a,onClick:l})=>t.jsx(je,{variant:"ghost",size:"sm",className:ne("h-6 w-6 rounded-none bg-transparent p-0 text-muted-foreground opacity-70 hover:bg-transparent hover:text-foreground hover:opacity-100",a==="failure"&&"text-[var(--status-error)] hover:text-[var(--status-error)]",a==="success"&&"text-[var(--status-success)] hover:text-[var(--status-success)]"),disabled:i,title:n,"aria-label":n,onClick:f=>{f.stopPropagation(),l()},children:e?t.jsx(W,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(W,{name:s,className:s==="add"?"size-4":"size-3.5"})}),fn=r.memo(function({filePath:s,staged:e,busyAction:i,disabled:a,onAction:l}){return t.jsx("div",{className:"flex items-center gap-0.5 rounded-full border border-[var(--interactive-border)]/45 bg-[var(--surface-background)]/95 px-1 py-0.5 shadow-sm backdrop-blur-md",children:e?t.jsx(Pe,{label:`Unstage ${s}`,icon:"arrow-go-back",loading:i==="unstage",disabled:a,onClick:()=>l("unstage")}):t.jsxs(t.Fragment,{children:[t.jsx(Pe,{label:`Revert changes in ${s}`,icon:"arrow-go-back",loading:i==="discard",disabled:a,tone:"failure",onClick:()=>l("discard")}),t.jsx(Pe,{label:`Stage ${s}`,icon:"add",loading:i==="stage",disabled:a,tone:"success",onClick:()=>l("stage")})]})})}),lt=3,pn=1e6,hn=15e3,Xe=500,mn=r.memo(function({directory:s,file:e,layout:i,wrapLines:a,isSelected:l,isExpanded:f,isMounted:d,onSelect:y,onExpandedChange:m,registerSectionRef:c,showOpenInEditorAction:p=!1,isOpeningInEditor:F=!1,onOpenInEditor:R,diffSource:x,staged:C=!1,showFileActions:g=!0,loadFullFiles:h=!1,initialDiffData:H=null}){const{git:M}=st(),E=ce(r.useCallback(u=>u.directories.get(s)?.diffCache.get(e.path)??null,[s,e.path])),S=ce(u=>u.setDiff),_=ce(u=>u.fetchStatus),j=Y(u=>u.setDiffFileLayout),w=Y(u=>u.setDiffWrapLines),[L,D]=r.useState(0),[A,k]=r.useState(null),[I,B]=r.useState(!1),[$,ee]=r.useState(null),[ue,Ne]=r.useState(!1),[b,se]=r.useState(null),U=r.useRef(null),ie=r.useRef(null),K=r.useMemo(()=>ot(e),[e]),J=i==="side-by-side",O=h?"full":"patch",re=`${e.index}:${e.working_dir}:${e.insertions}:${e.deletions}`,q=r.useMemo(()=>H||(b?.source===x?b.data:x!=="head"||!E?null:{original:E.original,modified:E.modified,isBinary:E.isBinary,contextMode:"full"}),[E,x,H,b]),he=q?.contextMode===O,de=r.useCallback(u=>{ie.current=u,c(e.path,u)},[e.path,c]),me=r.useCallback(u=>{m(e.path,u)},[e.path,m]),ge=r.useCallback(()=>{y(e.path)},[e.path,y]);r.useEffect(()=>{se(null),k(null),U.current=null},[x,re]),r.useEffect(()=>{if(!f||!d)return;if(!s||H||q&&he){U.current=null,B(!1);return}const u=`${s}::${e.path}::${x}::${re}::${O}::${L}`;if(U.current===u)return;U.current=u,k(null),B(!0);let P=!1;const te=et(),xe=h?pn:lt,be=De(e.path)?M.getGitFileDiff(s,{path:e.path,staged:x==="staged"}):M.getGitDiff(s,{path:e.path,source:x,contextLines:xe}),ae=hn,le=new Promise((V,X)=>{setTimeout(()=>X(new Error(`Timed out after ${ae}ms`)),ae)});return Promise.race([be,le]).then(V=>{if(!P){if("diff"in V){const X=$e(e.path,V.diff,O);se({source:x,data:X})}else{const X={original:V.original??"",modified:V.modified??"",isBinary:V.isBinary,contextMode:"full"};x==="head"?S(s,e.path,X,te):se({source:x,data:X})}B(!1)}}).catch(V=>{if(P)return;const X=V instanceof Error?V.message:String(V);k(X),B(!1)}),()=>{P=!0,U.current===u&&(U.current=null)}},[O,q,he,L,x,s,e.path,re,M,H,f,d,h,S]);const oe=r.useCallback(()=>{me(!f),ge()},[me,ge,f]),Ce=r.useCallback(async u=>{if(!(!s||$!==null)){ee(u);try{u==="stage"?await M.stageGitFile(s,e.path):u==="unstage"?await M.unstageGitFile(s,e.path):await M.revertGitFile(s,e.path,{scope:"working"}),D(P=>P+1),await _(s,M)}catch(P){const te=u==="unstage"?"Failed to unstage changes":u==="stage"?"Failed to stage changes":"Failed to revert changes";it.error(P instanceof Error?P.message:te)}finally{ee(P=>P===u?null:P)}}},[s,_,e.path,$,M]);return t.jsxs("div",{ref:de,className:ne("scroll-mt-9 border-b border-[var(--interactive-border)]/40 last:border-b-0"),children:[t.jsx("div",{className:ne("z-30 border-b border-[var(--interactive-border)]/35 bg-[var(--surface-elevated)]/90 backdrop-blur-md supports-[backdrop-filter]:bg-[var(--surface-elevated)]/80","sticky top-0"),children:t.jsxs("div",{role:"button",tabIndex:0,onClick:oe,onKeyDown:u=>{u.target===u.currentTarget&&(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),oe())},className:ne("cursor-pointer","group/header relative grid min-h-9 w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 overflow-hidden px-3 py-2","bg-transparent","text-muted-foreground hover:text-foreground",l?"bg-[var(--interactive-selection)]/35":null),children:[t.jsx("div",{className:"absolute inset-0 pointer-events-none group-hover/header:bg-[var(--interactive-hover)]/50"}),t.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[t.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover/header:opacity-100",children:f?t.jsx(W,{name:"arrow-down-s",className:"size-4"}):t.jsx(W,{name:"arrow-right-s",className:"size-4"})}),t.jsx("span",{className:"typography-micro font-semibold leading-none w-4 text-center uppercase",style:{color:K.color},title:K.description,"aria-label":K.description,children:K.code}),t.jsx("span",{className:"min-w-0 flex-1 overflow-hidden typography-ui-label",title:e.path,children:t.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[t.jsx(nt,{filePath:e.path,className:"h-3.5 w-3.5 flex-shrink-0 align-middle"}),(()=>{const u=e.path.lastIndexOf("/");if(u===-1)return t.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:e.path});const P=e.path.slice(0,u),te=e.path.slice(u+1);return t.jsxs("span",{className:"flex min-w-0 items-baseline overflow-hidden",children:[t.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:P}),t.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[t.jsx("span",{className:"text-muted-foreground",children:"/"}),t.jsx("span",{className:"text-foreground",children:te})]})]})})()]})})]}),t.jsxs("div",{className:"relative flex shrink-0 items-center justify-self-end gap-2",children:[at(e.insertions,e.deletions),p&&R?t.jsx(je,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:"Open this file in editor at change",onClick:u=>{u.stopPropagation(),R(e.path,q)},disabled:F,children:F?t.jsx(W,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(W,{name:"edit",className:"size-3.5"})}):null,t.jsx(rt,{mode:J?"side-by-side":"unified",onModeChange:u=>{const P=u==="side-by-side"?"side-by-side":"inline";j(e.path,P)},className:"opacity-70"}),t.jsxs(kt,{children:[t.jsx(Rt,{asChild:!0,children:t.jsx(je,{variant:"ghost",size:"sm",className:"h-5 w-5 p-0 opacity-70 hover:opacity-100",title:"File view options","aria-label":"File view options",onClick:u=>{u.stopPropagation()},onPointerDown:u=>{u.stopPropagation()},children:t.jsx(W,{name:"more-2-fill",className:"size-3.5"})})}),t.jsxs(Et,{align:"end",onClick:u=>{u.stopPropagation()},onPointerDown:u=>{u.stopPropagation()},children:[t.jsxs(Ge,{onSelect:()=>{w(!a)},children:[t.jsx(W,{name:"text-wrap",className:"size-4"}),t.jsx("span",{className:"flex-1",children:"Wrap lines"}),a?t.jsx(W,{name:"check",className:"size-4"}):null]}),t.jsxs(Ge,{onSelect:()=>{j(e.path,J?"inline":"side-by-side")},children:[t.jsx(W,{name:J?"align-justify":"layout-column",className:"size-4"}),J?"Switch to unified view":"Switch to side-by-side view"]})]})]})]})]})}),f&&t.jsxs("div",{className:"relative overflow-clip bg-background",children:[!d&&!A?t.jsx("div",{className:"h-40 border border-border/40 bg-background/40"}):null,A?t.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[t.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),t.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:A}),t.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>D(u=>u+1),children:"Retry"})]}):null,d&&I&&!q&&!A?t.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[t.jsx(W,{name:"loader-4",className:"size-4 animate-spin"}),"Loading diff..."]}):null,d&&q&&!ue&&e.insertions+e.deletions>Xe?t.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[t.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:`Large diff (${e.insertions+e.deletions} changed lines)`}),t.jsx("div",{className:"typography-meta text-muted-foreground",children:"Rendering may be slow. You can still view the diff by clicking below."}),t.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>Ne(!0),children:"Render anyway"})]}):null,d&&q&&(ue||e.insertions+e.deletions<=Xe)?t.jsxs(t.Fragment,{children:[t.jsx(dn,{filePath:e.path,diff:q,renderSideBySide:J,wrapLines:a}),g?t.jsx("div",{className:"pointer-events-none absolute bottom-3 right-3 z-20",children:t.jsx("div",{className:"pointer-events-auto",children:t.jsx(fn,{filePath:e.path,staged:C,busyAction:$,disabled:$!==null,onAction:Ce})})}):null]}):null]})]})}),gn=1100,Qe=300,xn=n=>n<=6?n:n<=12?6:n<=25?4:2,bn=(n,s)=>At(n,s),Ye=(n,s)=>{const e=n.split(`
11
- `),i=s.split(`
12
- `),a=Math.min(e.length,i.length);for(let l=0;l<a;l+=1)if(e[l]!==i[l])return l+1;return i.length>e.length?e.length+1:e.length>i.length?Math.max(1,i.length):1},yn=n=>Array.isArray(n)?n.filter(s=>!s||typeof s!="object"?!1:typeof s.file=="string"):[],wn=n=>n.split(/^diff --git /m).slice(1).flatMap(e=>{const[i=""]=e.split(`
13
- `,1),a=i.lastIndexOf(" b/");if(a<=2)return[];const l=i.slice(2,a),f=i.slice(a+3).trim(),d=`diff --git ${e}`,y=d.includes(`
14
- new file mode `)?"added":d.includes(`
15
- deleted file mode `)?"deleted":d.includes(`
16
- rename from `)?"renamed":"modified";let m=0,c=0;for(const p of d.split(`
17
- `))p.startsWith("+")&&!p.startsWith("+++")&&(m+=1),p.startsWith("-")&&!p.startsWith("---")&&(c+=1);return[{file:y==="deleted"?l:f,status:y,additions:m,deletions:c,patch:d}]}),Fn=n=>n==="added"?"A":n==="deleted"?"D":"M";function vn({activeDiffScope:n,effectiveDirectory:s,branchBase:e,branchHead:i,git:a,sessionMessageRecords:l}){const[f,d]=r.useState([]),[y,m]=r.useState(null),[c,p]=r.useState(!1),F=r.useMemo(()=>{const C=Tt(l,{showTextJustificationActivity:!1,mergeHiddenUserTurns:!0});for(let g=C.turns.length-1;g>=0;g-=1){const h=C.turns[g];if(!h)continue;const H=h.activityParts.map(S=>S.part).filter(S=>S.type==="tool"),M=Mt(H);if(M.length>0)return M.map(S=>({file:S.path,status:"modified",additions:S.additions,deletions:S.deletions,patch:S.patch}));const E=yn(h.userMessage.info?.summary?.diffs);if(E.length>0)return E}return[]},[l]);r.useEffect(()=>{if(n!=="branch"||!s||!e||!i||!a.getGitRangeDiff){d([]),m(null),p(!1);return}let C=!1;return p(!0),m(null),a.getGitRangeDiff(s,{base:e,head:i,contextLines:lt}).then(g=>{C||(d(wn(g.diff??"")),p(!1))}).catch(g=>{C||(d([]),p(!1),m(g instanceof Error?g.message:String(g)))}),()=>{C=!0}},[n,e,i,s,a]);const R=r.useMemo(()=>{const C=new Map;for(const g of F)if(g.file){if(typeof g.patch=="string"){C.set(g.file,$e(g.file,g.patch,"patch"));continue}typeof g.before!="string"&&typeof g.after!="string"||C.set(g.file,{original:g.before??"",modified:g.after??"",contextMode:"full"})}return C},[F]),x=r.useMemo(()=>{const C=new Map;for(const g of f)!g.file||typeof g.patch!="string"||C.set(g.file,$e(g.file,g.patch,"patch"));return C},[f]);return{branchDiffs:f,branchDiffError:y,branchDiffLoading:c,lastTurnDiffs:F,lastTurnDiffData:R,branchDiffData:x}}const Je=(n,s)=>{if(s.length===0)return null;let e=null,i=null;for(const l of s)l.top<=n?(!e||l.top>e.top)&&(e=l):(!i||l.top<i.top)&&(i=l);const a=e??i;return a?{path:a.path,topOffset:a.top-n}:null},jn=(n,s,e,i)=>Math.min(Math.max(0,i),Math.max(0,n+e-s));function Nn({pinSelectedFileHeaderToTopOnNavigate:n,scrollRequestNonce:s,changedFiles:e,expandedFiles:i,setMountedStackedFiles:a,fileDiffRefreshNonce:l}){const f=r.useRef(null),d=r.useRef(new Map),[y,m]=r.useState(null),c=r.useRef(null),p=r.useRef(null),F=r.useRef(!1),R=r.useRef(null),x=r.useRef(i),C=r.useRef(null);r.useLayoutEffect(()=>{x.current=i},[i]);const g=r.useRef(null),h=r.useCallback(()=>{const j=f.current;if(!j)return null;const w=j.getBoundingClientRect().top,L=[];for(const[D,A]of d.current)A&&L.push({path:D,top:A.getBoundingClientRect().top});return Je(w,L)},[]),H=r.useCallback(()=>{c.current=null,F.current=!1,m(null),p.current!==null&&(window.cancelAnimationFrame(p.current),p.current=null)},[]),M=r.useCallback(()=>{R.current=null;const j=f.current;if(!j)return;const w=j.getBoundingClientRect(),L=w.top-Qe,D=w.bottom+Qe,A={},k=[];for(const[I,B]of d.current){if(!B)continue;const $=B.getBoundingClientRect();k.push({path:I,top:$.top}),x.current.has(I)&&($.bottom<L||$.top>D||(A[I]=!0))}C.current=Je(w.top,k),a(I=>{let B=!1;const $=new Set(I);for(const ee of Object.keys(A))$.has(ee)||($.add(ee),B=!0);return B?$:I})},[a]),E=r.useCallback(()=>{typeof window>"u"||R.current===null&&(R.current=window.requestAnimationFrame(M))},[M]);r.useEffect(()=>{const j=f.current;if(j)return E(),j.addEventListener("scroll",E,{passive:!0}),window.addEventListener("resize",E),()=>{j.removeEventListener("scroll",E),window.removeEventListener("resize",E),R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)}},[e,i,E]),r.useLayoutEffect(()=>{const j=g.current;if(!j)return;g.current=null;const w=f.current,L=d.current.get(j.path);if(!w||!L)return;const D=w.getBoundingClientRect().top,A=L.getBoundingClientRect().top-D;w.scrollTop=jn(w.scrollTop,j.topOffset,A,w.scrollHeight-w.clientHeight),C.current=j},[l]);const S=r.useCallback((j,w)=>{const L=d.current;w?L.set(j,w):L.delete(j),E()},[E]),_=r.useCallback(j=>{const w=d.current.get(j),L=f.current;if(!w||!L)return!1;const D=w.getBoundingClientRect().top-L.getBoundingClientRect().top;return L.scrollTo({top:L.scrollTop+D,behavior:"auto"}),!0},[]);return r.useEffect(()=>{if(!c.current)return;let w=0;const L=20;let D=!1;const A=(I=!0)=>{D||(D=!0,c.current=null,F.current=!1,I&&m(null),p.current!==null&&(window.cancelAnimationFrame(p.current),p.current=null))},k=()=>{if(D){p.current=null;return}const I=c.current;if(!I){A(),p.current=null;return}if(!_(I)){w+=1,w<L?p.current=window.requestAnimationFrame(k):(A(),p.current=null);return}if(n&&F.current){m(I),A(!1);return}A()};return p.current=window.requestAnimationFrame(k),()=>{D=!0,p.current!==null&&(window.cancelAnimationFrame(p.current),p.current=null)}},[n,s,_]),{diffScrollRef:f,fileSectionRefs:d,pinnedStackedTarget:y,pendingScrollTargetRef:c,shouldPinAfterAlignRef:F,pendingScrollAnchorRestoreRef:g,lastScrollAnchorRef:C,captureScrollAnchor:h,cancelPendingScrollAlignment:H,queueVisibleStackedFilesSync:E,registerSectionRef:S,scrollToFile:_}}const Ze=n=>{if(!n)return null;const s=n.split(`
18
- `);let e=null;for(const i of s){const a=i.match(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,\d+)?\s*@@/);if(a){const l=Number.parseInt(a[1]??"",10);e=Number.isFinite(l)&&l>=1?l:null;continue}if(e!==null){if(i.startsWith(" ")){e+=1;continue}if(i.startsWith("+"))return e;if(i.startsWith("-"))return Math.max(1,e)}}return null};function Cn({effectiveDirectory:n,activeDiffStaged:s,git:e,files:i,setDiff:a,openContextFileAtLine:l}){const[f,d]=r.useState(null),y=r.useCallback(async(m,c)=>{if(!n||!m)return;d(m);const p=et();try{let F=null;if(c?.patch&&!c.isBinary&&!De(m)?F=Ze(c.patch):c&&c.contextMode==="full"&&!c.isBinary&&!De(m)&&(F=Ye(c.original,c.modified)),F===null)try{const h=await e.getGitDiff(n,{path:m,staged:s,contextLines:3});F=Ze(h.diff)}catch{F=null}let R=c;if(F===null||!R){const h=await e.getGitFileDiff(n,{path:m,staged:s});R={original:h.original??"",modified:h.modified??"",isBinary:h.isBinary},s||a(n,m,R,p??void 0)}const x=F??(R.isBinary||De(m)?1:Ye(R.original,R.modified)),C=bn(n,m),g=await Yt(i,C,{directory:n});if(!g.ok){it.error(Jt(g.reason));return}l(n,C,x,1)}finally{d(F=>F===m?null:F)}},[s,n,i,e,l,a]);return{openingEditorFilePath:f,openFileInEditorAtChange:y}}function Sn(n){const{hideStackedFileSidebar:s=!1,stackedDefaultCollapsedAll:e=!1,pinSelectedFileHeaderToTopOnNavigate:i=!1,diffScope:a="all",branchBase:l=null,branchHead:f=null,targetFilePath:d=null}=n,{git:y,files:m}=st(),c=It(),{screenWidth:p,isMobile:F}=Pt(),R=$t(c??null),x=Wt(c??null),C=_t(c??null),g=ce(o=>o.setActiveDirectory),h=ce(o=>o.ensureStatus),H=ce(o=>o.fetchStatus),M=ce(o=>o.clearDiffCache),E=ce(o=>o.setDiff),[S,_]=r.useState(null),[j,w]=r.useState(!1),[L,D]=r.useState(()=>new Set),[A,k]=r.useState(()=>new Set),[I,B]=r.useState(!1),[$,ee]=r.useState(0),[ue,Ne]=r.useState(()=>new Map),[b,se]=r.useState(a);r.useEffect(()=>{se(a)},[a]);const U=Y(o=>o.pendingDiffFile),ie=Y(o=>o.pendingDiffStaged),K=Y(o=>o.pendingDiffScope),J=Y(o=>o.setPendingDiffFile),O=Y(o=>o.diffLayoutPreference),re=Y(o=>o.diffFileLayout),q=Y(o=>o.setDiffFileLayout),he=Y(o=>o.diffWrapLinesOverride),de=Y(o=>o.wrapLinesByDefault),me=Y(o=>o.setDiffWrapLines),ge=Y(o=>o.openContextFileAtLine),oe=Bt(o=>o.currentSessionId),Ce=Ot(oe??""),u=he??de,te=(b==="staged"?!0:b==="working"?!1:null)??j,xe=F||p<=768,be=!s&&!xe&&p>=1024,ae=r.useRef(null),{branchDiffs:le,branchDiffError:V,branchDiffLoading:X,lastTurnDiffs:Z,lastTurnDiffData:Q,branchDiffData:ke}=vn({activeDiffScope:b,effectiveDirectory:c,branchBase:l,branchHead:f,git:y,sessionMessageRecords:Ce}),z=r.useMemo(()=>{if(b==="turn"||b==="branch")return(b==="branch"?le:Z).map(T=>({path:T.file??"",index:"",working_dir:Fn(T.status),insertions:T.additions??0,deletions:T.deletions??0,isNew:T.status==="added"})).filter(T=>T.path).sort((T,G)=>T.path.localeCompare(G.path));if(!x?.files)return[];const o=x.diffStats??{},N=b==="staged"?He:b==="working"?Ue:()=>!0;return x.files.filter(N).map(v=>({...v,insertions:o[v.path]?.insertions??0,deletions:o[v.path]?.deletions??0,isNew:Kt(v)})).sort((v,T)=>v.path.localeCompare(T.path))},[b,le,Z,x]),Ae=r.useMemo(()=>x?.files?x.files.filter(Ue).length:0,[x]),ct=r.useMemo(()=>x?.files?x.files.filter(He).length:0,[x]),ut=Z.length,dt=x?.files?.length??0,ft=le.length,{diffScrollRef:pt,pinnedStackedTarget:ht,pendingScrollTargetRef:ye,shouldPinAfterAlignRef:we,pendingScrollAnchorRestoreRef:We,lastScrollAnchorRef:_e,captureScrollAnchor:Be,cancelPendingScrollAlignment:Fe,queueVisibleStackedFilesSync:Re,registerSectionRef:mt,scrollToFile:Oe}=Nn({pinSelectedFileHeaderToTopOnNavigate:i,scrollRequestNonce:$,changedFiles:z,expandedFiles:L,setMountedStackedFiles:k,fileDiffRefreshNonce:ue}),ve=r.useCallback(o=>{D(N=>{if(N.has(o))return N;const v=new Set(N);return v.add(o),v})},[]),Te=r.useMemo(()=>z.map(o=>o.path).join("\0"),[z]);r.useEffect(()=>{const o=Te?Te.split("\0"):[],N=new Set(o),v=`${c??""}:${b}:${e?"collapsed":"default"}`,T=ae.current!==v;ae.current=v,D(G=>{if(T){const fe=e?0:xn(o.length);return new Set(o.slice(0,fe))}let Se=!1;const Le=new Set;for(const fe of G){if(!N.has(fe)){Se=!0;continue}Le.add(fe)}return Se?Le:G}),k(G=>{if(T)return new Set;let Se=!1;const Le=new Set;for(const fe of G){if(!N.has(fe)){Se=!0;continue}Le.add(fe)}return Se?Le:G})},[b,Te,c,k,e]);const Me=r.useCallback(o=>{const N=re[o.path];if(N)return N;if(O==="inline")return"inline";if(O==="side-by-side")return"side-by-side";const v=p<gn;return o.isNew||v?"inline":"side-by-side"},[re,O,p]),gt=r.useMemo(()=>z.length===0?null:z.every(o=>Me(o)==="side-by-side")?"side-by-side":"inline",[z,Me]);r.useEffect(()=>{c&&(g(c),h(c,y))},[c,g,h,y]),r.useEffect(()=>{if(c)return zt.onGitRefreshHint(o=>{ze(o.directory)===ze(c)&&(o.paths?.length&&(We.current=Be()??_e.current,M(c,o.paths),Ne(N=>{const v=new Map(N);for(const T of o.paths??[])v.set(T,(v.get(T)??0)+1);return v})),H(c,y,{silent:!0}))})},[Be,M,c,H,y,_e,We]),r.useEffect(()=>{b!=="all"&&!K||U&&(K&&se(K),_(U),w(K==="staged"||!K&&ie),J(null),we.current=!0,ye.current=U,ve(U),ee(o=>o+1))},[b,ve,U,K,ie,ye,J,we]),r.useEffect(()=>{if(b==="all")return;const o=d?.trim();o&&(_(o),w(b==="staged"),we.current=!0,ye.current=o,ve(o),ee(N=>N+1))},[b,ve,ye,we,d]),r.useEffect(()=>{if(!S)return;z.some(N=>N.path===S)||(_(null),w(!1))},[z,S]);const xt=r.useCallback((o,N)=>{Fe(),D(v=>{const T=v.has(o);if(N===T)return v;const G=new Set(v);return N?G.add(o):G.delete(o),G}),k(v=>{const T=v.has(o);if(N===T)return v;const G=new Set(v);return N?G.add(o):G.delete(o),G}),Re()},[Fe,Re,k]),bt=r.useCallback(()=>{Fe(),D(o=>o.size>0?new Set:new Set(z.map(N=>N.path))),k(new Set),Re()},[Fe,z,Re,k]),yt=r.useCallback(o=>{},[]),wt=r.useCallback(o=>{Fe(),_(o),w(!1),we.current=!0,ye.current=o,ve(o),ee(N=>N+1),Oe(o)},[Fe,ve,ye,Oe,we]),Ft=r.useCallback(o=>{const N=o==="side-by-side"?"side-by-side":"inline";z.forEach(v=>{q(v.path,N)})},[z,q]),{openingEditorFilePath:vt,openFileInEditorAtChange:jt}=Cn({effectiveDirectory:c,activeDiffStaged:te,git:y,files:m,setDiff:E,openContextFileAtLine:ge});return{git:y,files:m,effectiveDirectory:c,screenWidth:p,isMobile:F,isGitRepo:R,status:x,isLoadingStatus:C,activeDiffScope:b,setActiveDiffScope:se,branchDiffs:le,branchDiffError:V,branchDiffLoading:X,diffWrapLines:u,setDiffWrapLines:me,displayFileStaged:j,displayFile:S,pinnedStackedTarget:ht,expandedFiles:L,mountedStackedFiles:A,loadFullFiles:I,setLoadFullFiles:B,fileDiffRefreshNonce:ue,showFileSidebar:be,diffScrollRef:pt,lastTurnDiffData:Q,branchDiffData:ke,changedFiles:z,workingFileCount:Ae,stagedFileCount:ct,turnFileCount:ut,allFileCount:dt,branchFileCount:ft,currentLayoutForAllFiles:gt,openingEditorFilePath:vt,registerSectionRef:mt,handleStackedEntryExpandedChange:xt,handleExpandOrCollapseAll:bt,handleSelectFile:yt,handleSelectFileAndScroll:wt,handleHeaderLayoutChange:Ft,openFileInEditorAtChange:jt,getLayoutForFile:Me}}const Ns=({hideStackedFileSidebar:n=!1,stackedDefaultCollapsedAll:s=!1,pinSelectedFileHeaderToTopOnNavigate:e=!1,showOpenInEditorAction:i=!1,diffScope:a="all",onDiffScopeChange:l,branchBase:f=null,branchHead:d=null,targetFilePath:y=null,flushContent:m=!1,hideToolbar:c=!1,onHeaderControlsStateChange:p,toolbarSlot:F=null})=>{const{effectiveDirectory:R,isGitRepo:x,status:C,isLoadingStatus:g,activeDiffScope:h,setActiveDiffScope:H,branchDiffError:M,branchDiffLoading:E,diffWrapLines:S,setDiffWrapLines:_,displayFileStaged:j,displayFile:w,pinnedStackedTarget:L,expandedFiles:D,mountedStackedFiles:A,loadFullFiles:k,setLoadFullFiles:I,fileDiffRefreshNonce:B,showFileSidebar:$,diffScrollRef:ee,lastTurnDiffData:ue,branchDiffData:Ne,changedFiles:b,workingFileCount:se,stagedFileCount:U,turnFileCount:ie,allFileCount:K,branchFileCount:J,currentLayoutForAllFiles:O,openingEditorFilePath:re,registerSectionRef:q,handleStackedEntryExpandedChange:he,handleExpandOrCollapseAll:de,handleSelectFile:me,handleSelectFileAndScroll:ge,handleHeaderLayoutChange:oe,openFileInEditorAtChange:Ce,getLayoutForFile:u}=Sn({hideStackedFileSidebar:n,stackedDefaultCollapsedAll:s,pinSelectedFileHeaderToTopOnNavigate:e,diffScope:a,branchBase:f,branchHead:d,targetFilePath:y});r.useEffect(()=>{c&&l?.(h)},[h,c,l]);const P=r.useCallback(()=>{I(Z=>!Z)},[I]),te=r.useCallback(()=>{_(!S)},[S,_]),xe=r.useCallback(()=>{oe(O==="side-by-side"?"unified":"side-by-side")},[O,oe]),be=D.size,ae=r.useMemo(()=>({turnCount:ie,branchCount:J,expandedCount:be,totalCount:b.length,loadFullFiles:k,wrapLines:S,layoutMode:O,onExpandOrCollapseAll:de,onToggleLoadFullFiles:P,onToggleWrapLines:te,onToggleLayout:xe}),[ie,J,be,b.length,k,S,O,de,P,te,xe]);r.useEffect(()=>{c&&p?.(ae)},[c,ae,p]);const le=()=>{if(!R)return null;const Z={path:w,staged:j};return t.jsxs("div",{className:ne("flex min-w-0 flex-1 min-h-0 h-full",m?"gap-0":"gap-3 px-3 pb-3 pt-2"),children:[$&&t.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[t.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:b.length})]}),t.jsx(an,{changedFiles:b,selectedFile:null,onSelectFile:ge})]}),t.jsx("div",{className:"relative flex-1 min-w-0 min-h-0 h-full",children:t.jsxs(tt,{ref:ee,outerClassName:"min-h-0 h-full",className:"[overflow-anchor:none]",disableHorizontal:!0,observeMutations:!1,preventOverscroll:!0,"data-diff-virtual-root":!0,children:[t.jsx("div",{className:"flex flex-col [overflow-anchor:none]","data-diff-virtual-content":!0,children:b.map(Q=>{const ke=ln(h,Q,Z);return t.jsx(mn,{directory:R,file:Q,layout:u(Q),wrapLines:S,isSelected:!1,isExpanded:D.has(Q.path),isMounted:A.has(Q.path)||Q.path===L,onSelect:me,onExpandedChange:he,registerSectionRef:q,showOpenInEditorAction:i&&h!=="turn"&&h!=="branch",isOpeningInEditor:re===Q.path,onOpenInEditor:(z,Ae)=>{Ce(z,Ae)},diffSource:ke.source,staged:ke.staged,showFileActions:h!=="turn"&&h!=="branch",loadFullFiles:k,initialDiffData:h==="turn"?ue.get(Q.path)??null:h==="branch"?Ne.get(Q.path)??null:null},`${Q.path}:${B.get(Q.path)??0}`)})}),t.jsx("div",{"aria-hidden":"true",className:"h-16 shrink-0"})]})})]})},V=()=>R?h!=="turn"&&g&&!C?t.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[t.jsx(W,{name:"loader-4",className:"size-4 animate-spin"}),"Loading repository status..."]}):h!=="turn"&&h!=="branch"&&x===!1?t.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):h==="branch"&&E?t.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[t.jsx(W,{name:"loader-4",className:"size-4 animate-spin"}),"Loading branch changes..."]}):h==="branch"&&M?t.jsx("div",{className:"flex flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground",children:`Failed to load branch changes: ${M}`}):b.length===0?t.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:h==="turn"?"No last turn changes to display":"Working tree clean, no changes to display"}):le():t.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"}),X=t.jsxs("div",{className:F?"flex min-w-0 flex-1 items-center gap-1.5":"@container/diff-toolbar flex min-w-0 items-center gap-2 px-3 py-2 bg-background",children:[(x!==!1||h==="turn")&&(h==="all"||h==="working"||h==="staged"||h==="turn"||h==="branch")?t.jsx(qt,{scope:h,isGitRepo:x,branchAvailable:!!(f&&d),allCount:K,workingCount:se,stagedCount:U,turnCount:ie,branchCount:J,onScopeChange:Z=>{H(Z),l?.(Z)}}):t.jsx("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:t.jsx("span",{className:"typography-ui-label font-medium text-foreground",children:g&&!C?"Loading changes...":b.length===1?`${b.length} file changed`:`${b.length} files changed`})}),b.length>0&&t.jsxs(je,{variant:"ghost",size:"sm",onClick:de,className:ne("diff-toolbar__expand-button h-7 flex-shrink-0 gap-1 px-1.5 text-muted-foreground hover:text-foreground","ml-auto"),title:D.size>0?"Collapse all":"Expand all",children:[t.jsx(W,{name:"expand-up-down",className:"size-4"}),t.jsx("span",{className:"diff-toolbar__expand-label typography-ui-label",children:D.size>0?"Collapse all":"Expand all"})]}),b.length>0&&h!=="turn"&&h!=="branch"&&t.jsxs(Gt,{children:[t.jsx(Ht,{asChild:!0,children:t.jsx(je,{variant:"ghost",size:"sm",onClick:()=>I(Z=>!Z),"aria-pressed":k,"aria-label":k?"Unload full files":"Load full files",className:ne("h-7 w-7 flex-shrink-0 p-0 text-muted-foreground hover:text-foreground",k&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(W,{name:"file-download",className:"size-4"})})}),t.jsx(Ut,{children:t.jsx("p",{children:k?"Unload full files":"Load full files"})})]}),b.length>0&&t.jsx(je,{variant:"ghost",size:"sm",onClick:()=>_(!S),className:ne("h-5 w-5 p-0 transition-opacity",S?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:S?"Disable line wrap":"Enable line wrap",children:t.jsx(W,{name:"text-wrap",className:"size-4"})}),O&&t.jsx(rt,{mode:O==="side-by-side"?"side-by-side":"unified",onModeChange:oe})]});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[F?Nt.createPortal(X,F):c?null:X,V()]})};export{Ns as DiffView};