@kabmo-labs/kabmo 0.9.0 → 0.10.0

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 (180) hide show
  1. package/README.md +45 -0
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +333 -333
  4. package/dist/client/static/js/index-18xe7655.css +1 -0
  5. package/dist/client/static/js/{index-bpptfkz2.js → index-nxpe7835.js} +768 -763
  6. package/package.json +3 -1
  7. package/src/client/components/common/code-surface/bracket-guide.test.ts +249 -0
  8. package/src/client/components/common/code-surface/bracket-guide.ts +131 -0
  9. package/src/client/components/common/code-surface/documents.test.ts +5 -3
  10. package/src/client/components/common/code-surface/documents.ts +85 -0
  11. package/src/client/components/common/code-surface/extensions.test.ts +5 -0
  12. package/src/client/components/common/code-surface/extensions.ts +140 -7
  13. package/src/client/components/common/code-surface/fold-stack.test.ts +218 -0
  14. package/src/client/components/common/code-surface/fold.test.ts +148 -0
  15. package/src/client/components/common/code-surface/fold.ts +118 -0
  16. package/src/client/components/common/code-surface/indent-guide.ts +104 -0
  17. package/src/client/components/common/code-surface/indent.test.ts +239 -0
  18. package/src/client/components/common/code-surface/indent.ts +124 -0
  19. package/src/client/components/common/code-surface/index.tsx +76 -46
  20. package/src/client/components/common/code-surface/keymap.ts +12 -23
  21. package/src/client/components/common/code-surface/line-commands.test.ts +90 -0
  22. package/src/client/components/common/code-surface/line-commands.ts +103 -0
  23. package/src/client/components/common/code-surface/props.ts +87 -0
  24. package/src/client/components/common/code-surface/stream-language.test.ts +118 -0
  25. package/src/client/components/common/code-surface/stream-language.ts +123 -0
  26. package/src/client/components/common/code-surface/theme.test.ts +40 -5
  27. package/src/client/components/common/code-surface/theme.ts +113 -0
  28. package/src/client/components/common/code-surface/typing.test.ts +97 -0
  29. package/src/client/components/common/code-surface/typing.ts +111 -0
  30. package/src/client/components/common/toolbar-row/index.test.tsx +53 -4
  31. package/src/client/components/common/toolbar-row/index.tsx +101 -30
  32. package/src/client/components/layout/desktop-layout/WorkspacePanels.tsx +17 -0
  33. package/src/client/components/layout/desktop-layout/index.tsx +18 -0
  34. package/src/client/components/mobile/mobile-right-sidebar/FullEditor.tsx +35 -33
  35. package/src/client/components/mobile/mobile-right-sidebar/Header.tsx +20 -1
  36. package/src/client/components/mobile/mobile-right-sidebar/editor-props.ts +25 -0
  37. package/src/client/components/settings/categories/AppearanceSettings.tsx +6 -0
  38. package/src/client/components/settings/categories/appearance-settings/EditorIndentSection.tsx +87 -0
  39. package/src/client/components/settings/categories/appearance-settings/EditorTypingSection.tsx +99 -0
  40. package/src/client/components/workspace/chat-timeline/chat-input/expansion.ts +9 -4
  41. package/src/client/components/workspace/chat-timeline/chat-input/index.tsx +15 -11
  42. package/src/client/components/workspace/chat-timeline/chat-input/stretch-send.test.tsx +165 -0
  43. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.test.ts +17 -3
  44. package/src/client/components/workspace/chat-timeline/tool-renderers/shared/DiffView.tsx +10 -6
  45. package/src/client/components/workspace/editor/Body.tsx +24 -0
  46. package/src/client/components/workspace/editor/CommandPalette.tsx +4 -4
  47. package/src/client/components/workspace/editor/ConflictStrip.tsx +77 -0
  48. package/src/client/components/workspace/editor/Dialogs.tsx +53 -0
  49. package/src/client/components/workspace/editor/EmptyEditor.tsx +23 -0
  50. package/src/client/components/workspace/editor/ExternalChangeStrip.tsx +61 -0
  51. package/src/client/components/workspace/editor/FileDocument.tsx +89 -1
  52. package/src/client/components/workspace/editor/FilePane.tsx +43 -0
  53. package/src/client/components/workspace/editor/FindWidget.test.ts +9 -5
  54. package/src/client/components/workspace/editor/FindWidget.tsx +29 -0
  55. package/src/client/components/workspace/editor/GoToLineModal.tsx +123 -0
  56. package/src/client/components/workspace/editor/Notices.tsx +71 -0
  57. package/src/client/components/workspace/editor/Pane.tsx +118 -0
  58. package/src/client/components/workspace/editor/PluginColumn.tsx +32 -0
  59. package/src/client/components/workspace/editor/QuickOpenModal.tsx +146 -0
  60. package/src/client/components/workspace/editor/SaveAsModal.tsx +175 -0
  61. package/src/client/components/workspace/editor/SplitColumn.tsx +98 -0
  62. package/src/client/components/workspace/editor/SplitPane.tsx +57 -0
  63. package/src/client/components/workspace/editor/StatusBar.tsx +106 -0
  64. package/src/client/components/workspace/editor/TabContextMenu.tsx +75 -0
  65. package/src/client/components/workspace/editor/Tabs.tsx +195 -18
  66. package/src/client/components/workspace/editor/Toolbar.tsx +54 -181
  67. package/src/client/components/workspace/editor/index.tsx +199 -189
  68. package/src/client/components/workspace/editor/props.ts +64 -0
  69. package/src/client/components/workspace/editor/toolbar-clusters.tsx +300 -0
  70. package/src/client/components/workspace/file-explorer/Modals.tsx +14 -1
  71. package/src/client/components/workspace/file-explorer/TreeItem.tsx +2 -1
  72. package/src/client/components/workspace/file-explorer/clipboard.test.ts +3 -1
  73. package/src/client/components/workspace/file-explorer/index.test.ts +61 -0
  74. package/src/client/components/workspace/file-explorer/index.tsx +10 -48
  75. package/src/client/components/workspace/file-explorer/local-edit.test.ts +8 -3
  76. package/src/client/components/workspace/search-panel/Body.tsx +6 -1
  77. package/src/client/hooks/chat/composer/file-drop.ts +22 -37
  78. package/src/client/hooks/chat/composer/pipeline.test.ts +76 -0
  79. package/src/client/hooks/chat/composer/pipeline.ts +12 -1
  80. package/src/client/hooks/editor/caret-position.test.ts +58 -0
  81. package/src/client/hooks/editor/caret-position.ts +48 -0
  82. package/src/client/hooks/editor/file-editor-types.ts +200 -0
  83. package/src/client/hooks/editor/find-history.test.ts +132 -0
  84. package/src/client/hooks/editor/find-history.ts +46 -0
  85. package/src/client/hooks/editor/find-selection-range.test.ts +100 -0
  86. package/src/client/hooks/editor/find-selection-range.ts +49 -0
  87. package/src/client/hooks/editor/find-state.ts +13 -0
  88. package/src/client/hooks/editor/font.test.ts +0 -93
  89. package/src/client/hooks/editor/indent-settings.test.ts +104 -0
  90. package/src/client/hooks/editor/indent-settings.ts +88 -0
  91. package/src/client/hooks/editor/quick-open.test.ts +141 -0
  92. package/src/client/hooks/editor/quick-open.ts +127 -0
  93. package/src/client/hooks/editor/save-as.test.ts +156 -0
  94. package/src/client/hooks/editor/save-as.ts +122 -0
  95. package/src/client/hooks/editor/save-file.test.ts +179 -0
  96. package/src/client/hooks/editor/save-file.ts +73 -28
  97. package/src/client/hooks/editor/typing-settings.test.ts +73 -0
  98. package/src/client/hooks/editor/typing-settings.ts +65 -0
  99. package/src/client/hooks/editor/use-close-guard.ts +98 -0
  100. package/src/client/hooks/editor/use-editor-drop-overlay.test.ts +159 -0
  101. package/src/client/hooks/editor/use-editor-drop.shell.test.ts +224 -0
  102. package/src/client/hooks/editor/use-editor-drop.ts +58 -68
  103. package/src/client/hooks/editor/use-editor-find.test.ts +2 -2
  104. package/src/client/hooks/editor/use-editor-find.ts +38 -3
  105. package/src/client/hooks/editor/use-editor-panel-keys.ts +152 -0
  106. package/src/client/hooks/editor/use-editor-tab-state.ts +71 -0
  107. package/src/client/hooks/editor/use-external-change-notice.ts +71 -0
  108. package/src/client/hooks/editor/use-external-change.test.ts +88 -0
  109. package/src/client/hooks/editor/use-external-change.ts +146 -0
  110. package/src/client/hooks/editor/use-file-editor.ts +83 -116
  111. package/src/client/hooks/editor/use-file-read.ts +16 -8
  112. package/src/client/hooks/editor/use-file-writes.ts +28 -3
  113. package/src/client/hooks/editor/use-mobile-editor-find.ts +69 -0
  114. package/src/client/hooks/editor/use-mobile-reveal.ts +53 -0
  115. package/src/client/hooks/editor/use-search-reveal-jump.ts +57 -0
  116. package/src/client/hooks/editor/use-split-editor.test.tsx +169 -0
  117. package/src/client/hooks/editor/use-split-editor.ts +91 -0
  118. package/src/client/hooks/editor/use-unload-guard.tsx +117 -0
  119. package/src/client/hooks/editor/use-write-conflict.test.ts +164 -0
  120. package/src/client/hooks/editor/use-write-conflict.ts +152 -0
  121. package/src/client/hooks/editor/wheel-zoom.test.ts +141 -0
  122. package/src/client/hooks/editor/wheel-zoom.ts +96 -0
  123. package/src/client/hooks/ui/drag-presence.test.ts +193 -0
  124. package/src/client/hooks/ui/drag-presence.ts +108 -0
  125. package/src/client/hooks/ui/settings-modal.test.ts +115 -0
  126. package/src/client/hooks/workspace/file-listing.ts +36 -24
  127. package/src/client/hooks/workspace/file-tabs.test.ts +90 -0
  128. package/src/client/hooks/workspace/file-tabs.ts +46 -0
  129. package/src/client/hooks/workspace/file-tree-edits.ts +103 -0
  130. package/src/client/lib/desktop/dropped-paths.ts +83 -0
  131. package/src/client/lib/editor/tab-menu.test.ts +127 -0
  132. package/src/client/lib/editor/tab-menu.ts +127 -0
  133. package/src/client/lib/editor-dirty-tabs.test.ts +102 -0
  134. package/src/client/lib/editor-dirty-tabs.ts +103 -0
  135. package/src/client/lib/native/resume.test.ts +66 -0
  136. package/src/client/lib/native/resume.ts +42 -0
  137. package/src/client/main.tsx +8 -0
  138. package/src/client/tailwind.css +38 -0
  139. package/src/server/lib/bundler/css.test.ts +31 -0
  140. package/src/server/lib/fs/listing.test.ts +81 -16
  141. package/src/server/lib/fs/listing.ts +72 -5
  142. package/src/server/lib/fs/write-conflict.test.ts +68 -0
  143. package/src/server/lib/fs/write-conflict.ts +84 -0
  144. package/src/server/routes/fs/action-save-as.test.ts +82 -0
  145. package/src/server/routes/fs/action.test.ts +82 -0
  146. package/src/server/routes/fs/action.ts +54 -1
  147. package/src/server/routes/fs/exists.ts +11 -1
  148. package/src/server/routes/fs/read.ts +6 -1
  149. package/src/shared/lib/code/editor/find-replace.test.ts +1 -1
  150. package/src/shared/lib/code/editor/find-scan.test.ts +1 -1
  151. package/src/shared/lib/code/editor/find-scan.ts +22 -1
  152. package/src/shared/lib/code/editor/find-selection.test.ts +56 -0
  153. package/src/shared/lib/code/editor/indent-guide-rule.test.ts +65 -0
  154. package/src/shared/lib/code/editor/indent-guide-rule.ts +47 -0
  155. package/src/shared/lib/code/editor/indent-rules.test.ts +219 -0
  156. package/src/shared/lib/code/editor/indent-rules.ts +198 -0
  157. package/src/shared/lib/code/editor/keymap.test.ts +23 -0
  158. package/src/shared/lib/code/editor/keymap.ts +40 -3
  159. package/src/shared/lib/code/editor/palette.test.ts +25 -2
  160. package/src/shared/lib/code/editor/palette.ts +10 -0
  161. package/src/shared/lib/code/editor/stream-modes.ts +225 -0
  162. package/src/shared/lib/code/syntax-highlight.test.ts +1 -1
  163. package/src/shared/lib/fs/file-tree.test.ts +41 -0
  164. package/src/shared/lib/fs/file-tree.ts +126 -34
  165. package/src/shared/lib/fs/folder-chain.test.ts +87 -0
  166. package/src/shared/lib/fs/folder-chain.ts +91 -0
  167. package/src/shared/lib/fs/fs-helpers.test.ts +4 -50
  168. package/src/shared/lib/realtime/connection.test.ts +5 -1
  169. package/src/shared/lib/realtime/connection.ts +25 -119
  170. package/src/shared/lib/realtime/frozen-recovery.test.ts +93 -0
  171. package/src/shared/lib/realtime/resume.ts +223 -0
  172. package/src/shared/lib/realtime/state.ts +22 -0
  173. package/src/shared/lib/realtime/watchdog-wiring.test.ts +224 -0
  174. package/src/shared/lib/realtime/watchdog.test.ts +99 -0
  175. package/src/shared/lib/realtime/watchdog.ts +72 -0
  176. package/src/shared/lib/workspace/split-editor.test.ts +104 -0
  177. package/src/shared/lib/workspace/split-editor.ts +129 -0
  178. package/src/test-support/file-explorer-disk.test-util.ts +30 -3
  179. package/src/test-support/pristine-globals.ts +7 -0
  180. package/dist/client/static/js/index-k315p1e8.css +0 -1
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The watchdog's WIRING, driven through the interval the client really runs.
8
+ *
9
+ * The DECISION (freeze versus silence versus throttling) is pinned in
10
+ * `watchdog.test.ts`, where a timing rule can be asserted without a clock. What
11
+ * is left here is that the interval exists, that it reaches the client's own
12
+ * probe and re-dial paths, and that its clocks come from the socket's real
13
+ * traffic — the parts a pure function cannot cover.
14
+ *
15
+ * The reported failure these exist for: a backgrounded Android WebView fires no
16
+ * `visibilitychange` on return, and a socket the server's 30s heartbeat reaped
17
+ * while the page was frozen produces no `close` — `readyState` still says OPEN.
18
+ * The channel sat on a corpse with no frames, the stream frozen mid-answer, and
19
+ * only a page reload repaired it.
20
+ *
21
+ * Driven through the PUBLIC client (`subscribe`), so the wiring under test is
22
+ * the one production uses; the socket is a double only because these cases are
23
+ * about what the client does with a socket that stops answering.
24
+ */
25
+
26
+ import { afterEach, beforeEach, describe, expect, test, vi } from 'bun:test';
27
+ import { Window } from 'happy-dom';
28
+
29
+ import { realtimeClient, resetRealtimeClient } from '@/shared/lib/realtime/client';
30
+ import { currentStatus, state } from '@/shared/lib/realtime/state';
31
+ import { IDLE_PROBE_AFTER_MS } from '@/shared/lib/realtime/watchdog';
32
+ import { installDomGlobals, restoreDomGlobals } from '@/test-support/pristine-globals';
33
+
34
+ /** A socket whose answer the case decides, and whose frames are inspectable. */
35
+ class FakeSocket {
36
+ static instances: FakeSocket[] = [];
37
+ readyState = 0;
38
+ sent: string[] = [];
39
+ onopen: (() => void) | null = null;
40
+ onclose: (() => void) | null = null;
41
+ onmessage: ((event: { data: string }) => void) | null = null;
42
+ onerror: (() => void) | null = null;
43
+
44
+ constructor(public url: string) {
45
+ FakeSocket.instances.push(this);
46
+ }
47
+
48
+ open(): void {
49
+ this.readyState = 1;
50
+ this.onopen?.();
51
+ }
52
+
53
+ /** The server reaped it while the page was frozen: the browser never learned. */
54
+ silentDeath(): void {
55
+ this.readyState = 1;
56
+ }
57
+
58
+ send(data: string): void {
59
+ this.sent.push(data);
60
+ }
61
+
62
+ close(): void {
63
+ if (this.readyState === 3) return;
64
+ this.readyState = 3;
65
+ this.onclose?.();
66
+ }
67
+
68
+ frames(): Array<Record<string, unknown>> {
69
+ return this.sent.map((raw) => JSON.parse(raw) as Record<string, unknown>);
70
+ }
71
+ }
72
+
73
+ const WAKE_PROBE_MS = 2_000;
74
+ const RETRY_AFTER_ESTABLISHED_DROP_MS = 500;
75
+
76
+ let win: Window;
77
+ let unsubscribe: (() => void) | null = null;
78
+
79
+ beforeEach(() => {
80
+ FakeSocket.instances = [];
81
+ // Start from NO connection. A suite that dialed a real socket and did not
82
+ // release it leaves `state().socket` set, and `dial()` then early-returns on
83
+ // it — no FakeSocket is ever constructed, so every case here fails on a
84
+ // missing instance rather than on the watchdog. File order is the runner's,
85
+ // so this file must not depend on another suite's teardown.
86
+ resetRealtimeClient();
87
+ win = new Window({ url: 'http://localhost' });
88
+ // `vi.useFakeTimers` patches the RUNNER's globals, while happy-dom captured
89
+ // its own bound copies when it was imported. Delegating at call time is what
90
+ // lets the watchdog's `window.setInterval` be driven deterministically.
91
+ win.setTimeout = ((fn: () => void, ms?: number) =>
92
+ globalThis.setTimeout(fn, ms)) as unknown as typeof win.setTimeout;
93
+ win.clearTimeout = ((id?: number) => globalThis.clearTimeout(id)) as unknown as typeof win.clearTimeout;
94
+ win.setInterval = ((fn: () => void, ms?: number) =>
95
+ globalThis.setInterval(fn, ms)) as unknown as typeof win.setInterval;
96
+ win.clearInterval = ((id?: number) => globalThis.clearInterval(id)) as unknown as typeof win.clearInterval;
97
+ installDomGlobals(win);
98
+ realtimeClient.setSocketConstructor(FakeSocket as unknown as typeof WebSocket);
99
+ vi.useFakeTimers();
100
+ });
101
+
102
+ afterEach(() => {
103
+ unsubscribe?.();
104
+ unsubscribe = null;
105
+ resetRealtimeClient();
106
+ vi.useRealTimers();
107
+ restoreDomGlobals();
108
+ });
109
+
110
+ function subscribe(): void {
111
+ unsubscribe = realtimeClient.subscribe('probe:topic', () => {});
112
+ }
113
+
114
+ function lastSocket(): FakeSocket {
115
+ return FakeSocket.instances[FakeSocket.instances.length - 1]!;
116
+ }
117
+
118
+ describe('the liveness watchdog', () => {
119
+ test('a silent open socket is probed without any resume event', () => {
120
+ subscribe();
121
+ const socket = lastSocket();
122
+ socket.open();
123
+ // No `visibilitychange`, no `pageshow`, no `online`: only time passing.
124
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS);
125
+
126
+ expect(socket.frames().filter((frame) => frame.t === 'ping')).toHaveLength(1);
127
+ expect(FakeSocket.instances).toHaveLength(1);
128
+ expect(currentStatus()).toBe('open');
129
+ });
130
+
131
+ test('a probe that is never answered replaces the socket', () => {
132
+ subscribe();
133
+ const socket = lastSocket();
134
+ socket.open();
135
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS);
136
+ expect(socket.frames().filter((frame) => frame.t === 'ping')).toHaveLength(1);
137
+
138
+ // No pong: the deadline abandons the socket and the retry path dials.
139
+ vi.advanceTimersByTime(WAKE_PROBE_MS);
140
+ vi.advanceTimersByTime(RETRY_AFTER_ESTABLISHED_DROP_MS);
141
+ expect(FakeSocket.instances).toHaveLength(2);
142
+ expect(lastSocket()).not.toBe(socket);
143
+ });
144
+
145
+ test('a probe that IS answered leaves the connection alone', () => {
146
+ subscribe();
147
+ const socket = lastSocket();
148
+ socket.open();
149
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS);
150
+ const ping = socket.frames().find((frame) => frame.t === 'ping') as { id: number };
151
+ socket.onmessage?.({ data: JSON.stringify({ t: 'pong', id: ping.id }) });
152
+
153
+ // The pong restarted the idle clock, so the next window is quiet again.
154
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS - WAKE_PROBE_MS);
155
+ expect(FakeSocket.instances).toHaveLength(1);
156
+ expect(currentStatus()).toBe('open');
157
+ });
158
+
159
+ test('real traffic keeps the socket out of the idle probe', () => {
160
+ subscribe();
161
+ const socket = lastSocket();
162
+ socket.open();
163
+ // A quiet-but-healthy connection: deltas and the server's own heartbeat keep
164
+ // the clock fresh, so the watchdog must never question it.
165
+ for (let elapsed = 0; elapsed < IDLE_PROBE_AFTER_MS * 2; elapsed += 5_000) {
166
+ socket.onmessage?.({ data: JSON.stringify({ t: 'pong', id: 999 }) });
167
+ vi.advanceTimersByTime(5_000);
168
+ }
169
+ expect(socket.frames().filter((frame) => frame.t === 'ping')).toHaveLength(0);
170
+ expect(FakeSocket.instances).toHaveLength(1);
171
+ });
172
+
173
+ test('the watchdog stops with the last subscription', () => {
174
+ subscribe();
175
+ const socket = lastSocket();
176
+ socket.open();
177
+ unsubscribe?.();
178
+ unsubscribe = null;
179
+
180
+ const before = FakeSocket.instances.length;
181
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS * 2);
182
+ expect(socket.frames().filter((frame) => frame.t === 'ping')).toHaveLength(0);
183
+ expect(FakeSocket.instances).toHaveLength(before);
184
+ });
185
+
186
+ test('a reset stops the watchdog', () => {
187
+ subscribe();
188
+ const socket = lastSocket();
189
+ socket.open();
190
+ resetRealtimeClient();
191
+
192
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS * 2);
193
+ expect(socket.frames().filter((frame) => frame.t === 'ping')).toHaveLength(0);
194
+ });
195
+
196
+ test('a probe armed before a freeze does not block every later probe', () => {
197
+ subscribe();
198
+ const socket = lastSocket();
199
+ socket.open();
200
+
201
+ // A probe is armed, then the page freezes before its own deadline can fire —
202
+ // and a frozen page freezes that deadline timer WITH it, so `probeId` stays
203
+ // set with nothing left to clear it. Both halves are written directly: fake
204
+ // timers fire the deadline on schedule, so advancing the clock cannot
205
+ // produce this state.
206
+ socket.silentDeath();
207
+ const host = state();
208
+ host.probeId = 99;
209
+ host.probeArmedAt = Date.now() - (WAKE_PROBE_MS + IDLE_PROBE_AFTER_MS);
210
+ clearTimeout(host.probeTimer);
211
+ host.probeTimer = undefined;
212
+
213
+ // The next watchdog probe must discard that stale arm rather than return
214
+ // early on it: an armed-but-unanswerable probe that blocks every later one is
215
+ // a socket that is never questioned, so nothing ever re-dials.
216
+ vi.advanceTimersByTime(IDLE_PROBE_AFTER_MS);
217
+ expect(socket.frames().filter((frame) => frame.t === 'ping')).toHaveLength(1);
218
+
219
+ // And this one DOES get its deadline, so the dead socket is replaced.
220
+ vi.advanceTimersByTime(WAKE_PROBE_MS);
221
+ vi.advanceTimersByTime(RETRY_AFTER_ESTABLISHED_DROP_MS);
222
+ expect(lastSocket()).not.toBe(socket);
223
+ });
224
+ });
@@ -0,0 +1,99 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The watchdog's decision, pinned directly.
8
+ *
9
+ * Every branch here answers a timing question, and a timing case driven through
10
+ * real timers is a test of the clock rather than of the rule. The driver that
11
+ * calls this is `resume.ts`; the interval it owns is covered separately in
12
+ * `connection.test.ts`, through the public client.
13
+ *
14
+ * The reported failure this exists for: an Android WebView that was backgrounded
15
+ * fires no `visibilitychange` on return, and a socket the server's 30s heartbeat
16
+ * reaped while the page was frozen produces no `close` — `readyState` still says
17
+ * OPEN. The channel sat on a corpse until a page reload.
18
+ */
19
+
20
+ import { describe, expect, test } from 'bun:test';
21
+
22
+ import {
23
+ FREEZE_DETECT_MS,
24
+ IDLE_PROBE_AFTER_MS,
25
+ LIVENESS_TICK_MS,
26
+ watchdogAction,
27
+ } from '@/shared/lib/realtime/watchdog';
28
+
29
+ /** A healthy tick: on schedule, traffic just arrived, page visible and open. */
30
+ const HEALTHY = {
31
+ sinceTick: LIVENESS_TICK_MS,
32
+ sinceInbound: LIVENESS_TICK_MS,
33
+ hidden: false,
34
+ open: true,
35
+ wanted: true,
36
+ } as const;
37
+
38
+ describe('watchdogAction', () => {
39
+ test('a healthy connection asks for nothing', () => {
40
+ expect(watchdogAction(HEALTHY)).toBeNull();
41
+ });
42
+
43
+ test('a late tick is a freeze, and waking beats probing', () => {
44
+ // The page was suspended: the clock moved, our interval did not. This is the
45
+ // only resume signal a backgrounded Android WebView leaves behind.
46
+ expect(watchdogAction({ ...HEALTHY, sinceTick: FREEZE_DETECT_MS + 1 })).toBe('wake');
47
+ // Even with the socket silent for longer still, waking is the stronger
48
+ // repair: it re-dials a socket that is gone, while a probe can only question
49
+ // one the browser still believes in.
50
+ expect(
51
+ watchdogAction({ ...HEALTHY, sinceTick: FREEZE_DETECT_MS + 1, sinceInbound: IDLE_PROBE_AFTER_MS * 4 }),
52
+ ).toBe('wake');
53
+ });
54
+
55
+ test('a late tick on a HIDDEN page is throttling, not a freeze', () => {
56
+ // A hidden tab is legitimately throttled to about a tick a minute. Reading
57
+ // that as a freeze would re-dial on every throttled tick for a page nobody is
58
+ // looking at.
59
+ expect(
60
+ watchdogAction({ ...HEALTHY, hidden: true, sinceTick: LIVENESS_TICK_MS * 20 }),
61
+ ).toBeNull();
62
+ });
63
+
64
+ test('silence on a visible open socket is probed', () => {
65
+ expect(watchdogAction({ ...HEALTHY, sinceInbound: IDLE_PROBE_AFTER_MS })).toBe('probe');
66
+ });
67
+
68
+ test('a probe fires below the server heartbeat, not after it', () => {
69
+ // The server reaps an unanswered connection at 30s. Probing later would only
70
+ // ever discover a connection already torn down.
71
+ expect(IDLE_PROBE_AFTER_MS).toBeLessThan(30_000);
72
+ expect(FREEZE_DETECT_MS).toBeGreaterThan(LIVENESS_TICK_MS);
73
+ });
74
+
75
+ test('silence on a hidden page is still probed', () => {
76
+ // Deliberately not gated on visibility: a connection that died while the
77
+ // user was in another app is repaired before they come back, rather than
78
+ // after. `wake` is what needs the page to be visible.
79
+ expect(
80
+ watchdogAction({ ...HEALTHY, hidden: true, sinceInbound: IDLE_PROBE_AFTER_MS + 1 }),
81
+ ).toBe('probe');
82
+ });
83
+
84
+ test('a closed socket is never probed', () => {
85
+ // `wake` owns the re-dial path; a probe has nothing to send on.
86
+ expect(watchdogAction({ ...HEALTHY, open: false, sinceInbound: IDLE_PROBE_AFTER_MS * 3 })).toBeNull();
87
+ });
88
+
89
+ test('nothing happens once every subscription is released', () => {
90
+ expect(
91
+ watchdogAction({ ...HEALTHY, wanted: false, sinceTick: FREEZE_DETECT_MS * 3, sinceInbound: IDLE_PROBE_AFTER_MS * 3 }),
92
+ ).toBeNull();
93
+ });
94
+
95
+ test('a tick one millisecond under either threshold is not enough', () => {
96
+ expect(watchdogAction({ ...HEALTHY, sinceTick: FREEZE_DETECT_MS })).toBeNull();
97
+ expect(watchdogAction({ ...HEALTHY, sinceInbound: IDLE_PROBE_AFTER_MS - 1 })).toBeNull();
98
+ });
99
+ });
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The watchdog's DECISION, separated from the interval that drives it.
8
+ *
9
+ * A pure function over two clocks, because the cases that matter are timing
10
+ * cases and a timing case tested through real timers is a test of the clock. The
11
+ * driver in `resume.ts` reads `Date.now()` and calls this; every branch below is
12
+ * pinned directly.
13
+ *
14
+ * Two facts it distinguishes, and neither is available from the browser:
15
+ *
16
+ * - **The page was FROZEN.** A tick that arrives far later than its deadline
17
+ * cannot be produced by a running interval, so the page was suspended — a
18
+ * backgrounded phone, a suspended tab. That is a resume, and the failure count
19
+ * from the frozen window is worthless.
20
+ * - **The socket is SILENT.** An OPEN socket with no inbound traffic for longer
21
+ * than the idle window is questioned, which catches a connection that died
22
+ * while the tab stayed visible (a Wi-Fi to cellular handoff).
23
+ *
24
+ * A HIDDEN document is neither: it is legitimately throttled to roughly a tick a
25
+ * minute, so every tick would read as a freeze. Freeze detection is therefore
26
+ * gated on a visible page, while the idle probe is not — that one also repairs a
27
+ * connection that died while the user was in another app, before they return.
28
+ */
29
+
30
+ /** How often the watchdog runs. */
31
+ export const LIVENESS_TICK_MS = 5_000;
32
+ /**
33
+ * A tick this much later than it was scheduled means the page was frozen: a
34
+ * running interval cannot skip its own deadline by this much.
35
+ */
36
+ export const FREEZE_DETECT_MS = LIVENESS_TICK_MS * 2;
37
+ /**
38
+ * Silence on an OPEN socket that justifies a probe. Below the server's 30s
39
+ * protocol heartbeat, so a connection the server is about to reap is checked
40
+ * before the reap rather than after it.
41
+ */
42
+ export const IDLE_PROBE_AFTER_MS = 25_000;
43
+
44
+ export interface WatchdogInput {
45
+ /** Milliseconds since the previous tick fired. */
46
+ sinceTick: number;
47
+ /** Milliseconds since anything last arrived on the open socket. */
48
+ sinceInbound: number;
49
+ /** Whether the document reports itself hidden. */
50
+ hidden: boolean;
51
+ /** Whether a socket is open right now (the probe is only meaningful then). */
52
+ open: boolean;
53
+ /** Whether anyone still wants the channel. */
54
+ wanted: boolean;
55
+ }
56
+
57
+ /**
58
+ * `'wake'` — treat the page as back (reset the budget, probe or re-dial);
59
+ * `'probe'` — question the open socket; `null` — nothing to do.
60
+ */
61
+ export type WatchdogAction = 'wake' | 'probe' | null;
62
+
63
+ export function watchdogAction(input: WatchdogInput): WatchdogAction {
64
+ if (!input.wanted) return null;
65
+ // Ordered: a freeze explains the silence too, and waking is the stronger
66
+ // repair — it re-dials when the socket is already gone, while a probe can only
67
+ // question one the browser still believes in.
68
+ if (input.sinceTick > FREEZE_DETECT_MS && !input.hidden) return 'wake';
69
+ if (!input.open) return null;
70
+ if (input.sinceInbound < IDLE_PROBE_AFTER_MS) return null;
71
+ return 'probe';
72
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The split editor's rules.
8
+ *
9
+ * Every one of them prevents a pane that cannot be used: a split onto the tab the left pane
10
+ * already shows is a wide pane with a divider through it; a persisted id for a tab that is
11
+ * gone opens onto an empty half-column the user has to discover how to dismiss; a divider
12
+ * dragged to either extreme deletes a pane by accident.
13
+ */
14
+
15
+ import { describe, expect, test } from 'bun:test';
16
+
17
+ import {
18
+ DEFAULT_SPLIT,
19
+ MAX_SPLIT_FRACTION,
20
+ MIN_SPLIT_FRACTION,
21
+ canSplitTo,
22
+ clampSplitFraction,
23
+ readSplitState,
24
+ splitAfterActivate,
25
+ } from '@/shared/lib/workspace/split-editor';
26
+
27
+ describe('canSplitTo', () => {
28
+ test('a second open tab can be the right pane', () => {
29
+ expect(canSplitTo('b.ts', 'a.ts', ['a.ts', 'b.ts'])).toBe(true);
30
+ });
31
+
32
+ test('the tab the left pane already shows is refused — one file twice is not a split', () => {
33
+ expect(canSplitTo('a.ts', 'a.ts', ['a.ts', 'b.ts'])).toBe(false);
34
+ });
35
+
36
+ test('a tab that is not open is refused', () => {
37
+ expect(canSplitTo('gone.ts', 'a.ts', ['a.ts'])).toBe(false);
38
+ });
39
+
40
+ test('null is refused, which is what closes the pane', () => {
41
+ expect(canSplitTo(null, 'a.ts', ['a.ts'])).toBe(false);
42
+ });
43
+ });
44
+
45
+ describe('splitAfterActivate', () => {
46
+ test('activating the tab the right pane shows collapses the split', () => {
47
+ const state = { rightFileId: 'b.ts', fraction: 0.5 };
48
+ expect(splitAfterActivate(state, 'b.ts')).toEqual({ rightFileId: null, fraction: 0.5 });
49
+ });
50
+
51
+ test('activating another tab leaves the split standing', () => {
52
+ const state = { rightFileId: 'b.ts', fraction: 0.5 };
53
+ expect(splitAfterActivate(state, 'c.ts')).toBe(state);
54
+ });
55
+
56
+ test('an unsplit column is untouched', () => {
57
+ expect(splitAfterActivate(DEFAULT_SPLIT, 'a.ts')).toBe(DEFAULT_SPLIT);
58
+ });
59
+ });
60
+
61
+ describe('clampSplitFraction', () => {
62
+ test('keeps a position inside the bounds', () => {
63
+ expect(clampSplitFraction(0.5)).toBe(0.5);
64
+ expect(clampSplitFraction(0.9)).toBe(MAX_SPLIT_FRACTION);
65
+ expect(clampSplitFraction(0.05)).toBe(MIN_SPLIT_FRACTION);
66
+ });
67
+
68
+ test('a non-finite value falls back to the default', () => {
69
+ expect(clampSplitFraction(Number.NaN)).toBe(DEFAULT_SPLIT.fraction);
70
+ expect(clampSplitFraction(Number.POSITIVE_INFINITY)).toBe(DEFAULT_SPLIT.fraction);
71
+ });
72
+ });
73
+
74
+ describe('readSplitState', () => {
75
+ test('a valid persisted state is restored', () => {
76
+ expect(readSplitState({ rightFileId: 'b.ts', fraction: 0.3 }, ['a.ts', 'b.ts'])).toEqual({
77
+ rightFileId: 'b.ts',
78
+ fraction: 0.3,
79
+ });
80
+ });
81
+
82
+ test('a right pane naming a tab that is gone is DROPPED, not trusted', () => {
83
+ // The split would otherwise open onto a pane that cannot render, and the only way out
84
+ // would be to close a pane nobody can see.
85
+ expect(readSplitState({ rightFileId: 'gone.ts', fraction: 0.3 }, ['a.ts'])).toEqual({
86
+ rightFileId: null,
87
+ fraction: 0.3,
88
+ });
89
+ });
90
+
91
+ test('the fraction survives even when the pane is dropped, so a later split keeps it', () => {
92
+ expect(readSplitState({ rightFileId: 'gone.ts', fraction: 0.7 }, []).fraction).toBe(0.7);
93
+ });
94
+
95
+ test('a malformed blob answers the default', () => {
96
+ expect(readSplitState(null, [])).toEqual(DEFAULT_SPLIT);
97
+ expect(readSplitState('nonsense', [])).toEqual(DEFAULT_SPLIT);
98
+ expect(readSplitState({}, [])).toEqual(DEFAULT_SPLIT);
99
+ });
100
+
101
+ test('an out-of-bounds fraction is clamped on read', () => {
102
+ expect(readSplitState({ rightFileId: 'a.ts', fraction: 0.99 }, ['a.ts']).fraction).toBe(MAX_SPLIT_FRACTION);
103
+ });
104
+ });
@@ -0,0 +1,129 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: Apache-2.0
4
+ */
5
+
6
+ /**
7
+ * The editor column's SECOND group: two documents side by side.
8
+ *
9
+ * ## Why this does not touch the panel-width model
10
+ *
11
+ * The plan called split editor the most expensive item because it "conflicts with the
12
+ * coupled editor/right-panel width model". It does not have to. The split lives INSIDE the
13
+ * editor panel: that panel keeps its own width (its fraction, its floor, its diff variant),
14
+ * and the two panes divide the space it already has. Nothing about `panel-widths.ts`
15
+ * changes — no new slot, no second pair, no re-derivation of the 0.7 pair cap — because
16
+ * splitting a column is not the same decision as how wide the column is.
17
+ *
18
+ * ## The two panes are TABS, not a second document list
19
+ *
20
+ * The left pane is the active tab; the right pane is another tab the user picked. That is
21
+ * what keeps ONE tab list authoritative: a second list would need its own ordering, its own
22
+ * close semantics and its own persisted state, and the two could disagree about which file
23
+ * is open. Picking the same tab twice is refused (a pane showing its twin is a wide pane
24
+ * with a divider through it).
25
+ *
26
+ * ## A closed pane's tab is NOT closed
27
+ *
28
+ * Splitting is a view, so closing the right pane leaves the tab open in the strip. The
29
+ * reverse also holds: closing the tab that a pane shows collapses the split, because a pane
30
+ * naming a tab that is gone has nothing to draw.
31
+ */
32
+
33
+ /** The split's state, persisted per session beside the rest of the layout. */
34
+ export interface SplitEditorState {
35
+ /** The tab shown in the RIGHT pane, or null when the column is not split. */
36
+ rightFileId: number | string | null;
37
+ /**
38
+ * The divider's position as a share of the editor panel's width, 0–1.
39
+ *
40
+ * A fraction rather than pixels for the same reason the panel widths are: a pixel value
41
+ * is only right on the display it was dragged on.
42
+ */
43
+ fraction: number;
44
+ }
45
+
46
+ export const DEFAULT_SPLIT: SplitEditorState = { rightFileId: null, fraction: 0.5 };
47
+
48
+ /** Bounds on the divider, so neither pane can be squeezed out of existence. */
49
+ export const MIN_SPLIT_FRACTION = 0.2;
50
+ export const MAX_SPLIT_FRACTION = 0.8;
51
+
52
+ /**
53
+ * Split with `rightFileId`, or refuse when it cannot be shown.
54
+ *
55
+ * Refused cases, each of which would otherwise draw an empty or duplicated pane: the id
56
+ * names the tab the LEFT pane already shows, or the id names no open tab (a stale persisted
57
+ * value after a reload).
58
+ */
59
+ export function canSplitTo(
60
+ rightFileId: number | string | null,
61
+ activeFileId: number | string | null,
62
+ openIds: readonly (number | string)[],
63
+ ): boolean {
64
+ if (rightFileId === null) return false;
65
+ if (rightFileId === activeFileId) return false;
66
+ return openIds.includes(rightFileId);
67
+ }
68
+
69
+ /**
70
+ * The tab a bare "split" gesture should put in the right pane: the most recently opened tab
71
+ * that is not the left pane's own.
72
+ *
73
+ * A menu row can name its tab, but a BUTTON cannot — and the button has to exist, because
74
+ * the tab strip folds every non-active tab into the overflow menu at panel width, so a
75
+ * split reachable only by right-clicking another tab is unreachable in the common case. The
76
+ * newest other tab is the one the user just opened, which is what they mean by "show me both".
77
+ *
78
+ * `null` means there is nothing to split with — one tab, and a divider through one document
79
+ * is not two documents.
80
+ */
81
+ export function splitCandidate(
82
+ activeFileId: number | string | null,
83
+ openIds: readonly (number | string)[],
84
+ ): number | string | null {
85
+ for (let index = openIds.length - 1; index >= 0; index -= 1) {
86
+ const id = openIds[index];
87
+ if (id !== activeFileId) return id;
88
+ }
89
+ return null;
90
+ }
91
+
92
+ /**
93
+ * The split state after the ACTIVE tab changed.
94
+ *
95
+ * The left pane follows the active tab, so a switch that lands on the tab the right pane
96
+ * already shows would draw one file twice. The split collapses in that case rather than
97
+ * silently re-picking a different right pane: the user asked to look at that file, and the
98
+ * whole column showing it is the honest answer.
99
+ */
100
+ export function splitAfterActivate(state: SplitEditorState, activeFileId: number | string | null): SplitEditorState {
101
+ if (state.rightFileId === null) return state;
102
+ if (state.rightFileId !== activeFileId) return state;
103
+ return { ...state, rightFileId: null };
104
+ }
105
+
106
+ /** Clamp a dragged divider position into the bounds above. */
107
+ export function clampSplitFraction(fraction: number): number {
108
+ if (!Number.isFinite(fraction)) return DEFAULT_SPLIT.fraction;
109
+ return Math.max(MIN_SPLIT_FRACTION, Math.min(MAX_SPLIT_FRACTION, fraction));
110
+ }
111
+
112
+ /**
113
+ * The split's state read from a session blob, defended.
114
+ *
115
+ * A persisted `rightFileId` for a tab that no longer exists is DROPPED rather than trusted:
116
+ * the split would otherwise open onto a pane that cannot render, and the only way out would
117
+ * be to close a pane nobody can see.
118
+ */
119
+ export function readSplitState(raw: unknown, openIds: readonly (number | string)[]): SplitEditorState {
120
+ if (typeof raw !== 'object' || raw === null) return DEFAULT_SPLIT;
121
+ const value = raw as { rightFileId?: unknown; fraction?: unknown };
122
+ const fraction = typeof value.fraction === 'number' ? clampSplitFraction(value.fraction) : DEFAULT_SPLIT.fraction;
123
+ const rightFileId =
124
+ typeof value.rightFileId === 'string' || typeof value.rightFileId === 'number' ? value.rightFileId : null;
125
+ if (rightFileId === null || !openIds.includes(rightFileId)) {
126
+ return { rightFileId: null, fraction };
127
+ }
128
+ return { rightFileId, fraction };
129
+ }
@@ -64,13 +64,40 @@ export function diskHas(disk: Disk, path: string): boolean {
64
64
  return (disk[dir] ?? {})[name] !== undefined;
65
65
  }
66
66
 
67
+ /**
68
+ * The directories a single-child folder chain runs through, starting at `path`.
69
+ *
70
+ * Mirrors `folderChain` in `src/server/lib/fs/listing.ts`, including where it
71
+ * stops: a folder holding exactly one FOLDER continues the chain, and a file, a
72
+ * second entry or an empty folder ends it. The harness has to fold like the
73
+ * server does or a spec would assert a tree the real listing never produces.
74
+ */
75
+ function chainFrom(disk: Disk, path: string): string[] {
76
+ const segments = [path.slice(path.lastIndexOf('/') + 1)];
77
+ let current = path;
78
+ for (let depth = 1; depth < 32; depth += 1) {
79
+ const dir = disk[current];
80
+ const entries = Object.keys(dir ?? {});
81
+ if (entries.length !== 1 || dir![entries[0]!] !== null) return segments;
82
+ current = `${current}/${entries[0]}`;
83
+ segments.push(entries[0]!);
84
+ }
85
+ return segments;
86
+ }
87
+
67
88
  /** One directory's entries as the server emits them: folders with `children: null`. */
68
89
  export function entriesOf(disk: Disk, path: string): unknown[] {
69
90
  const dir = disk[path] ?? {};
70
91
  return Object.keys(dir).map((child) => {
71
92
  const rel = path === '.' ? child : `${path}/${child}`;
72
- return dir[child] === null
73
- ? { id: rel, name: child, type: 'folder', path: rel, children: null, ignored: false }
74
- : { id: rel, name: child, type: 'file', path: rel, ignored: false };
93
+ if (dir[child] !== null) return { id: rel, name: child, type: 'file', path: rel, ignored: false };
94
+ // A folder holding exactly one folder is one collapsed row naming the chain,
95
+ // whose path is the DEEPEST directory — the one whose contents it shows.
96
+ const chain = chainFrom(disk, rel);
97
+ if (chain.length > 1) {
98
+ const deep = `${rel}/${chain.slice(1).join('/')}`;
99
+ return { id: deep, name: chain.join('/'), type: 'folder', path: deep, children: null, ignored: false };
100
+ }
101
+ return { id: rel, name: child, type: 'folder', path: rel, children: null, ignored: false };
75
102
  });
76
103
  }