@histoire/cli 0.0.0-stage → 1.0.0-beta.2

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 (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/cli.d.ts +9 -0
  4. package/dist/cli.js +88 -0
  5. package/dist/commands/dev.d.ts +44 -0
  6. package/dist/commands/dev.js +115 -0
  7. package/dist/commands/host.d.ts +66 -0
  8. package/dist/commands/host.js +1 -0
  9. package/dist/commands/screenshot-setup-args.d.ts +4 -0
  10. package/dist/commands/screenshot-setup-args.js +35 -0
  11. package/dist/commands/signal-guard.d.ts +29 -0
  12. package/dist/commands/signal-guard.js +52 -0
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.js +1 -0
  15. package/dist/terminal/actions.d.ts +51 -0
  16. package/dist/terminal/actions.js +60 -0
  17. package/dist/terminal/banner.d.ts +19 -0
  18. package/dist/terminal/banner.js +48 -0
  19. package/dist/terminal/bridge.d.ts +58 -0
  20. package/dist/terminal/bridge.js +103 -0
  21. package/dist/terminal/clipboard.d.ts +46 -0
  22. package/dist/terminal/clipboard.js +85 -0
  23. package/dist/terminal/diagnostics/attach.d.ts +9 -0
  24. package/dist/terminal/diagnostics/attach.js +46 -0
  25. package/dist/terminal/diagnostics/client.d.ts +12 -0
  26. package/dist/terminal/diagnostics/client.js +19 -0
  27. package/dist/terminal/diagnostics/lines.d.ts +17 -0
  28. package/dist/terminal/diagnostics/lines.js +61 -0
  29. package/dist/terminal/dispatch.d.ts +28 -0
  30. package/dist/terminal/dispatch.js +52 -0
  31. package/dist/terminal/feedback.d.ts +14 -0
  32. package/dist/terminal/feedback.js +27 -0
  33. package/dist/terminal/history/bounded.d.ts +37 -0
  34. package/dist/terminal/history/bounded.js +54 -0
  35. package/dist/terminal/host-extras.d.ts +14 -0
  36. package/dist/terminal/host-extras.js +26 -0
  37. package/dist/terminal/info/client.d.ts +20 -0
  38. package/dist/terminal/info/client.js +25 -0
  39. package/dist/terminal/info/generation-client.d.ts +33 -0
  40. package/dist/terminal/info/generation-client.js +32 -0
  41. package/dist/terminal/info/lines.d.ts +19 -0
  42. package/dist/terminal/info/lines.js +33 -0
  43. package/dist/terminal/info/network.d.ts +17 -0
  44. package/dist/terminal/info/network.js +48 -0
  45. package/dist/terminal/info/qr.d.ts +7 -0
  46. package/dist/terminal/info/qr.js +14 -0
  47. package/dist/terminal/keys.d.ts +44 -0
  48. package/dist/terminal/keys.js +60 -0
  49. package/dist/terminal/logs/browser-options.d.ts +9 -0
  50. package/dist/terminal/logs/browser-options.js +19 -0
  51. package/dist/terminal/navigation/browser.d.ts +69 -0
  52. package/dist/terminal/navigation/browser.js +193 -0
  53. package/dist/terminal/navigation/list.d.ts +53 -0
  54. package/dist/terminal/navigation/list.js +104 -0
  55. package/dist/terminal/navigation/search.d.ts +22 -0
  56. package/dist/terminal/navigation/search.js +44 -0
  57. package/dist/terminal/output/decoder.d.ts +24 -0
  58. package/dist/terminal/output/decoder.js +63 -0
  59. package/dist/terminal/output/history.d.ts +43 -0
  60. package/dist/terminal/output/history.js +21 -0
  61. package/dist/terminal/output/pipeline.d.ts +33 -0
  62. package/dist/terminal/output/pipeline.js +59 -0
  63. package/dist/terminal/output/sanitize.d.ts +32 -0
  64. package/dist/terminal/output/sanitize.js +142 -0
  65. package/dist/terminal/panel-model.d.ts +20 -0
  66. package/dist/terminal/panel-model.js +38 -0
  67. package/dist/terminal/panel.d.ts +30 -0
  68. package/dist/terminal/panel.js +53 -0
  69. package/dist/terminal/plain.d.ts +29 -0
  70. package/dist/terminal/plain.js +68 -0
  71. package/dist/terminal/progress/format.d.ts +28 -0
  72. package/dist/terminal/progress/format.js +77 -0
  73. package/dist/terminal/progress/state.d.ts +71 -0
  74. package/dist/terminal/progress/state.js +150 -0
  75. package/dist/terminal/protocol/catalog.d.ts +143 -0
  76. package/dist/terminal/protocol/catalog.js +61 -0
  77. package/dist/terminal/protocol/core.d.ts +117 -0
  78. package/dist/terminal/protocol/core.js +98 -0
  79. package/dist/terminal/protocol/diagnostics.d.ts +79 -0
  80. package/dist/terminal/protocol/diagnostics.js +31 -0
  81. package/dist/terminal/protocol/index.d.ts +22 -0
  82. package/dist/terminal/protocol/index.js +1 -0
  83. package/dist/terminal/protocol/progress.d.ts +67 -0
  84. package/dist/terminal/protocol/progress.js +52 -0
  85. package/dist/terminal/protocol/requests.d.ts +30 -0
  86. package/dist/terminal/protocol/requests.js +13 -0
  87. package/dist/terminal/protocol/session.d.ts +55 -0
  88. package/dist/terminal/protocol/session.js +28 -0
  89. package/dist/terminal/protocol/tests.d.ts +212 -0
  90. package/dist/terminal/protocol/tests.js +87 -0
  91. package/dist/terminal/protocol/watch.d.ts +60 -0
  92. package/dist/terminal/protocol/watch.js +40 -0
  93. package/dist/terminal/requests/browser-options.d.ts +8 -0
  94. package/dist/terminal/requests/browser-options.js +24 -0
  95. package/dist/terminal/requests/history.d.ts +30 -0
  96. package/dist/terminal/requests/history.js +53 -0
  97. package/dist/terminal/retained.d.ts +27 -0
  98. package/dist/terminal/retained.js +21 -0
  99. package/dist/terminal/session-types.d.ts +76 -0
  100. package/dist/terminal/session-types.js +1 -0
  101. package/dist/terminal/session.d.ts +8 -0
  102. package/dist/terminal/session.js +282 -0
  103. package/dist/terminal/shutdown.d.ts +12 -0
  104. package/dist/terminal/shutdown.js +30 -0
  105. package/dist/terminal/stories/client.d.ts +26 -0
  106. package/dist/terminal/stories/client.js +28 -0
  107. package/dist/terminal/stories/handoff.d.ts +39 -0
  108. package/dist/terminal/stories/handoff.js +40 -0
  109. package/dist/terminal/stories/paged.d.ts +70 -0
  110. package/dist/terminal/stories/paged.js +137 -0
  111. package/dist/terminal/stories/render.d.ts +39 -0
  112. package/dist/terminal/stories/render.js +94 -0
  113. package/dist/terminal/stories/state.d.ts +93 -0
  114. package/dist/terminal/stories/state.js +191 -0
  115. package/dist/terminal/stories/target.d.ts +24 -0
  116. package/dist/terminal/stories/target.js +29 -0
  117. package/dist/terminal/style.d.ts +45 -0
  118. package/dist/terminal/style.js +82 -0
  119. package/dist/terminal/support.d.ts +53 -0
  120. package/dist/terminal/support.js +66 -0
  121. package/dist/terminal/surface.d.ts +41 -0
  122. package/dist/terminal/surface.js +200 -0
  123. package/dist/terminal/tests/client.d.ts +21 -0
  124. package/dist/terminal/tests/client.js +12 -0
  125. package/dist/terminal/tests/console.d.ts +95 -0
  126. package/dist/terminal/tests/console.js +202 -0
  127. package/dist/terminal/tests/format.d.ts +18 -0
  128. package/dist/terminal/tests/format.js +55 -0
  129. package/dist/terminal/tests/header.d.ts +16 -0
  130. package/dist/terminal/tests/header.js +90 -0
  131. package/dist/terminal/tests/reporter.d.ts +17 -0
  132. package/dist/terminal/tests/reporter.js +99 -0
  133. package/dist/terminal/tests/results.d.ts +44 -0
  134. package/dist/terminal/tests/results.js +104 -0
  135. package/dist/terminal/tests/scope.d.ts +25 -0
  136. package/dist/terminal/tests/scope.js +25 -0
  137. package/dist/terminal/tests/session.d.ts +11 -0
  138. package/dist/terminal/tests/session.js +24 -0
  139. package/dist/terminal/tests/state.d.ts +57 -0
  140. package/dist/terminal/tests/state.js +134 -0
  141. package/dist/terminal/views/clear-history.d.ts +6 -0
  142. package/dist/terminal/views/clear-history.js +10 -0
  143. package/dist/terminal/views/error.d.ts +8 -0
  144. package/dist/terminal/views/error.js +24 -0
  145. package/dist/terminal/views/frame.d.ts +20 -0
  146. package/dist/terminal/views/frame.js +23 -0
  147. package/dist/terminal/views/help.d.ts +3 -0
  148. package/dist/terminal/views/help.js +32 -0
  149. package/dist/terminal/views/index.d.ts +6 -0
  150. package/dist/terminal/views/index.js +13 -0
  151. package/dist/terminal/views/logs.d.ts +3 -0
  152. package/dist/terminal/views/logs.js +7 -0
  153. package/dist/terminal/views/registry.d.ts +114 -0
  154. package/dist/terminal/views/registry.js +40 -0
  155. package/dist/terminal/views/requests.d.ts +8 -0
  156. package/dist/terminal/views/requests.js +15 -0
  157. package/dist/terminal/views/session.d.ts +9 -0
  158. package/dist/terminal/views/session.js +133 -0
  159. package/dist/terminal/views/stories.d.ts +9 -0
  160. package/dist/terminal/views/stories.js +172 -0
  161. package/dist/terminal/views/tests.d.ts +9 -0
  162. package/dist/terminal/views/tests.js +105 -0
  163. package/dist/terminal/watch/client.d.ts +12 -0
  164. package/dist/terminal/watch/client.js +7 -0
  165. package/dist/terminal/watch/controller.d.ts +30 -0
  166. package/dist/terminal/watch/controller.js +157 -0
  167. package/dist/terminal/watch/format.d.ts +15 -0
  168. package/dist/terminal/watch/format.js +37 -0
  169. package/dist/terminal/watch/session.d.ts +17 -0
  170. package/dist/terminal/watch/session.js +12 -0
  171. package/dist/terminal/width.d.ts +24 -0
  172. package/dist/terminal/width.js +171 -0
  173. package/dist/workbench-url.d.ts +30 -0
  174. package/dist/workbench-url.js +55 -0
  175. package/package.json +54 -3
@@ -0,0 +1,172 @@
1
+ import { createListNavigation } from '../navigation/list.js';
2
+ import { createSearchInput } from '../navigation/search.js';
3
+ import { sanitizeText } from '../output/sanitize.js';
4
+ import { getTestTargetHandoff } from '../stories/handoff.js';
5
+ import { catalogSegment, emptyStoriesText, storiesStatus, storyRow, variantRow, variantsStatus } from '../stories/render.js';
6
+ import { createStoriesState } from '../stories/state.js';
7
+ import { resolveTargetUrl } from '../stories/target.js';
8
+ import { fitWidth } from '../width.js';
9
+ import { renderViewFrame } from './frame.js';
10
+ /** Rows from the end of the loaded list at which the next page is requested. */
11
+ const LOAD_AHEAD = 10;
12
+ /**
13
+ * `p`: browse the canonical catalog. Enter on a story lists its variants, Enter on a variant
14
+ * (or on a story without variants) opens it in the workbench; `o` opens the selection, `y`
15
+ * copies its address, `t` opens the tests screen on the exact target, `/` searches the whole
16
+ * catalog. Selection is kept by ID through revisions and restarts; a target the catalog no
17
+ * longer confirms is not actionable.
18
+ */
19
+ export const createStoriesView = (host) => {
20
+ const state = createStoriesState({ bridge: host.bridge, progress: host.progress, changed: () => host.requestRender() });
21
+ const handoff = getTestTargetHandoff(host);
22
+ const stories = createListNavigation({ id: story => story.id });
23
+ const variants = createListNavigation({ id: variant => variant.id });
24
+ const search = createSearchInput();
25
+ let level = 'stories';
26
+ /** Story whose variant selection `variants` holds; another story starts at its first variant. */
27
+ let variantsOf;
28
+ state.keepVisible(() => stories.selectedId(), () => variants.selectedId(), id => stories.select(id));
29
+ host.addPanelSegment(() => catalogSegment(state.view().catalog));
30
+ /** Pushes loaded rows into the navigation; selection follows IDs. */
31
+ function sync() {
32
+ stories.setItems(state.view().stories);
33
+ variants.setItems(state.variants().variants);
34
+ }
35
+ /** Story under the cursor, only while the current catalog confirms it. */
36
+ function story() {
37
+ sync();
38
+ return stories.selectedItem();
39
+ }
40
+ /** Selected story/variant with what is needed to act on it, or why not. */
41
+ function target() {
42
+ const selected = story();
43
+ if (!selected)
44
+ return 'Selected story is not in the catalog';
45
+ if (level === 'stories')
46
+ return { story: selected };
47
+ const variant = variants.selectedItem();
48
+ return variant ? { story: selected, variant } : 'Selected variant is not in the catalog';
49
+ }
50
+ /** Opens the target in the workbench or says why it cannot be opened. */
51
+ async function open() {
52
+ const selection = target();
53
+ if (typeof selection === 'string')
54
+ return host.notify(selection);
55
+ const resolved = await resolveTargetUrl({ publicUrl: host.url(), workbench: state.view().workbench, ...selection });
56
+ if ('problem' in resolved)
57
+ return host.notify(resolved.problem);
58
+ host.notify(`Opening ${selection.variant?.title ?? selection.story.title}`);
59
+ void host.openBrowser(resolved.url).catch(error => host.notify(`Failed: ${error instanceof Error ? error.message : String(error)}`));
60
+ }
61
+ /** Copies the workbench address of the selection. */
62
+ async function copy() {
63
+ const selection = target();
64
+ if (typeof selection === 'string')
65
+ return host.notify(selection);
66
+ const resolved = await resolveTargetUrl({ publicUrl: host.url(), workbench: state.view().workbench, ...selection });
67
+ if ('problem' in resolved)
68
+ return host.notify(resolved.problem);
69
+ void host.copy(resolved.url).then(result => host.notify(result.ok ? `Copied address${result.note ? ` (${result.note})` : ''}` : `Copy unavailable: ${result.reason}. Address is not shown`));
70
+ }
71
+ /** Hands the exact story or variant to the tests screen and runs it. Executable targets only. */
72
+ function test() {
73
+ const selection = target();
74
+ if (typeof selection === 'string')
75
+ return host.notify(selection);
76
+ const { revision, generation } = state.view();
77
+ if (!revision || !generation)
78
+ return host.notify('Catalog is not ready');
79
+ if (selection.story.ambiguous || selection.variant?.ambiguous)
80
+ return host.notify('Target ID is shared, it cannot be tested');
81
+ if (selection.story.docsOnly || selection.story.variantCount === 0)
82
+ return host.notify('This story has no variants to test');
83
+ const label = selection.variant ? `${selection.story.title} / ${selection.variant.title}` : selection.story.title;
84
+ handoff.set({ target: selection.variant ? { scope: 'variant', storyId: selection.story.id, variantId: selection.variant.id } : { scope: 'story', storyId: selection.story.id }, label, storyLabel: selection.story.title, revision, generation });
85
+ // The handoff retargets the tests scope synchronously, so the run below uses exactly this target.
86
+ host.openView('t');
87
+ void host.tests.run().then(result => host.notify('problem' in result ? result.problem : 'Tests queued'));
88
+ }
89
+ /** Enter: story with variants lists them; anything else opens in the workbench. */
90
+ function activate() {
91
+ const selected = story();
92
+ if (level === 'variants' || !selected || selected.ambiguous || selected.docsOnly || selected.variantCount === 0)
93
+ return void open();
94
+ level = 'variants';
95
+ if (variantsOf !== selected.id)
96
+ variants.select(undefined);
97
+ variantsOf = selected.id;
98
+ state.openStory(selected.id);
99
+ }
100
+ /** Requests the next page when the cursor nears the end of what is loaded. */
101
+ function loadAhead() {
102
+ const view = state.view();
103
+ const loaded = level === 'stories' ? view.stories : state.variants().variants;
104
+ const index = loaded.findIndex(item => item.id === (level === 'stories' ? stories : variants).selectedId());
105
+ if (index >= loaded.length - LOAD_AHEAD)
106
+ void (level === 'stories' ? state.moreStories() : state.moreVariants());
107
+ }
108
+ return {
109
+ id: 'stories',
110
+ shortcut: 'p',
111
+ title: 'Stories',
112
+ enter() {
113
+ level = 'stories';
114
+ state.openStory(undefined);
115
+ state.refresh();
116
+ },
117
+ leave() {
118
+ level = 'stories';
119
+ state.openStory(undefined);
120
+ },
121
+ capturesInput: () => level === 'stories' && search.active(),
122
+ handleKey(key) {
123
+ if (level === 'stories' && search.handleKey(key)) {
124
+ state.search(search.applied());
125
+ return true;
126
+ }
127
+ if (key.name === 'escape' && level === 'variants') {
128
+ level = 'stories';
129
+ state.openStory(undefined);
130
+ return true;
131
+ }
132
+ sync();
133
+ if ((level === 'stories' ? stories : variants).handleKey(key, Math.max(1, host.size().rows - 5))) {
134
+ loadAhead();
135
+ return true;
136
+ }
137
+ if (key.name === 'return')
138
+ activate();
139
+ else if (key.char === 'o')
140
+ void open();
141
+ else if (key.char === 'y')
142
+ void copy();
143
+ else if (key.char === 't')
144
+ test();
145
+ else if (key.char === 'u')
146
+ state.refresh();
147
+ else
148
+ return false;
149
+ return true;
150
+ },
151
+ render(size) {
152
+ sync();
153
+ const view = state.view();
154
+ const opened = state.variants();
155
+ const selectedId = (level === 'stories' ? stories : variants).selectedId();
156
+ const header = level === 'stories' ? storiesStatus(view) : variantsStatus(stories.selectedItem(), opened, view.catalog?.updating === true);
157
+ const height = Math.max(1, size.rows - 4);
158
+ const rows = level === 'stories'
159
+ ? stories.window(height).items.map(item => storyRow(item, item.id === selectedId, size.columns))
160
+ : variants.window(height).items.map(item => variantRow(item, item.id === selectedId, size.columns));
161
+ const body = [header, ...rows];
162
+ if (!rows.length)
163
+ body.push(` ${level === 'stories' ? emptyStoriesText(view, selectedId !== undefined) : opened.status === 'failed' ? `Variants unavailable: ${opened.problem ?? 'unknown reason'}` : opened.status === 'ready' ? 'No variants' : 'Loading variants'}`);
164
+ else if (selectedId !== undefined && (level === 'stories' ? stories : variants).selectedItem() === undefined)
165
+ body.push(` Selected ${level === 'stories' ? 'story' : 'variant'} is not in the catalog`);
166
+ const footer = search.active()
167
+ ? `/${search.text()}▏`
168
+ : fitWidth(level === 'stories' ? 'Up/Down · Enter variants · o open · y copy address · t test · / search · u refresh · Esc back' : 'Up/Down · Enter open · o open · y copy address · t test · u refresh · Esc stories', size.columns);
169
+ return renderViewFrame({ title: level === 'stories' ? 'Stories' : `Stories · ${sanitizeText(stories.selectedItem()?.title ?? stories.selectedId() ?? '')}`, body, footer, ...size });
170
+ },
171
+ };
172
+ };
@@ -0,0 +1,9 @@
1
+ import type { TerminalViewFactory } from './registry.js';
2
+ /**
3
+ * `t`: run and inspect browser tests. Left/Right pick All, Story or Variant (the latter two
4
+ * come from the story browser's `t` and are disabled while unresolved), `r` runs the
5
+ * selected scope, Enter opens the selected case, `s` stops, `f` filters failures, `[`/`]` step through retained runs by
6
+ * ID. Cases of the shown run are paged and use the shared list/search/detail/copy browser;
7
+ * totals, uncollected stories and run errors come from the summary, not from loaded pages.
8
+ */
9
+ export declare const createTestsView: TerminalViewFactory;
@@ -0,0 +1,105 @@
1
+ import { createHistoryBrowser } from '../navigation/browser.js';
2
+ import { buildTestsHeader, describeEmptyResults, describeResultsStatus, TESTS_FOOTER } from '../tests/header.js';
3
+ import { createResultsList, describeCase } from '../tests/results.js';
4
+ /** Rows from the end of the loaded cases at which the next page is requested. */
5
+ const LOAD_AHEAD = 10;
6
+ /** Row label of a case state. */
7
+ const LABELS = { failed: 'FAIL', passed: 'pass', skipped: 'skip' };
8
+ /**
9
+ * `t`: run and inspect browser tests. Left/Right pick All, Story or Variant (the latter two
10
+ * come from the story browser's `t` and are disabled while unresolved), `r` runs the
11
+ * selected scope, Enter opens the selected case, `s` stops, `f` filters failures, `[`/`]` step through retained runs by
12
+ * ID. Cases of the shown run are paged and use the shared list/search/detail/copy browser;
13
+ * totals, uncollected stories and run errors come from the summary, not from loaded pages.
14
+ */
15
+ export const createTestsView = (host) => {
16
+ const { tests } = host;
17
+ const results = createResultsList(tests);
18
+ host.addPanelSegment(() => tests.segment());
19
+ const browser = createHistoryBrowser({
20
+ host,
21
+ title: 'Tests',
22
+ noun: 'cases',
23
+ items: () => results.rows(),
24
+ id: row => row.id,
25
+ rank: row => row.rank,
26
+ text: row => describeCase(row.case),
27
+ label: row => LABELS[row.case.state],
28
+ tone: row => row.case.state === 'failed' ? 'error' : row.case.state === 'skipped' ? 'dim' : undefined,
29
+ omitted: () => tests.viewed()?.operation.summary?.omittedCases ?? 0,
30
+ subscribe: results.subscribe,
31
+ header: () => buildTestsHeader(tests, results),
32
+ status: shown => describeResultsStatus(tests, results, shown),
33
+ empty: () => describeEmptyResults(tests, results),
34
+ follow: false,
35
+ footer: TESTS_FOOTER,
36
+ });
37
+ let unsubscribe;
38
+ /** Requests the next page when the cursor nears the end of what is loaded. */
39
+ function loadAhead() {
40
+ const rows = results.rows();
41
+ const index = rows.findIndex(row => row.id === browser.navigation.selectedId());
42
+ if (results.hasMore() && index >= rows.length - LOAD_AHEAD)
43
+ results.loadMore();
44
+ }
45
+ /** `r`: submits the selected scope and shows why nothing was admitted. */
46
+ function run() {
47
+ void tests.run().then(result => 'problem' in result ? host.notify(result.problem) : host.notify('Tests queued'));
48
+ }
49
+ /** `s`: stops terminal work and says what was asked. */
50
+ function stop() {
51
+ void tests.stop().then(host.notify);
52
+ }
53
+ /** Move the scope or tell why it cannot move. */
54
+ function moveScope(direction) {
55
+ if (tests.moveScope(direction))
56
+ return;
57
+ host.notify(tests.runnable().available ? 'No other scope available' : (tests.runnable().reason ?? 'Scope unavailable'));
58
+ }
59
+ /** Screen keys by key name (arrows) or typed character; Enter falls through to the browser, which opens the selected case. */
60
+ const keyActions = {
61
+ 'left': () => moveScope(-1),
62
+ 'right': () => moveScope(1),
63
+ 'r': run,
64
+ 's': stop,
65
+ 'f': () => results.setFailuresOnly(!results.failuresOnly()),
66
+ 'w': () => void tests.toggleWatch().then(host.notify),
67
+ '[': () => tests.moveViewed(1),
68
+ ']': () => tests.moveViewed(-1),
69
+ };
70
+ return {
71
+ id: 'tests',
72
+ shortcut: 't',
73
+ title: 'Tests',
74
+ enter() {
75
+ results.sync();
76
+ browser.enter();
77
+ // Operation events, progress, scope and generation changes all repaint the screen.
78
+ unsubscribe = tests.subscribe(() => {
79
+ results.sync();
80
+ host.requestRender();
81
+ });
82
+ },
83
+ leave() {
84
+ unsubscribe?.();
85
+ unsubscribe = undefined;
86
+ browser.leave();
87
+ },
88
+ capturesInput: browser.capturesInput,
89
+ handleKey(key) {
90
+ // Detail and search own every key, including the ones used here.
91
+ if (browser.detailOpen() || browser.search.active())
92
+ return browser.handleKey(key);
93
+ const action = Object.hasOwn(keyActions, key.char ?? key.name) ? keyActions[key.char ?? key.name] : undefined;
94
+ if (action) {
95
+ action();
96
+ return true;
97
+ }
98
+ if (!browser.handleKey(key))
99
+ return false;
100
+ loadAhead();
101
+ return true;
102
+ },
103
+ render: size => browser.render(size),
104
+ };
105
+ };
@@ -0,0 +1,12 @@
1
+ import type { TerminalBridge } from '../bridge.js';
2
+ import type { WatchSetArgs, WatchStateDto } from '../protocol/watch.js';
3
+ /** Typed wrapper of the `watch.*` operations. */
4
+ export interface WatchClient {
5
+ /** Enables, retargets or disables watching in the current generation; idempotent. */
6
+ set: (args: WatchSetArgs) => Promise<WatchStateDto>;
7
+ }
8
+ /**
9
+ * Creates the typed client. Pure sugar over `bridge.send`; holds no state.
10
+ * @param bridge Parent bridge (or any object with a compatible `send`).
11
+ */
12
+ export declare function createWatchClient(bridge: Pick<TerminalBridge, 'send'>): WatchClient;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Creates the typed client. Pure sugar over `bridge.send`; holds no state.
3
+ * @param bridge Parent bridge (or any object with a compatible `send`).
4
+ */
5
+ export function createWatchClient(bridge) {
6
+ return { set: args => bridge.send('watch.set', args) };
7
+ }
@@ -0,0 +1,30 @@
1
+ import type { TerminalBridge } from '../bridge.js';
2
+ import type { ProgressState } from '../progress/state.js';
3
+ import type { TestsConsole, TestsWatchControl } from '../tests/console.js';
4
+ import type { WatchClient } from './client.js';
5
+ /** Inputs of the session-lifetime watch controller. */
6
+ export interface WatchControllerOptions {
7
+ /** Event source for `watch.state`. */
8
+ bridge: Pick<TerminalBridge, 'subscribe'>;
9
+ /** Typed `watch.set` access. */
10
+ client: WatchClient;
11
+ /** Generation mirror: sync waits for a ready generation and repeats for every new one. */
12
+ progress: Pick<ProgressState, 'snapshot' | 'subscribe'>;
13
+ /** Console owning scope selection, results and stop hooks. */
14
+ tests: TestsConsole;
15
+ /** Prints one line (plain mode) or shows transient feedback. */
16
+ report: (line: string) => void;
17
+ /** Whether automatic status lines should be printed (plain mode); the TUI shows state in its panel instead. */
18
+ plain: () => boolean;
19
+ /** `--test-watch`: start with the whole book. */
20
+ initial?: boolean;
21
+ }
22
+ /**
23
+ * Session-lifetime owner of the watch preference and scope. The preference only
24
+ * describes what the user wants; the child scheduler of the current generation
25
+ * is the only authority that runs or cancels anything. Every new ready
26
+ * generation is told the preference once (child state is generation-scoped),
27
+ * so a config restart keeps watching and runs the retained scope once.
28
+ * @param options Bridge, generation mirror, console and output.
29
+ */
30
+ export declare function createWatchController(options: WatchControllerOptions): TestsWatchControl;
@@ -0,0 +1,157 @@
1
+ import { isWatchState } from '../protocol/watch.js';
2
+ import { describeTarget } from '../tests/format.js';
3
+ import { followOperation } from '../tests/reporter.js';
4
+ import { describePhase, describeWatchLine, describeWatchSegment, sameScope } from './format.js';
5
+ /**
6
+ * Session-lifetime owner of the watch preference and scope. The preference only
7
+ * describes what the user wants; the child scheduler of the current generation
8
+ * is the only authority that runs or cancels anything. Every new ready
9
+ * generation is told the preference once (child state is generation-scoped),
10
+ * so a config restart keeps watching and runs the retained scope once.
11
+ * @param options Bridge, generation mirror, console and output.
12
+ */
13
+ export function createWatchController(options) {
14
+ const { tests, progress } = options;
15
+ let preference = { enabled: options.initial === true, scope: { scope: 'all' } };
16
+ /** What each generation was last told successfully (`off` is the child default). */
17
+ const told = new Map();
18
+ const inflight = new Map();
19
+ const followed = new Set();
20
+ let observed;
21
+ let lastLine;
22
+ let lastRuntime;
23
+ const listeners = new Set();
24
+ const notify = () => {
25
+ for (const listener of [...listeners]) {
26
+ try {
27
+ listener();
28
+ }
29
+ catch { }
30
+ }
31
+ };
32
+ /** State the child reported for the current generation only. */
33
+ const current = () => {
34
+ const seen = observed;
35
+ if (!seen)
36
+ return undefined;
37
+ return seen.generation === progress.snapshot().generation ? seen.state : undefined;
38
+ };
39
+ const wanted = () => preference.enabled ? JSON.stringify(preference.scope) : 'off';
40
+ /** Prints one automatic line in plain mode, once per distinct text. */
41
+ function say(line) {
42
+ if (!line || line === lastLine || !options.plain())
43
+ return;
44
+ lastLine = line;
45
+ options.report(line);
46
+ }
47
+ /** Records a state of the current generation and announces it. */
48
+ function accept(generation, state) {
49
+ if (generation !== progress.snapshot().generation)
50
+ return;
51
+ observed = { generation, state };
52
+ if (preference.enabled && state.enabled) {
53
+ const entry = state.operationId ? tests.state.get(state.operationId) : undefined;
54
+ say(describeWatchLine(state, preference.scope, entry ? describeTarget(entry.operation.target) : undefined));
55
+ // Plain mode has no panel: each run is followed to its summary like a manual one.
56
+ if (state.operationId && !followed.has(state.operationId) && options.plain()) {
57
+ followed.add(state.operationId);
58
+ void followOperation(tests, state.operationId, options.report);
59
+ }
60
+ }
61
+ notify();
62
+ }
63
+ /** Tells the ready generation what is wanted; repeats only if the wish changed meanwhile. */
64
+ async function sync() {
65
+ const snapshot = progress.snapshot();
66
+ const { generation } = snapshot;
67
+ if (snapshot.status !== 'ready' || !generation)
68
+ return;
69
+ const key = wanted();
70
+ if ((told.get(generation) ?? 'off') === key || inflight.get(generation) === key)
71
+ return;
72
+ inflight.set(generation, key);
73
+ try {
74
+ const state = await options.client.set(preference.enabled ? { enabled: true, scope: preference.scope } : { enabled: false });
75
+ told.set(generation, key);
76
+ if (told.size > 64)
77
+ told.delete(told.keys().next().value);
78
+ if (isWatchState(state))
79
+ accept(generation, state);
80
+ }
81
+ catch (error) {
82
+ say(`Watch could not be updated: ${error instanceof Error ? error.message : String(error)}`);
83
+ }
84
+ finally {
85
+ inflight.delete(generation);
86
+ }
87
+ if (wanted() !== key)
88
+ await sync();
89
+ }
90
+ /** Notes, in plain mode, that the runtime itself is between generations. */
91
+ function noteRuntime() {
92
+ const { status, generation } = progress.snapshot();
93
+ if (!preference.enabled || status === 'ready' || status === 'closed') {
94
+ lastRuntime = undefined;
95
+ return;
96
+ }
97
+ const key = `${status}:${generation}`;
98
+ if (key === lastRuntime)
99
+ return;
100
+ lastRuntime = key;
101
+ if (status === 'failed')
102
+ say('Watch paused: the runtime failed to start, it resumes when the problem is fixed');
103
+ else if (status === 'restarting')
104
+ say('Watch: waiting for the runtime to restart');
105
+ }
106
+ options.bridge.subscribe(({ generation, event, data }) => {
107
+ if (event === 'watch.state' && isWatchState(data))
108
+ accept(generation, data);
109
+ });
110
+ progress.subscribe(() => {
111
+ noteRuntime();
112
+ void sync();
113
+ notify();
114
+ });
115
+ /** Applies a new preference and tells the runtime if it is ready. */
116
+ function prefer(enabled, scope) {
117
+ preference = { enabled, scope };
118
+ lastLine = undefined;
119
+ notify();
120
+ return sync();
121
+ }
122
+ const control = {
123
+ async toggle() {
124
+ const selected = tests.runnable();
125
+ if (preference.enabled) {
126
+ // An explicitly chosen different scope retargets; the same scope switches off.
127
+ if (selected.available && selected.target && !sameScope(selected.target, preference.scope)) {
128
+ void prefer(true, selected.target);
129
+ return `Watch retargeted: ${describeTarget(selected.target)}`;
130
+ }
131
+ void prefer(false, preference.scope);
132
+ return 'Watch off';
133
+ }
134
+ if (!selected.available || !selected.target)
135
+ return selected.reason ?? 'Selected scope cannot be watched';
136
+ void prefer(true, selected.target);
137
+ return `Watch on: ${describeTarget(selected.target)}${progress.snapshot().status === 'ready' ? '' : ', starts when the runtime is ready'}`;
138
+ },
139
+ active: () => preference.enabled,
140
+ status: () => preference.enabled ? `Watch on · ${describeTarget(preference.scope)} · ${current() ? describePhase(current()) : 'waiting for the runtime'}` : undefined,
141
+ segment: () => preference.enabled ? describeWatchSegment(current()) : undefined,
142
+ subscribe(listener) {
143
+ listeners.add(listener);
144
+ return () => void listeners.delete(listener);
145
+ },
146
+ };
147
+ /** `s` / plain `stop`: watching is switched off (and the child told) before anything is cancelled. */
148
+ tests.onStop(async () => {
149
+ if (!preference.enabled)
150
+ return;
151
+ await prefer(false, preference.scope);
152
+ return 'Watch off';
153
+ });
154
+ tests.setWatchControl(control);
155
+ void sync();
156
+ return control;
157
+ }
@@ -0,0 +1,15 @@
1
+ import type { TestTarget } from '../protocol/tests.js';
2
+ import type { WatchStateDto } from '../protocol/watch.js';
3
+ /** Whether two exact scopes name the same target. */
4
+ export declare function sameScope(left: TestTarget, right: TestTarget): boolean;
5
+ /** Short word for the main panel. */
6
+ export declare function describeWatchSegment(state: WatchStateDto | undefined): string;
7
+ /** State of the scheduler in words (reason included), for the tests screen. */
8
+ export declare function describePhase(state: WatchStateDto): string;
9
+ /**
10
+ * Plain-output line announcing a watch state, or undefined when nothing is worth saying.
11
+ * @param state Latest state.
12
+ * @param scope Watched scope.
13
+ * @param running What the current run executes, when known (affected stories differ from the scope).
14
+ */
15
+ export declare function describeWatchLine(state: WatchStateDto, scope: TestTarget, running?: string): string | undefined;
@@ -0,0 +1,37 @@
1
+ import { sanitizeText } from '../output/sanitize.js';
2
+ import { describeTarget } from '../tests/format.js';
3
+ /** Whether two exact scopes name the same target. */
4
+ export function sameScope(left, right) {
5
+ return JSON.stringify(left) === JSON.stringify(right);
6
+ }
7
+ /** Short word for the main panel. */
8
+ export function describeWatchSegment(state) {
9
+ return `watch ${state && state.phase !== 'off' ? state.phase : 'starting'}`;
10
+ }
11
+ /** State of the scheduler in words (reason included), for the tests screen. */
12
+ export function describePhase(state) {
13
+ const reason = state.reason ? `: ${sanitizeText(state.reason)}` : '';
14
+ switch (state.phase) {
15
+ case 'off': return 'starting';
16
+ case 'idle': return 'waiting for changes';
17
+ case 'waiting': return `waiting${reason}`;
18
+ case 'running': return 'running';
19
+ case 'paused': return `paused${reason}`;
20
+ }
21
+ }
22
+ /**
23
+ * Plain-output line announcing a watch state, or undefined when nothing is worth saying.
24
+ * @param state Latest state.
25
+ * @param scope Watched scope.
26
+ * @param running What the current run executes, when known (affected stories differ from the scope).
27
+ */
28
+ export function describeWatchLine(state, scope, running) {
29
+ const target = describeTarget(scope);
30
+ switch (state.phase) {
31
+ case 'off': return undefined;
32
+ case 'idle': return `Watch: waiting for changes in ${target}`;
33
+ case 'waiting': return `Watch: waiting${state.reason ? `, ${sanitizeText(state.reason).replace(/^\w/, letter => letter.toLowerCase())}` : ''}`;
34
+ case 'running': return `Watch: running ${running ?? target}`;
35
+ case 'paused': return `Watch paused: ${sanitizeText(state.reason ?? 'needs attention')}`;
36
+ }
37
+ }
@@ -0,0 +1,17 @@
1
+ import type { TerminalSessionOptions } from '../session-types.js';
2
+ import type { TestsConsole } from '../tests/console.js';
3
+ /** Output hooks the session supplies. */
4
+ export interface SessionWatchOutput {
5
+ /** Prints one line (plain mode) or shows transient feedback (TUI). */
6
+ report: (line: string) => void;
7
+ /** Whether the session is in plain output mode. */
8
+ plain: () => boolean;
9
+ }
10
+ /**
11
+ * Registers the watch with the session's test console: `w`, plain `watch`, the stop hook
12
+ * and the panel text. `--test-watch` starts with the whole book and needs no input.
13
+ * @param tests Session test console.
14
+ * @param options Bridge, progress mirror and the `testWatch` flag.
15
+ * @param output Session output hooks.
16
+ */
17
+ export declare function attachSessionWatch(tests: TestsConsole, options: Pick<TerminalSessionOptions, 'bridge' | 'progress' | 'testWatch'>, output: SessionWatchOutput): void;
@@ -0,0 +1,12 @@
1
+ import { createWatchClient } from './client.js';
2
+ import { createWatchController } from './controller.js';
3
+ /**
4
+ * Registers the watch with the session's test console: `w`, plain `watch`, the stop hook
5
+ * and the panel text. `--test-watch` starts with the whole book and needs no input.
6
+ * @param tests Session test console.
7
+ * @param options Bridge, progress mirror and the `testWatch` flag.
8
+ * @param output Session output hooks.
9
+ */
10
+ export function attachSessionWatch(tests, options, output) {
11
+ createWatchController({ bridge: options.bridge, client: createWatchClient(options.bridge), progress: options.progress, tests, initial: options.testWatch === true, ...output });
12
+ }
@@ -0,0 +1,24 @@
1
+ /** Terminal cell widths without a dependency: SGR-aware, East Asian wide and emoji aware. */
2
+ /**
3
+ * Number of terminal cells one code point occupies.
4
+ * @param code Unicode code point.
5
+ */
6
+ export declare function codePointWidth(code: number): number;
7
+ /**
8
+ * Display width of text in terminal cells, ignoring SGR styling.
9
+ * @param text Text without cursor-moving controls.
10
+ */
11
+ export declare function displayWidth(text: string): number;
12
+ /**
13
+ * Truncates text to at most `columns` cells, marking the cut with an ellipsis.
14
+ * Styling stays balanced when a styled line is cut.
15
+ * @param text Single line of text.
16
+ * @param columns Cell budget.
17
+ */
18
+ export declare function fitWidth(text: string, columns: number): string;
19
+ /**
20
+ * Wraps text into lines of at most `columns` cells, breaking mid-word only when needed.
21
+ * @param text Text that may contain newlines.
22
+ * @param columns Cell budget per line.
23
+ */
24
+ export declare function wrapWidth(text: string, columns: number): string[];