@kabmo-labs/kabmo 0.24.0 → 0.25.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 (205) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +579 -510
  3. package/dist/client/static/js/index-bc9aa4mx.css +1 -0
  4. package/dist/client/static/js/{index-jcr5twtp.js → index-ga8cbpt4.js} +1072 -1174
  5. package/package.json +2 -4
  6. package/src/cli/lib/args.js +24 -1
  7. package/src/cli/lib/args.test.js +16 -0
  8. package/src/cli/lib/commands/session.js +233 -0
  9. package/src/cli/lib/commands/session.test.js +103 -0
  10. package/src/cli/main.js +1 -1
  11. package/src/client/components/common/ComposerPicker.tsx +3 -0
  12. package/src/client/components/common/code-surface/shiki.test.ts +82 -0
  13. package/src/client/components/common/code-surface/shiki.ts +28 -7
  14. package/src/client/components/common/session-actions-menu/NewChildSessionDialog.tsx +113 -0
  15. package/src/client/components/common/session-actions-menu/index.tsx +33 -2
  16. package/src/client/components/common/session-row/StatusSlot.tsx +4 -4
  17. package/src/client/components/common/session-row/index.tsx +27 -1
  18. package/src/client/components/layout/desktop-layout/resizer/separator-drag.ts +3 -3
  19. package/src/client/components/layout/session-sidebar/CategoryItem.tsx +25 -12
  20. package/src/client/components/layout/session-sidebar/ChildSessionList.tsx +66 -0
  21. package/src/client/components/layout/session-sidebar/SessionItem.tsx +28 -3
  22. package/src/client/components/layout/session-sidebar/about-modal/HarnessTable.tsx +36 -5
  23. package/src/client/components/layout/session-sidebar/about-modal/HarnessTableLog.test.tsx +94 -0
  24. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.test.tsx +130 -0
  25. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogDialog.tsx +120 -0
  26. package/src/client/components/layout/session-sidebar/about-modal/UpdateLogLine.tsx +47 -0
  27. package/src/client/components/layout/session-sidebar/about-modal/index.tsx +28 -35
  28. package/src/client/components/layout/session-sidebar/modern/WorkspaceSection.tsx +18 -5
  29. package/src/client/components/mobile/mobile-session-sidebar/Item.tsx +21 -4
  30. package/src/client/components/mobile/mobile-session-sidebar/SessionRow.tsx +27 -5
  31. package/src/client/components/workspace/chat-timeline/ComposerDock.tsx +64 -70
  32. package/src/client/components/workspace/chat-timeline/ComposerDockFrame.tsx +35 -0
  33. package/src/client/components/workspace/chat-timeline/EmptyWorkspacePrompt.tsx +135 -118
  34. package/src/client/components/workspace/chat-timeline/MessageItem.tsx +22 -1
  35. package/src/client/components/workspace/chat-timeline/MessageList.tsx +4 -0
  36. package/src/client/components/workspace/chat-timeline/TimelineBody.tsx +3 -0
  37. package/src/client/components/workspace/chat-timeline/composer-dock-frame.test.tsx +155 -0
  38. package/src/client/components/workspace/chat-timeline/index.tsx +3 -1
  39. package/src/client/components/workspace/terminal-panel/KeyBar.tsx +10 -8
  40. package/src/client/components/workspace/terminal-panel/{RealtimeXtermView.tsx → RealtimeTerminalView.tsx} +51 -58
  41. package/src/client/components/workspace/terminal-panel/fit.test.ts +37 -0
  42. package/src/client/components/workspace/terminal-panel/fit.ts +64 -0
  43. package/src/client/components/workspace/terminal-panel/fonts.test.ts +161 -0
  44. package/src/client/components/workspace/terminal-panel/fonts.ts +164 -0
  45. package/src/client/components/workspace/terminal-panel/grid.test.ts +52 -0
  46. package/src/client/components/workspace/terminal-panel/grid.ts +118 -0
  47. package/src/client/components/workspace/terminal-panel/index.tsx +25 -21
  48. package/src/client/components/workspace/terminal-panel/mount.ts +247 -223
  49. package/src/client/components/workspace/terminal-panel/navigation.test.ts +54 -0
  50. package/src/client/components/workspace/terminal-panel/navigation.ts +47 -0
  51. package/src/client/data/settings/omp-schema.json +1 -1
  52. package/src/client/data/theme/terminal.test.ts +25 -0
  53. package/src/client/data/theme/terminal.ts +96 -79
  54. package/src/client/hooks/chat/composer/items.test.ts +12 -26
  55. package/src/client/hooks/chat/composer/pick-mapping.test.ts +42 -0
  56. package/src/client/hooks/chat/omp/prompt-send.test.ts +7 -7
  57. package/src/client/hooks/chat/omp/prompt-send.ts +26 -14
  58. package/src/client/hooks/chat/timeline/prompt-text.test.ts +34 -1
  59. package/src/client/hooks/chat/timeline/prompt-text.ts +47 -20
  60. package/src/client/hooks/chat/timeline/send-execute.test.ts +39 -0
  61. package/src/client/hooks/chat/timeline/send-helpers.ts +30 -1
  62. package/src/client/hooks/chat/timeline/send-steer.test.ts +3 -1
  63. package/src/client/hooks/chat/timeline/send.test-util.ts +7 -1
  64. package/src/client/hooks/chat/timeline/send.test.ts +3 -1
  65. package/src/client/hooks/chat/timeline/send.ts +51 -50
  66. package/src/client/hooks/chat/timeline/use-fork-session.ts +49 -0
  67. package/src/client/hooks/models/use-harness-update.test.ts +193 -0
  68. package/src/client/hooks/models/use-harness-update.ts +202 -0
  69. package/src/client/hooks/workspace/child-expansion.ts +33 -0
  70. package/src/client/hooks/workspace/terminal/index.ts +17 -3
  71. package/src/client/hooks/workspace/terminal/socket.ts +9 -4
  72. package/src/client/lib/session-tree.test.ts +50 -0
  73. package/src/client/lib/session-tree.ts +59 -0
  74. package/src/client/tailwind.css +17 -11
  75. package/src/server/index.ts +2 -0
  76. package/src/server/lib/auth/guard.ts +10 -0
  77. package/src/server/lib/btw/session-copy.server.ts +6 -44
  78. package/src/server/lib/btw/session-copy.test.ts +2 -1
  79. package/src/server/lib/db/schema.ts +4 -0
  80. package/src/server/lib/db/seed-terminal.test.ts +1 -1
  81. package/src/server/lib/db/seed.test.ts +1 -1
  82. package/src/server/lib/harness/acp/background-work.test.ts +262 -0
  83. package/src/server/lib/harness/acp/background-work.ts +320 -0
  84. package/src/server/lib/harness/acp/client.ts +2 -2
  85. package/src/server/lib/harness/acp/gateway-env.test.ts +64 -0
  86. package/src/server/lib/harness/acp/gateway-env.ts +70 -0
  87. package/src/server/lib/harness/acp/prompt.test.ts +20 -0
  88. package/src/server/lib/harness/acp/prompt.ts +19 -3
  89. package/src/server/lib/harness/acp/session-background.test.ts +129 -0
  90. package/src/server/lib/harness/acp/session-exit.ts +31 -0
  91. package/src/server/lib/harness/acp/session-handshake.test.ts +108 -0
  92. package/src/server/lib/harness/acp/session-handshake.ts +27 -1
  93. package/src/server/lib/harness/acp/session-listeners.ts +31 -0
  94. package/src/server/lib/harness/acp/session-requests.ts +47 -0
  95. package/src/server/lib/harness/acp/session-turns.ts +20 -5
  96. package/src/server/lib/harness/acp/session.test-util.ts +23 -1
  97. package/src/server/lib/harness/acp/session.ts +59 -59
  98. package/src/server/lib/harness/acp/turn.test.ts +81 -0
  99. package/src/server/lib/harness/acp/turn.ts +26 -9
  100. package/src/server/lib/harness/acp/verbs.ts +12 -2
  101. package/src/server/lib/harness/launch.ts +3 -1
  102. package/src/server/lib/harness/spawn.server.ts +15 -2
  103. package/src/server/lib/harness/update-job-store.test.ts +126 -0
  104. package/src/server/lib/harness/update-job-store.ts +109 -0
  105. package/src/server/lib/harness/update-job.server.ts +203 -0
  106. package/src/server/lib/harness/update-worker.test.ts +153 -0
  107. package/src/server/lib/harness/update-worker.ts +197 -0
  108. package/src/server/lib/lifecycle/paths.ts +23 -0
  109. package/src/server/lib/omp/rpc/manager.ts +5 -5
  110. package/src/server/lib/omp/rpc/prewarm-pool.ts +12 -3
  111. package/src/server/lib/omp/rpc/session-registry.ts +14 -2
  112. package/src/server/lib/omp/rpc/terminal-settle.ts +53 -5
  113. package/src/server/lib/omp/session/delete-flow.server.ts +47 -0
  114. package/src/server/lib/omp/session/delete.server.ts +5 -0
  115. package/src/server/lib/omp/session/rewind-file.ts +39 -21
  116. package/src/server/lib/omp/session/sidebar-data.server.ts +6 -6
  117. package/src/server/lib/omp/session/transcript-copy.ts +123 -0
  118. package/src/server/lib/sessions/agent-token.server.test.ts +64 -0
  119. package/src/server/lib/sessions/agent-token.server.ts +134 -0
  120. package/src/server/lib/sessions/answers.server.test.ts +33 -0
  121. package/src/server/lib/sessions/answers.server.ts +37 -0
  122. package/src/server/lib/sessions/dispatch.server.test.ts +143 -0
  123. package/src/server/lib/sessions/dispatch.server.ts +128 -0
  124. package/src/server/lib/sessions/fork.server.test.ts +209 -0
  125. package/src/server/lib/sessions/fork.server.ts +304 -0
  126. package/src/server/lib/sessions/lifecycle.server.test.ts +75 -0
  127. package/src/server/lib/sessions/lifecycle.server.ts +71 -0
  128. package/src/server/lib/sessions/notify.server.test.ts +112 -0
  129. package/src/server/lib/sessions/notify.server.ts +212 -0
  130. package/src/server/lib/sessions/relation-types.ts +76 -0
  131. package/src/server/lib/sessions/relations.server.test.ts +207 -0
  132. package/src/server/lib/sessions/relations.server.ts +337 -0
  133. package/src/server/lib/sessions/resolve.server.ts +106 -0
  134. package/src/server/lib/sessions/schema.server.ts +82 -0
  135. package/src/server/lib/sessions/sidebar-relations.server.test.ts +61 -0
  136. package/src/server/lib/sessions/sidebar-relations.server.ts +47 -0
  137. package/src/server/lib/sessions/spawn.server.test.ts +196 -0
  138. package/src/server/lib/sessions/spawn.server.ts +310 -0
  139. package/src/server/lib/terminal/attach-replay.test.ts +2 -2
  140. package/src/server/lib/terminal/output.test.ts +2 -2
  141. package/src/server/lib/terminal/output.ts +1 -1
  142. package/src/server/lib/terminal/resize.test.ts +99 -0
  143. package/src/server/lib/terminal/runtime.server.ts +26 -6
  144. package/src/server/lib/terminal/send-result.test.ts +18 -1
  145. package/src/server/lib/terminal/send-result.ts +26 -2
  146. package/src/server/lib/terminal/session.server.ts +6 -6
  147. package/src/server/lib/usage/new-api.test.ts +92 -0
  148. package/src/server/lib/usage/new-api.ts +131 -0
  149. package/src/server/lib/usage/provider-endpoint.test.ts +106 -0
  150. package/src/server/lib/usage/provider-key.ts +33 -0
  151. package/src/server/lib/usage/providers.server.ts +10 -3
  152. package/src/server/lib/usage/vendor-balance.server.ts +4 -53
  153. package/src/server/lib/usage/vendor-http.ts +41 -0
  154. package/src/server/lib/usage/window.ts +55 -0
  155. package/src/server/routes/agent/command.ts +14 -1
  156. package/src/server/routes/agent/harness-command.ts +6 -0
  157. package/src/server/routes/agent/new.ts +15 -0
  158. package/src/server/routes/harness/add-provider.test.ts +9 -1
  159. package/src/server/routes/harness/import-action.ts +4 -0
  160. package/src/server/routes/harness/import.test.ts +1 -1
  161. package/src/server/routes/harness/index.ts +5 -1
  162. package/src/server/routes/harness/update-status.ts +26 -0
  163. package/src/server/routes/harness/update.test.ts +119 -0
  164. package/src/server/routes/harness/update.ts +59 -147
  165. package/src/server/routes/sessions/answer.ts +24 -0
  166. package/src/server/routes/sessions/batch-delete.ts +11 -5
  167. package/src/server/routes/sessions/delete.ts +4 -2
  168. package/src/server/routes/sessions/fork.ts +74 -0
  169. package/src/server/routes/sessions/index.ts +14 -0
  170. package/src/server/routes/sessions/relations.ts +85 -0
  171. package/src/server/routes/sessions/session.ts +4 -0
  172. package/src/server/routes/sessions/spawn.ts +134 -0
  173. package/src/server/routes/terminal/ws.ts +3 -3
  174. package/src/shared/lib/chat/composer/client.ts +31 -2
  175. package/src/shared/lib/chat/composer/delegation.test.ts +93 -0
  176. package/src/shared/lib/chat/composer/delegation.ts +206 -0
  177. package/src/shared/lib/chat/notice-text.ts +1 -1
  178. package/src/shared/lib/chat/tool/summary-wait.test.ts +11 -0
  179. package/src/shared/lib/code/ansi.ts +1 -1
  180. package/src/shared/lib/fonts/nerd-symbols.css +4 -3
  181. package/src/shared/lib/fonts/nerd-symbols.test.ts +9 -9
  182. package/src/shared/lib/harness/provider-facts.test.ts +27 -0
  183. package/src/shared/lib/harness/providers.ts +35 -1
  184. package/src/shared/lib/harness/update-job.ts +33 -0
  185. package/src/shared/lib/harness/update-plan.test.ts +21 -6
  186. package/src/shared/lib/harness/update-plan.ts +12 -4
  187. package/src/shared/lib/omp/session/wait-idle.test.ts +11 -0
  188. package/src/shared/lib/omp/session/wait-idle.ts +12 -2
  189. package/src/shared/lib/theme/catalog.test.ts +13 -9
  190. package/src/shared/lib/theme/color.test.ts +2 -2
  191. package/src/shared/lib/theme/color.ts +4 -4
  192. package/src/shared/lib/theme/theme.test.ts +1 -1
  193. package/src/shared/lib/workspace/terminal/input.test.ts +27 -0
  194. package/src/shared/lib/workspace/terminal/input.ts +33 -0
  195. package/src/shared/lib/workspace/terminal/keys.test.ts +1 -1
  196. package/src/shared/lib/workspace/terminal/keys.ts +7 -7
  197. package/src/shared/types/chat.ts +1 -1
  198. package/src/shared/types/harness-update.ts +65 -0
  199. package/src/shared/types/omp/agent.ts +19 -2
  200. package/src/shared/types/workspace.ts +4 -0
  201. package/src/test-support/fake-omp-fork.ts +16 -2
  202. package/src/test-support/harness-table.test-util.ts +15 -1
  203. package/dist/client/static/js/index-z3w7n85q.css +0 -1
  204. package/src/client/components/workspace/terminal-panel/webgl.test.ts +0 -75
  205. package/src/client/components/workspace/terminal-panel/webgl.ts +0 -108
@@ -0,0 +1,161 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ import { afterEach, describe, expect, test } from 'bun:test';
7
+ import {
8
+ measureTerminalCell,
9
+ waitForTerminalFonts,
10
+ watchTerminalFonts,
11
+ } from '@/client/components/workspace/terminal-panel/fonts';
12
+
13
+ type LoadingListener = (event: { fontfaces: { family: string }[] }) => void;
14
+
15
+ interface FakeFonts {
16
+ load: (font: string, text?: string) => Promise<unknown>;
17
+ addEventListener: (_type: string, listener: LoadingListener) => void;
18
+ removeEventListener: (_type: string, listener: LoadingListener) => void;
19
+ }
20
+
21
+ function installFakeDocument(): { fonts: FakeFonts; listeners: Set<LoadingListener> } {
22
+ const listeners = new Set<LoadingListener>();
23
+ const fonts: FakeFonts = {
24
+ load: async () => [],
25
+ addEventListener: (_type, listener) => listeners.add(listener),
26
+ removeEventListener: (_type, listener) => listeners.delete(listener),
27
+ };
28
+ // Bun has no DOM; install the one object the helpers read.
29
+ const host = globalThis as unknown as { document?: unknown };
30
+ host.document = { fonts };
31
+ return { fonts, listeners };
32
+ }
33
+
34
+ afterEach(() => {
35
+ const host = globalThis as unknown as { document?: unknown };
36
+ delete host.document;
37
+ });
38
+
39
+ describe('waitForTerminalFonts', () => {
40
+ test('loads the text face only, so the bundled symbols face stays lazy', async () => {
41
+ const { fonts } = installFakeDocument();
42
+ const calls: { font: string; text?: string }[] = [];
43
+ fonts.load = async (font, text) => {
44
+ calls.push({ font, ...(text ? { text } : {}) });
45
+ return [];
46
+ };
47
+
48
+ await waitForTerminalFonts();
49
+
50
+ expect(calls).toEqual([{ font: '12px "Fira Code"' }]);
51
+ expect(calls.some((call) => call.font.includes('Kabmo Nerd Symbols'))).toBe(false);
52
+ });
53
+
54
+ test('a face that fails to load does not keep the terminal closed', async () => {
55
+ const { fonts } = installFakeDocument();
56
+ fonts.load = async () => {
57
+ throw new Error('offline');
58
+ };
59
+
60
+ expect(await waitForTerminalFonts()).toBeUndefined();
61
+ });
62
+ });
63
+
64
+ describe('watchTerminalFonts', () => {
65
+ test('calls back only for a terminal face', () => {
66
+ const { listeners } = installFakeDocument();
67
+ let loaded = 0;
68
+ const dispose = watchTerminalFonts(() => {
69
+ loaded += 1;
70
+ });
71
+
72
+ for (const listener of listeners) listener({ fontfaces: [{ family: 'Inter' }] });
73
+ expect(loaded).toBe(0);
74
+
75
+ for (const listener of listeners) listener({ fontfaces: [{ family: '"Fira Code"' }] });
76
+ expect(loaded).toBe(1);
77
+
78
+ dispose();
79
+ expect(listeners.size).toBe(0);
80
+ });
81
+ });
82
+
83
+ describe('measureTerminalCell', () => {
84
+ interface Box {
85
+ advance: number;
86
+ /** Ink of `Mg`. */
87
+ ascent: number;
88
+ descent: number;
89
+ /** The font's own line box, as `fontBoundingBox*` reports it. */
90
+ lineAscent: number;
91
+ lineDescent: number;
92
+ }
93
+
94
+ function installFakeCanvas(box: Box): { fonts: unknown } {
95
+ const host = globalThis as unknown as { document?: unknown };
96
+ const context = {
97
+ font: '',
98
+ measureText: (text: string) => {
99
+ const descent = text === 'Mg' ? box.descent : 0;
100
+ return {
101
+ width: box.advance,
102
+ actualBoundingBoxAscent: box.ascent,
103
+ actualBoundingBoxDescent: descent,
104
+ fontBoundingBoxAscent: box.lineAscent,
105
+ fontBoundingBoxDescent: box.lineDescent,
106
+ };
107
+ },
108
+ };
109
+ host.document = { fonts: {}, createElement: () => ({ getContext: () => context }) };
110
+ return { fonts: {} };
111
+ }
112
+
113
+ // Fira Code at 12 px, measured in Chromium: an `M` advance of 7.2, an `Mg`
114
+ // ink of 8.26 above and 2.54 below the baseline, and a line box of 12 + 4.
115
+ const FIRA_CODE_12: Box = {
116
+ advance: 7.2,
117
+ ascent: 8.26,
118
+ descent: 2.54,
119
+ lineAscent: 12,
120
+ lineDescent: 4,
121
+ };
122
+
123
+ test('pads the ink 2.5 px above and 1 px below', () => {
124
+ installFakeCanvas(FIRA_CODE_12);
125
+
126
+ const cell = measureTerminalCell(12, "'Fira Code'");
127
+
128
+ // The cell is the paintable advance rounded up, not the font size.
129
+ expect(cell.width).toBe(8);
130
+ // 11 px of ink + 2.5 + 1, rounded up: a cell built from `M` alone was the
131
+ // reported bug — the descender ended on the cell's last pixel and the next
132
+ // row clipped it.
133
+ expect(cell.height).toBe(15);
134
+ const above = cell.baseline - FIRA_CODE_12.ascent;
135
+ const below = cell.height - cell.baseline - FIRA_CODE_12.descent;
136
+ expect(Math.abs(above - 2.5)).toBeLessThanOrEqual(0.5);
137
+ expect(Math.abs(below - 1)).toBeLessThanOrEqual(0.5);
138
+ });
139
+
140
+ test('never lets ink exceed the cell when it reaches past the line box', () => {
141
+ // A face whose `g` hangs lower than its `fontBoundingBox` says it should.
142
+ const box: Box = { advance: 7.2, ascent: 9, descent: 6, lineAscent: 10, lineDescent: 2 };
143
+ installFakeCanvas(box);
144
+
145
+ const cell = measureTerminalCell(12, "'Fira Code'");
146
+
147
+ expect(cell.height).toBeGreaterThanOrEqual(Math.ceil(box.ascent + box.descent) + 4);
148
+ expect(cell.baseline - box.ascent).toBeGreaterThanOrEqual(1);
149
+ expect(cell.height - cell.baseline - box.descent).toBeGreaterThanOrEqual(1);
150
+ });
151
+
152
+ test('answers a usable box when there is no DOM', () => {
153
+ const host = globalThis as unknown as { document?: unknown };
154
+ delete host.document;
155
+
156
+ const cell = measureTerminalCell(12, "'Fira Code'");
157
+
158
+ expect(cell.width).toBeGreaterThan(0);
159
+ expect(cell.height).toBeGreaterThan(cell.baseline);
160
+ });
161
+ });
@@ -0,0 +1,164 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Font readiness for the terminal canvas.
8
+ *
9
+ * The renderer measures its cell box when the terminal opens. Measuring against
10
+ * a fallback face gives the grid the wrong width, and a phone has no installed
11
+ * Nerd Font to fall through to. A face that lands later is not fatal: the
12
+ * caller re-measures and fits.
13
+ */
14
+
15
+ import type { Terminal } from 'ghostty-web';
16
+ import {
17
+ TERMINAL_FACES,
18
+ TERMINAL_FONT_FAMILY,
19
+ TERMINAL_FONT_SIZE,
20
+ TERMINAL_TEXT_FAMILY,
21
+ } from '@/client/data/theme/terminal';
22
+
23
+ const FONT_LOAD_TIMEOUT_MS = 2000;
24
+
25
+ /**
26
+ * Wait for the text face, bounded by a timeout.
27
+ *
28
+ * Only the text face is loaded explicitly: the renderer measures `M` for its
29
+ * cell width, and that glyph comes from the text face. Asking for the bundled
30
+ * symbols face here would force its 1.1 MB download on every machine, including
31
+ * the ones whose own Nerd Font the fallback chain would have used — the
32
+ * `@font-face` is deliberately lazy. PUA glyphs that arrive late are repainted
33
+ * by `watchTerminalFonts`.
34
+ */
35
+ export async function waitForTerminalFonts(): Promise<void> {
36
+ if (typeof document === 'undefined' || !document.fonts?.load) return;
37
+ const timeout = Promise.withResolvers<void>();
38
+ const timer = setTimeout(timeout.resolve, FONT_LOAD_TIMEOUT_MS);
39
+ try {
40
+ await Promise.race([
41
+ document.fonts.load(`${TERMINAL_FONT_SIZE}px "${TERMINAL_TEXT_FAMILY}"`).then(
42
+ () => undefined,
43
+ () => undefined,
44
+ ),
45
+ timeout.promise,
46
+ ]);
47
+ } finally {
48
+ clearTimeout(timer);
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Call `onLoaded` when one of the terminal's faces lands late.
54
+ *
55
+ * Returns a disposer.
56
+ */
57
+ export function watchTerminalFonts(onLoaded: () => void): () => void {
58
+ if (typeof document === 'undefined' || !document.fonts) return () => {};
59
+ const faces = new Set<string>(TERMINAL_FACES);
60
+ const listener = (event: FontFaceSetLoadEvent) => {
61
+ const loaded = [...event.fontfaces].some((face) =>
62
+ faces.has(face.family.replace(/['"]/g, '').trim()),
63
+ );
64
+ if (loaded) onLoaded();
65
+ };
66
+ document.fonts.addEventListener('loadingdone', listener);
67
+ return () => document.fonts.removeEventListener('loadingdone', listener);
68
+ }
69
+
70
+ /** One cell's box in CSS px, as the canvas renderer needs it. */
71
+ export interface TerminalCellMetrics {
72
+ width: number;
73
+ height: number;
74
+ baseline: number;
75
+ }
76
+
77
+ /**
78
+ * Block padding above the ink's ascent and below its descent, in CSS px.
79
+ *
80
+ * Measured against the glyph ink, not the em box: the rectangle a person sees
81
+ * around a coloured run is compared to the letters, so these are the numbers
82
+ * chosen on the real panel — 2.5 over 1, which puts the letters high in the
83
+ * rectangle; the 1 px below is still enough for a `g`/`y`/`p` descender (2.54)
84
+ * because the padding is measured from the *ink*, not the baseline.
85
+ *
86
+ * Fractional on purpose: the cell height is `ceil` of the ink plus both paddings
87
+ * (15 px at 12 px Fira Code), and the baseline is `round(ascent + top)`, which
88
+ * is what makes a 2.5 request land as 3 px of block above a cap that sits 2.74
89
+ * px below it.
90
+ */
91
+ const CELL_PADDING_TOP_PX = 2.5;
92
+ const CELL_PADDING_BOTTOM_PX = 1;
93
+
94
+ /**
95
+ * Measure the cell box from the font's real ink, not one glyph's.
96
+ *
97
+ * ghostty-web's own `measureFont` measures `M` alone. `M` has no descender, so
98
+ * it substitutes `0.2em`, and the box comes out **13 px** at 12 px Fira Code
99
+ * (ink ascent 8.3, baseline 10, cell ends at 13). A `g`/`y`/`p` descender then
100
+ * ends on the row's last pixel, and since every row is repainted with the theme
101
+ * background before its cells (`renderLine`), the next row's fill clips whatever
102
+ * hangs below — measured: a `\e[41m` block around `ggyypp` had 0 px of block
103
+ * under the descenders, and every coloured block read as cropped.
104
+ *
105
+ * Measuring `Mg` supplies a real descent, and the box is the ink plus the two
106
+ * paddings above: at 12 px Fira Code (ink 8.26 / 2.54) that is `height = 15`
107
+ * and `baseline = 11`, i.e. 2.74 px of block above the cap and 1.46 px below
108
+ * the descender. The box is deliberately not the font's line box (line box plus
109
+ * padding came out 20 px, which read as too loose on the real panel).
110
+ */
111
+ export function measureTerminalCell(fontSize: number, fontFamily: string): TerminalCellMetrics {
112
+ // The fallback is the CSS default ratio, used when there is no canvas to
113
+ // measure against (a unit test, a non-DOM import).
114
+ const fallbackAscent = fontSize * 0.8;
115
+ const fallbackDescent = fontSize * 0.2;
116
+ let width = Math.ceil(fontSize * 0.6);
117
+ let ascent = fallbackAscent;
118
+ let descent = fallbackDescent;
119
+ const context =
120
+ typeof document === 'undefined' ? null : document.createElement('canvas').getContext('2d');
121
+ if (context) {
122
+ context.font = `${fontSize}px ${fontFamily}`;
123
+ width = Math.ceil(context.measureText('M').width) || width;
124
+ const ink = context.measureText('Mg');
125
+ ascent = ink.actualBoundingBoxAscent || fallbackAscent;
126
+ descent = ink.actualBoundingBoxDescent || fallbackDescent;
127
+ }
128
+ return {
129
+ width,
130
+ height: Math.ceil(ascent + descent + CELL_PADDING_TOP_PX + CELL_PADDING_BOTTOM_PX),
131
+ baseline: Math.round(ascent + CELL_PADDING_TOP_PX),
132
+ };
133
+ }
134
+
135
+ /** The private end of `CanvasRenderer` this module corrects. */
136
+ interface MetricsRenderer {
137
+ measureFont: () => TerminalCellMetrics;
138
+ remeasureFont: () => void;
139
+ }
140
+
141
+ /**
142
+ * Give the renderer a cell box that holds a descender.
143
+ *
144
+ * `CanvasRenderer.measureFont` and the field it writes are private, and the
145
+ * cell height it derives from `M` leaves a descender on the row's last pixel
146
+ * (see `measureTerminalCell`). Replacing the instance method and re-measuring
147
+ * is the only way to correct it without patching the dependency:
148
+ * `remeasureFont()` calls `this.measureFont()`, and every consumer — fit,
149
+ * `resize`, `render`, the mouse-report cell size — reads `getMetrics()`.
150
+ *
151
+ * The override reads `term.options`, so the font-size round-trip in
152
+ * `watchTerminalFonts` re-measures with this rule instead of restoring the
153
+ * vendor's 13 px box.
154
+ */
155
+ export function installCellMetrics(term: Terminal): void {
156
+ const renderer = term.renderer as unknown as MetricsRenderer | undefined;
157
+ if (!renderer) return;
158
+ renderer.measureFont = () =>
159
+ measureTerminalCell(
160
+ term.options.fontSize ?? TERMINAL_FONT_SIZE,
161
+ term.options.fontFamily ?? TERMINAL_FONT_FAMILY,
162
+ );
163
+ renderer.remeasureFont();
164
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ import { describe, expect, test } from 'bun:test';
7
+ import {
8
+ GRID_SETTLE_MS,
9
+ MIN_REPORT_COLS,
10
+ MIN_REPORT_ROWS,
11
+ gridDecision,
12
+ } from '@/client/components/workspace/terminal-panel/grid';
13
+
14
+ const UNATTACHED = { attached: false, committed: { cols: 0, rows: 0 } };
15
+
16
+ describe('gridDecision', () => {
17
+ test('announces the first real grid as the attach size', () => {
18
+ expect(gridDecision({ cols: 41, rows: 47, ...UNATTACHED })).toEqual({
19
+ kind: 'attach',
20
+ cols: 41,
21
+ rows: 47,
22
+ });
23
+ });
24
+
25
+ test('ignores a squeezed panel instead of resizing the shell', () => {
26
+ // Measured: `resize 5x37` reached a real shell while the panel was opening
27
+ // its width transition, and the shell redrew its prompt hard-wrapped.
28
+ expect(gridDecision({ cols: 5, rows: 37, ...UNATTACHED })).toEqual({ kind: 'ignore' });
29
+ expect(gridDecision({ cols: MIN_REPORT_COLS - 1, rows: 47, ...UNATTACHED })).toEqual({
30
+ kind: 'ignore',
31
+ });
32
+ expect(gridDecision({ cols: 41, rows: MIN_REPORT_ROWS - 1, ...UNATTACHED })).toEqual({
33
+ kind: 'ignore',
34
+ });
35
+ });
36
+
37
+ test('maps a corrected grid onto a resize once attached', () => {
38
+ const attached = { attached: true, committed: { cols: 41, rows: 47 } };
39
+ expect(gridDecision({ cols: 41, rows: 47, ...attached })).toEqual({ kind: 'ignore' });
40
+ expect(gridDecision({ cols: 40, rows: 47, ...attached })).toEqual({
41
+ kind: 'change',
42
+ cols: 40,
43
+ rows: 47,
44
+ });
45
+ });
46
+
47
+ test('waits longer than a frame before announcing', () => {
48
+ // The panel's width transition outlives one animation frame; a gate shorter
49
+ // than ~100 ms measured the animating box again.
50
+ expect(GRID_SETTLE_MS).toBeGreaterThanOrEqual(100);
51
+ });
52
+ });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * When a terminal grid may be announced to the shell.
8
+ *
9
+ * A terminal's grid is a PTY size, and a PTY size is a `SIGWINCH`: the shell
10
+ * answers each one by redrawing its prompt, and those redraws are output that
11
+ * lives in the scrollback forever. The right panel opens with a width
12
+ * transition, so fits during it measure a squeezed box — announcing one sent
13
+ * `resize 5x37` to a real shell, which redrew its prompt hard-wrapped at five
14
+ * columns. Worse, before the first fit the terminal still holds ghostty's 80×24
15
+ * default, which looks like a plausible size: a reload announced `80x24` and the
16
+ * shell answered by rewrapping its prompt at 80 columns. Both left garbage in
17
+ * the history, and every later reload replayed one more block of it above the
18
+ * live prompt, which is why the prompt marched down the panel.
19
+ *
20
+ * Two rules follow, and they are this module:
21
+ *
22
+ * - **A grid is announced only after it has held still** (`GRID_SETTLE_MS`), so
23
+ * a value read mid-animation never leaves the client.
24
+ * - **A grid comes from a real fit**, never from the terminal's default: the
25
+ * caller's `fit()` reports whether the container was measurable, and the
26
+ * decision below is not even asked when it was not.
27
+ */
28
+
29
+ import type { Terminal } from 'ghostty-web';
30
+
31
+ /** A grid below this is a panel mid-transition, not a size someone chose. */
32
+ export const MIN_REPORT_COLS = 10;
33
+ export const MIN_REPORT_ROWS = 5;
34
+ /** How long a grid must hold still before it is announced to the shell. */
35
+ export const GRID_SETTLE_MS = 120;
36
+
37
+ export type GridEvent =
38
+ | { kind: 'ignore' }
39
+ | { kind: 'attach'; cols: number; rows: number }
40
+ | { kind: 'change'; cols: number; rows: number };
41
+
42
+ /**
43
+ * Classify a measured grid against what has already been announced.
44
+ *
45
+ * Pure, so the rules can be pinned without a renderer, a timer or a socket.
46
+ */
47
+ export function gridDecision(input: {
48
+ cols: number;
49
+ rows: number;
50
+ attached: boolean;
51
+ committed: { cols: number; rows: number };
52
+ }): GridEvent {
53
+ const { cols, rows, attached, committed } = input;
54
+ if (cols < MIN_REPORT_COLS || rows < MIN_REPORT_ROWS) return { kind: 'ignore' };
55
+ if (!attached) return { kind: 'attach', cols, rows };
56
+ if (cols === committed.cols && rows === committed.rows) return { kind: 'ignore' };
57
+ return { kind: 'change', cols, rows };
58
+ }
59
+
60
+ export interface GridAnnouncerOptions {
61
+ /** The live terminal; the announcer never holds it, a theme rebuild replaces it. */
62
+ current: () => Terminal | undefined;
63
+ /** Fit to the container. False when the panel is hidden or the cell unmeasured. */
64
+ fit: () => boolean;
65
+ onReady: (cols: number, rows: number) => void;
66
+ onGridChange: (cols: number, rows: number) => void;
67
+ }
68
+
69
+ export interface GridAnnouncer {
70
+ /** Announce after the grid has held still for `GRID_SETTLE_MS`. */
71
+ schedule: () => void;
72
+ /** Forget what was announced, so the next commit states the grid again. */
73
+ restate: () => void;
74
+ /** True once the first real grid has been announced. */
75
+ isAttached: () => boolean;
76
+ dispose: () => void;
77
+ }
78
+
79
+ export function createGridAnnouncer(options: GridAnnouncerOptions): GridAnnouncer {
80
+ let committed = { cols: 0, rows: 0 };
81
+ let attached = false;
82
+ let timer: ReturnType<typeof setTimeout> | undefined;
83
+
84
+ const commit = (): void => {
85
+ if (!options.fit()) return;
86
+ const term = options.current();
87
+ if (!term) return;
88
+ const event = gridDecision({
89
+ cols: term.cols,
90
+ rows: term.rows,
91
+ attached,
92
+ committed,
93
+ });
94
+ if (event.kind === 'ignore') return;
95
+ committed = { cols: event.cols, rows: event.rows };
96
+ if (event.kind === 'attach') {
97
+ attached = true;
98
+ options.onReady(event.cols, event.rows);
99
+ return;
100
+ }
101
+ options.onGridChange(event.cols, event.rows);
102
+ };
103
+
104
+ return {
105
+ schedule() {
106
+ clearTimeout(timer);
107
+ timer = setTimeout(commit, GRID_SETTLE_MS);
108
+ },
109
+ restate() {
110
+ committed = { cols: 0, rows: 0 };
111
+ },
112
+ isAttached: () => attached,
113
+ dispose() {
114
+ clearTimeout(timer);
115
+ timer = undefined;
116
+ },
117
+ };
118
+ }
@@ -8,7 +8,7 @@ import { copyToClipboard, readClipboardText } from '@/client/hooks/ui/clipboard'
8
8
  import { TerminalHeader } from '@/client/components/workspace/terminal-panel/Header';
9
9
  import { TerminalQuickActions } from '@/client/components/workspace/terminal-panel/QuickActions';
10
10
  import { TerminalKeyBar } from '@/client/components/workspace/terminal-panel/KeyBar';
11
- import { RealtimeXtermView, type RealtimeXtermHandle } from '@/client/components/workspace/terminal-panel/RealtimeXtermView';
11
+ import { RealtimeTerminalView, type RealtimeTerminalHandle } from '@/client/components/workspace/terminal-panel/RealtimeTerminalView';
12
12
  import {
13
13
  NO_MODIFIERS,
14
14
  applyModifiers,
@@ -30,7 +30,7 @@ interface TerminalPanelProps {
30
30
  const encoder = new TextEncoder();
31
31
 
32
32
  export function TerminalPanel({ className = '', enabled = true, rootPath, showHeader = true, active = true }: TerminalPanelProps) {
33
- const xtermRef = useRef<RealtimeXtermHandle>(null);
33
+ const terminalRef = useRef<RealtimeTerminalHandle>(null);
34
34
  const { isDark } = useTheme();
35
35
  // Only a device without a physical keyboard gets the key bar: on a desktop
36
36
  // every one of those keys is already under the user's fingers, and a strip of
@@ -44,21 +44,21 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
44
44
  const { activeRepo, setActiveRepo } = useRepoScope(rootPath);
45
45
  const { repos, scanning: reposScanning, rescan: rescanRepos } = useRepoList(rootPath, enabled);
46
46
  const gridRef = useRef<{ cols: number; rows: number } | null>(null);
47
- // The latch is read inside `handleInput`, which xterm calls outside React's
47
+ // The latch is read inside `handleInput`, which the terminal calls outside React's
48
48
  // render — a ref is what makes it the value at the keystroke, not at mount.
49
49
  const modifiersRef = useRef(modifiers);
50
50
  modifiersRef.current = modifiers;
51
51
 
52
52
  const handleOutput = useCallback((bytes: Uint8Array) => {
53
- xtermRef.current?.write(bytes);
53
+ terminalRef.current?.write(bytes);
54
54
  }, []);
55
55
 
56
56
  const handleReplay = useCallback((bytes: Uint8Array, frame: { replayCols: number; replayRows: number }) => {
57
- xtermRef.current?.writeReplay(bytes, frame.replayCols, frame.replayRows);
57
+ terminalRef.current?.writeReplay(bytes, frame.replayCols, frame.replayRows);
58
58
  }, []);
59
59
 
60
60
  const handleRestart = useCallback(() => {
61
- xtermRef.current?.reset();
61
+ terminalRef.current?.reset();
62
62
  }, []);
63
63
 
64
64
  const {
@@ -70,6 +70,7 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
70
70
  resize,
71
71
  input,
72
72
  restart,
73
+ reattach,
73
74
  } = useTerminal({
74
75
  root: enabled ? rootPath : undefined,
75
76
  repo: activeRepo,
@@ -112,19 +113,19 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
112
113
 
113
114
  const handleToggleModifier = useCallback((modifier: TerminalModifier) => {
114
115
  setModifiers((previous) => ({ ...previous, [modifier]: !previous[modifier] }));
115
- xtermRef.current?.focus();
116
+ terminalRef.current?.focus();
116
117
  }, []);
117
118
 
118
119
  const handleKey = useCallback((id: TerminalKeyId) => {
119
120
  const sequence = resolveKeySequence(id, {
120
- applicationCursorKeys: xtermRef.current?.applicationCursorKeys() ?? false,
121
+ applicationCursorKeys: terminalRef.current?.applicationCursorKeys() ?? false,
121
122
  modifiers: modifiersRef.current,
122
123
  });
123
124
  if (!sequence) return;
124
125
  input(encoder.encode(sequence));
125
126
  setModifiers(NO_MODIFIERS);
126
127
  // Keep the OS keyboard where it was; a key bar tap must not dismiss it.
127
- xtermRef.current?.focus();
128
+ terminalRef.current?.focus();
128
129
  }, [input]);
129
130
 
130
131
  /**
@@ -134,7 +135,7 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
134
135
  * instead of flashing success over an untouched clipboard.
135
136
  */
136
137
  const handleCopy = useCallback(async () => {
137
- const selection = xtermRef.current?.getSelection() ?? '';
138
+ const selection = terminalRef.current?.getSelection() ?? '';
138
139
  if (!selection) return false;
139
140
  return copyToClipboard(selection);
140
141
  }, []);
@@ -142,27 +143,29 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
142
143
  const handlePaste = useCallback(async () => {
143
144
  const text = await readClipboardText();
144
145
  if (text === null || text.length === 0) return false;
145
- // Through xterm's own paste, so a bracketed-paste shell gets its markers.
146
- xtermRef.current?.paste(text);
147
- xtermRef.current?.focus();
146
+ // Through the terminal's own paste, so a bracketed-paste shell gets its markers.
147
+ terminalRef.current?.paste(text);
148
+ terminalRef.current?.focus();
148
149
  return true;
149
150
  }, []);
150
151
 
151
- const handleBinaryInput = useCallback((data: string) => {
152
- const bytes = new Uint8Array(data.length);
153
- for (let i = 0; i < data.length; i += 1) bytes[i] = data.charCodeAt(i) & 0xff;
152
+ const handleBinaryInput = useCallback((bytes: Uint8Array) => {
154
153
  input(bytes);
155
154
  }, [input]);
156
155
 
157
156
  const handleQuickAction = useCallback((command: string) => {
158
157
  input(encoder.encode(`${command}\r`));
159
- xtermRef.current?.focus();
158
+ terminalRef.current?.focus();
160
159
  }, [input]);
161
160
 
162
161
  const handleRestartClick = useCallback(() => {
163
162
  restart();
164
163
  }, [restart]);
165
164
 
165
+ const handleReattach = useCallback(() => {
166
+ reattach();
167
+ }, [reattach]);
168
+
166
169
  if (!enabled) {
167
170
  return (
168
171
  <div className={`flex flex-col h-full bg-paper items-center justify-center text-ink/40 ${className}`}>
@@ -175,6 +178,7 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
175
178
  <div
176
179
  ref={rootRef}
177
180
  className={`flex flex-col h-full w-full bg-paper text-ink overflow-hidden ${className}`}
181
+ aria-hidden={!active}
178
182
  // The soft keyboard covers the bottom of the visual viewport without
179
183
  // shrinking the layout one, so the key bar would sit behind the keys the
180
184
  // user is typing on. Lifting by the panel's actual overlap with the
@@ -207,15 +211,15 @@ export function TerminalPanel({ className = '', enabled = true, rootPath, showHe
207
211
  </div>
208
212
  )}
209
213
 
210
- {/* Real-time Xterm Terminal Canvas, driven by the PTY socket */}
214
+ {/* Real-time terminal canvas, driven by the PTY socket */}
211
215
  <div className="flex-1 w-full min-h-0 bg-canvas overflow-hidden">
212
- <RealtimeXtermView
213
- ref={xtermRef}
216
+ <RealtimeTerminalView
217
+ ref={terminalRef}
214
218
  onInput={handleInput}
215
219
  onBinaryInput={handleBinaryInput}
216
220
  onReady={handleReady}
217
221
  onGridChange={handleGridChange}
218
- visible={active}
222
+ onReattach={handleReattach}
219
223
  />
220
224
  </div>
221
225