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

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 +117 -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,90 @@
1
+ import { sanitizeText } from '../output/sanitize.js';
2
+ import { describeOperation, describeTarget } from './format.js';
3
+ /** Most uncollected stories and run errors listed before "+N more". */
4
+ const LISTED = 3;
5
+ /** Wording of a result page that cannot be read. */
6
+ const UNAVAILABLE = {
7
+ evicted: 'details were dropped by retention, totals are kept',
8
+ retired: 'runtime restarted before the details were loaded',
9
+ unknown: 'run is no longer tracked',
10
+ running: 'run has not finished',
11
+ };
12
+ /** Status line above the case list. */
13
+ export function describeResultsStatus(tests, results, shown) {
14
+ const entry = tests.viewed();
15
+ const summary = entry?.operation.summary;
16
+ const parts = [];
17
+ if (!entry)
18
+ return 'No run yet';
19
+ if (results.status() === 'unavailable')
20
+ parts.push(`Cases unavailable: ${UNAVAILABLE[results.reason() ?? ''] ?? results.reason()}`);
21
+ else if (results.status() === 'failed')
22
+ parts.push(`Cases unavailable: ${sanitizeText(results.reason() ?? 'read failed')}`);
23
+ else if (entry.operation.state !== 'completed' || entry.lost)
24
+ parts.push('Cases appear when the run completes');
25
+ else
26
+ parts.push(`${shown} of ${results.total()} ${results.failuresOnly() ? 'failed cases' : 'cases'}${results.hasMore() ? ', more to load' : ''}`);
27
+ if (summary?.omittedCases)
28
+ parts.push(`${summary.omittedCases} cases omitted, counted in totals`);
29
+ return `\u001B[2m${parts.join(' · ')}\u001B[22m`;
30
+ }
31
+ /** Empty-list text for the current load state. */
32
+ export function describeEmptyResults(tests, results) {
33
+ const entry = tests.viewed();
34
+ if (!entry)
35
+ return 'Press r to run the selected scope';
36
+ if (results.status() === 'loading')
37
+ return 'Loading cases';
38
+ if (entry.operation.state === 'completed' && results.status() === 'ready')
39
+ return results.failuresOnly() ? 'No failed cases' : 'No cases ran';
40
+ return 'No cases to show';
41
+ }
42
+ /**
43
+ * Lines above the case list: scope selector, admission problem, the viewed run (with its
44
+ * historical label), uncollected stories and run-level errors. Counts come from the
45
+ * summary, never from the loaded case pages.
46
+ * @param tests Console.
47
+ * @param results Results list (filter state).
48
+ */
49
+ export function buildTestsHeader(tests, results) {
50
+ const selected = tests.selectedScope();
51
+ const scopes = tests.scopeOptions().map((option) => {
52
+ const label = sanitizeText(option.scope === 'all' ? option.label : `${option.scope === 'story' ? 'Story' : 'Variant'}: ${option.label}`);
53
+ if (!option.available)
54
+ return `\u001B[2m${label}${option.scope === selected ? ` (${option.reason})` : ''}\u001B[22m`;
55
+ return option.scope === selected ? `\u001B[7m ${label} \u001B[27m` : label;
56
+ });
57
+ const lines = [`Scope ${scopes.join(' ')}`];
58
+ const watching = tests.watchStatus();
59
+ if (watching)
60
+ lines.push(sanitizeText(watching));
61
+ const problem = tests.problem();
62
+ if (problem)
63
+ lines.push(`\u001B[31m${sanitizeText(problem)}\u001B[39m`);
64
+ const entry = tests.viewed();
65
+ if (!entry)
66
+ return lines;
67
+ const { operation } = entry;
68
+ const all = tests.entries();
69
+ const position = all.findIndex(item => item.operation.id === operation.id) + 1;
70
+ const historical = tests.historical(entry);
71
+ const head = `Run ${all.length - position + 1} of ${all.length} · ${describeTarget(operation.target)} · revision ${operation.revision.slice(0, 8)}`;
72
+ lines.push(historical ? `\u001B[33mHistorical\u001B[39m · ${head} · ${historical}` : head);
73
+ lines.push(entry.lost ? 'Lost · runtime ended before the run finished' : describeOperation(operation, entry.progress));
74
+ const { summary } = operation;
75
+ if (summary) {
76
+ for (const story of summary.uncollected.slice(0, LISTED))
77
+ lines.push(`\u001B[31mUncollected\u001B[39m ${sanitizeText(story.relativePath)} · ${sanitizeText(story.error.split('\n')[0])}`);
78
+ const moreStories = summary.uncollected.length - LISTED + summary.omittedUncollected;
79
+ if (moreStories > 0)
80
+ lines.push(`+${moreStories} more uncollected stories`);
81
+ for (const error of summary.runErrors.slice(0, LISTED))
82
+ lines.push(`\u001B[31mError\u001B[39m ${sanitizeText(error.split('\n')[0])}`);
83
+ const moreErrors = summary.runErrors.length - LISTED + summary.omittedRunErrors;
84
+ if (moreErrors > 0)
85
+ lines.push(`+${moreErrors} more run errors`);
86
+ }
87
+ return lines;
88
+ }
89
+ /** Footer hint of the Tests view. */
90
+ export const TESTS_FOOTER = 'Left/Right scope · r run · s stop · w watch · Enter detail · f failures · [ ] runs · / search · Esc back';
@@ -0,0 +1,17 @@
1
+ import type { TestsConsole } from './console.js';
2
+ /**
3
+ * Follows one admitted operation in plain output: a line per lifecycle or phase change,
4
+ * then outcome, uncollected stories, run errors and named failures. Resolves when the
5
+ * operation is final or its runtime is gone. Slice 10 reuses it for scheduled runs.
6
+ * @param tests Console owning the state.
7
+ * @param operationId Admitted operation.
8
+ * @param report Line sink.
9
+ */
10
+ export declare function followOperation(tests: TestsConsole, operationId: string, report: (line: string) => void): Promise<void>;
11
+ /**
12
+ * Plain `tests`: submits the selected scope and follows it to the end. Assertion failures
13
+ * are reported, never thrown, so they cannot change the server or its exit status.
14
+ * @param tests Console.
15
+ * @param report Line sink.
16
+ */
17
+ export declare function runAndReport(tests: TestsConsole, report: (line: string) => void): Promise<void>;
@@ -0,0 +1,99 @@
1
+ import { sanitizeText } from '../output/sanitize.js';
2
+ import { TEST_FINAL_STATES } from '../protocol/tests.js';
3
+ import { describeOperation, describeTarget } from './format.js';
4
+ import { describeCase } from './results.js';
5
+ /** Failed cases listed in the plain summary before "+N more". */
6
+ const LISTED_FAILURES = 10;
7
+ /** Longest error line printed per failure. */
8
+ const ERROR_CHARS = 200;
9
+ /** Final lines of a finished entry: outcome, uncollected stories, run errors, named failures. */
10
+ async function finalLines(tests, entry) {
11
+ const { operation } = entry;
12
+ if (entry.lost)
13
+ return ['Tests lost: the runtime ended before the run finished'];
14
+ const lines = [describeOperation(operation)];
15
+ const { summary } = operation;
16
+ if (!summary)
17
+ return lines;
18
+ for (const story of summary.uncollected)
19
+ lines.push(` Uncollected ${sanitizeText(story.relativePath)}: ${sanitizeText(story.error.split('\n')[0])}`);
20
+ if (summary.omittedUncollected)
21
+ lines.push(` +${summary.omittedUncollected} more uncollected stories`);
22
+ for (const error of summary.runErrors)
23
+ lines.push(` Error: ${sanitizeText(error.split('\n')[0]).slice(0, ERROR_CHARS)}`);
24
+ if (summary.omittedRunErrors)
25
+ lines.push(` +${summary.omittedRunErrors} more run errors`);
26
+ if (!summary.failed)
27
+ return lines;
28
+ try {
29
+ const page = await tests.state.results(operation.id, { failedOnly: true });
30
+ if (page.unavailable)
31
+ return [...lines, ` Failed case details unavailable (${page.unavailable})`];
32
+ for (const failed of page.cases.slice(0, LISTED_FAILURES)) {
33
+ lines.push(` FAIL ${describeCase(failed).split('\n')[0]}`);
34
+ if (failed.errors[0])
35
+ lines.push(` ${sanitizeText(failed.errors[0].split('\n')[0]).slice(0, ERROR_CHARS)}`);
36
+ }
37
+ const hidden = summary.failed - Math.min(page.cases.length, LISTED_FAILURES);
38
+ if (hidden > 0)
39
+ lines.push(` +${hidden} more failed cases${summary.omittedCases ? ' (some details were dropped by retention)' : ''}`);
40
+ }
41
+ catch (error) {
42
+ lines.push(` Failed case details unavailable (${error instanceof Error ? error.message : String(error)})`);
43
+ }
44
+ return lines;
45
+ }
46
+ /**
47
+ * Follows one admitted operation in plain output: a line per lifecycle or phase change,
48
+ * then outcome, uncollected stories, run errors and named failures. Resolves when the
49
+ * operation is final or its runtime is gone. Slice 10 reuses it for scheduled runs.
50
+ * @param tests Console owning the state.
51
+ * @param operationId Admitted operation.
52
+ * @param report Line sink.
53
+ */
54
+ export function followOperation(tests, operationId, report) {
55
+ return new Promise((resolve) => {
56
+ let shown = '';
57
+ let seen = false;
58
+ let unsubscribe = () => { };
59
+ const check = () => {
60
+ const entry = tests.state.get(operationId);
61
+ if (!entry) {
62
+ // Evicted from the bounded history while still followed: nothing more will arrive.
63
+ if (!seen)
64
+ return;
65
+ unsubscribe();
66
+ report('Tests result is no longer retained');
67
+ return resolve();
68
+ }
69
+ seen = true;
70
+ const finished = entry.lost || TEST_FINAL_STATES.includes(entry.operation.state);
71
+ if (!finished) {
72
+ // Progress ticks are frequent: one line per state or phase change is the decisive part.
73
+ const key = `${entry.operation.state}|${entry.progress?.phase ?? ''}`;
74
+ if (key !== shown)
75
+ report(describeOperation(entry.operation, entry.progress));
76
+ shown = key;
77
+ return;
78
+ }
79
+ unsubscribe();
80
+ void finalLines(tests, entry).then(lines => lines.forEach(report)).finally(resolve);
81
+ };
82
+ unsubscribe = tests.subscribe(check);
83
+ check();
84
+ });
85
+ }
86
+ /**
87
+ * Plain `tests`: submits the selected scope and follows it to the end. Assertion failures
88
+ * are reported, never thrown, so they cannot change the server or its exit status.
89
+ * @param tests Console.
90
+ * @param report Line sink.
91
+ */
92
+ export async function runAndReport(tests, report) {
93
+ const target = tests.runnable().target;
94
+ const admitted = await tests.run();
95
+ if ('problem' in admitted)
96
+ return report(admitted.problem);
97
+ report(`Tests queued: ${target ? describeTarget(target) : 'selected scope'}`);
98
+ await followOperation(tests, admitted.id, report);
99
+ }
@@ -0,0 +1,44 @@
1
+ import type { TestCaseDto } from '../protocol/tests.js';
2
+ import type { TestsConsole } from './console.js';
3
+ /** One loaded case with the position that keeps list order stable. */
4
+ export interface ResultRow {
5
+ /** Stable identity: story, variant and case ID. */
6
+ id: string;
7
+ /** Position in the retained order (failures first). */
8
+ rank: number;
9
+ /** Case as the child retained it. */
10
+ case: TestCaseDto;
11
+ }
12
+ /** What the results list currently holds. */
13
+ export type ResultsStatus = 'none' | 'loading' | 'ready' | 'unavailable' | 'failed';
14
+ /** Paged, cached view of the cases of the operation the console shows. */
15
+ export interface ResultsList {
16
+ /** Loaded rows in retained order. */
17
+ rows: () => readonly ResultRow[];
18
+ /** Cases matching the filter that the child retained (loaded or not). */
19
+ total: () => number;
20
+ /** Load state of the first page. */
21
+ status: () => ResultsStatus;
22
+ /** Why nothing is readable (`evicted`, `retired`, ...) or the read failure. */
23
+ reason: () => string | undefined;
24
+ /** More pages exist beyond the loaded rows. */
25
+ hasMore: () => boolean;
26
+ /** Failures-only filter. */
27
+ failuresOnly: () => boolean;
28
+ /** Toggles the failures-only filter and reloads. */
29
+ setFailuresOnly: (value: boolean) => void;
30
+ /** Reloads when the viewed operation, its finality or the filter changed; call on every state change. */
31
+ sync: () => void;
32
+ /** Requests the next page. */
33
+ loadMore: () => void;
34
+ /** Observes loads. Returns an unsubscribe function. */
35
+ subscribe: (listener: () => void) => () => void;
36
+ }
37
+ /** Plain text of one case for search, detail and copy. */
38
+ export declare function describeCase(item: TestCaseDto): string;
39
+ /**
40
+ * Loads result pages of the viewed operation through the cached state. Only completed
41
+ * operations have cases; pages of a replaced runtime stay `retired` and are never rebuilt.
42
+ * @param tests Console deciding which operation is shown.
43
+ */
44
+ export declare function createResultsList(tests: TestsConsole): ResultsList;
@@ -0,0 +1,104 @@
1
+ import { sanitizeText } from '../output/sanitize.js';
2
+ /** Plain text of one case for search, detail and copy. */
3
+ export function describeCase(item) {
4
+ const where = [item.storyId, item.variantId].filter(Boolean).join(' / ');
5
+ const errors = item.unavailable ? ['Failure text was dropped, it exceeded the size bound'] : item.errors;
6
+ return sanitizeText([`${item.fullName || item.name}${where ? ` (${where})` : ''}`, ...errors].join('\n'));
7
+ }
8
+ /**
9
+ * Loads result pages of the viewed operation through the cached state. Only completed
10
+ * operations have cases; pages of a replaced runtime stay `retired` and are never rebuilt.
11
+ * @param tests Console deciding which operation is shown.
12
+ */
13
+ export function createResultsList(tests) {
14
+ const listeners = new Set();
15
+ let rows = [];
16
+ let total = 0;
17
+ let next;
18
+ let status = 'none';
19
+ let reason;
20
+ let failuresOnly = false;
21
+ /** Identity of what is loaded; a different key starts over. */
22
+ let loadedKey = '';
23
+ /** Fences replies of superseded loads. */
24
+ let epoch = 0;
25
+ let loadingMore = false;
26
+ const notify = () => listeners.forEach(listener => listener());
27
+ /** Reads one page and appends or replaces rows. */
28
+ async function load(operationId, cursor, mine) {
29
+ try {
30
+ const page = await tests.state.results(operationId, { cursor, failedOnly: failuresOnly || undefined });
31
+ if (mine !== epoch)
32
+ return;
33
+ if (page.unavailable) {
34
+ status = 'unavailable';
35
+ reason = page.unavailable;
36
+ }
37
+ else {
38
+ const offset = rows.length;
39
+ rows = [...rows, ...page.cases.map((item, index) => ({ id: `${item.storyId ?? ''}|${item.variantId ?? ''}|${item.id}`, rank: offset + index, case: item }))];
40
+ total = page.total;
41
+ next = page.next;
42
+ status = 'ready';
43
+ }
44
+ }
45
+ catch (error) {
46
+ if (mine !== epoch)
47
+ return;
48
+ status = 'failed';
49
+ reason = error instanceof Error ? error.message : String(error);
50
+ }
51
+ loadingMore = false;
52
+ notify();
53
+ }
54
+ /** Starts over for a new operation or filter. */
55
+ function reset(key, entryId, completed) {
56
+ loadedKey = key;
57
+ epoch++;
58
+ rows = [];
59
+ total = 0;
60
+ next = undefined;
61
+ reason = undefined;
62
+ loadingMore = false;
63
+ if (!entryId || !completed) {
64
+ status = 'none';
65
+ return notify();
66
+ }
67
+ status = 'loading';
68
+ notify();
69
+ void load(entryId, undefined, epoch);
70
+ }
71
+ /** Reloads when the viewed operation, its finality or the filter changed. */
72
+ function sync() {
73
+ const entry = tests.viewed();
74
+ const completed = entry?.operation.state === 'completed' && !entry.lost;
75
+ const key = `${entry?.operation.id ?? ''}|${completed}|${failuresOnly}`;
76
+ if (key !== loadedKey)
77
+ reset(key, entry?.operation.id, completed);
78
+ }
79
+ return {
80
+ rows: () => rows,
81
+ total: () => total,
82
+ status: () => status,
83
+ reason: () => reason,
84
+ hasMore: () => next !== undefined,
85
+ failuresOnly: () => failuresOnly,
86
+ setFailuresOnly(value) {
87
+ failuresOnly = value;
88
+ loadedKey = '';
89
+ sync();
90
+ },
91
+ sync,
92
+ loadMore() {
93
+ const entry = tests.viewed();
94
+ if (next === undefined || loadingMore || !entry)
95
+ return;
96
+ loadingMore = true;
97
+ void load(entry.operation.id, next, epoch);
98
+ },
99
+ subscribe(listener) {
100
+ listeners.add(listener);
101
+ return () => void listeners.delete(listener);
102
+ },
103
+ };
104
+ }
@@ -0,0 +1,25 @@
1
+ import type { TestTarget } from '../protocol/tests.js';
2
+ import type { TestTargetSelection } from '../stories/handoff.js';
3
+ /** Scope kinds the Tests view can select, in left/right order. */
4
+ export type TestScopeKind = 'all' | 'story' | 'variant';
5
+ /** One selectable scope with the exact target it would run, or why it cannot be selected. */
6
+ export interface ScopeOption {
7
+ /** Scope kind. */
8
+ scope: TestScopeKind;
9
+ /** Short plain label (sanitize before rendering: it may carry story titles). */
10
+ label: string;
11
+ /** Whether `r` may run this scope now. */
12
+ available: boolean;
13
+ /** Why the scope is disabled. */
14
+ reason?: string;
15
+ /** Exact target, only when available. */
16
+ target?: TestTarget;
17
+ }
18
+ /**
19
+ * Builds the three scope options. `All` is always selectable. Story and variant need the
20
+ * target handed over from the stories screen, and that target must belong to the current
21
+ * runtime generation: after a restart it stays visible but unresolved until selected again.
22
+ * @param selection Latest handed-over target.
23
+ * @param generation Current runtime generation.
24
+ */
25
+ export declare function resolveScopeOptions(selection: TestTargetSelection | undefined, generation: string | undefined): ScopeOption[];
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Builds the three scope options. `All` is always selectable. Story and variant need the
3
+ * target handed over from the stories screen, and that target must belong to the current
4
+ * runtime generation: after a restart it stays visible but unresolved until selected again.
5
+ * @param selection Latest handed-over target.
6
+ * @param generation Current runtime generation.
7
+ */
8
+ export function resolveScopeOptions(selection, generation) {
9
+ const all = { scope: 'all', label: 'All stories', available: true, target: { scope: 'all' } };
10
+ const none = (scope, reason) => ({ scope, label: scope === 'story' ? 'Story' : 'Variant', available: false, reason });
11
+ if (!selection) {
12
+ const reason = 'Select one in Stories and press t';
13
+ return [all, none('story', reason), none('variant', reason)];
14
+ }
15
+ if (selection.generation !== generation) {
16
+ const reason = 'Selected before the last restart, select it again in Stories';
17
+ return [all, { ...none('story', reason), label: selection.storyLabel ?? selection.target.storyId }, { ...none('variant', selection.target.scope === 'variant' ? reason : 'No variant selected'), label: selection.target.scope === 'variant' ? selection.label : 'Variant' }];
18
+ }
19
+ const { target } = selection;
20
+ const story = { scope: 'story', label: selection.storyLabel ?? target.storyId, available: true, target: { scope: 'story', storyId: target.storyId } };
21
+ const variant = target.scope === 'variant'
22
+ ? { scope: 'variant', label: selection.label, available: true, target }
23
+ : none('variant', 'No variant selected');
24
+ return [all, story, variant];
25
+ }
@@ -0,0 +1,11 @@
1
+ import type { TerminalSessionOptions } from '../session-types.js';
2
+ import type { SessionWatchOutput } from '../watch/session.js';
3
+ import type { TestsConsole } from './console.js';
4
+ /**
5
+ * Builds the session's test console and its watch. Operations are observed for the whole
6
+ * session: a caller-provided state (the dev command, which also feeds it runtime retirement)
7
+ * is used as is, otherwise a private one listens to the bridge.
8
+ * @param options Session options (bridge, progress, optional shared state, `testWatch`).
9
+ * @param output Output hooks of the watch; without them the watch is not registered.
10
+ */
11
+ export declare function createSessionTests(options: Pick<TerminalSessionOptions, 'bridge' | 'progress' | 'tests' | 'testWatch'>, output?: SessionWatchOutput): TestsConsole;
@@ -0,0 +1,24 @@
1
+ import { getTestTargetHandoff } from '../stories/handoff.js';
2
+ import { attachSessionWatch } from '../watch/session.js';
3
+ import { createTestsClient } from './client.js';
4
+ import { createTestsConsole } from './console.js';
5
+ import { createTestsState } from './state.js';
6
+ /**
7
+ * Builds the session's test console and its watch. Operations are observed for the whole
8
+ * session: a caller-provided state (the dev command, which also feeds it runtime retirement)
9
+ * is used as is, otherwise a private one listens to the bridge.
10
+ * @param options Session options (bridge, progress, optional shared state, `testWatch`).
11
+ * @param output Output hooks of the watch; without them the watch is not registered.
12
+ */
13
+ export function createSessionTests(options, output) {
14
+ const client = createTestsClient(options.bridge);
15
+ let state = options.tests;
16
+ if (!state) {
17
+ state = createTestsState({ client });
18
+ state.attach(options.bridge);
19
+ }
20
+ const tests = createTestsConsole({ state, client, bridge: options.bridge, progress: options.progress, handoff: getTestTargetHandoff({ bridge: options.bridge }) });
21
+ if (output)
22
+ attachSessionWatch(tests, options, output);
23
+ return tests;
24
+ }
@@ -0,0 +1,57 @@
1
+ import type { TerminalBridge } from '../bridge.js';
2
+ import type { TestOperationDto, TestProgressDto, TestResultsPage } from '../protocol/tests.js';
3
+ import type { TestsClient } from './client.js';
4
+ /** One tracked operation as the parent displays it. */
5
+ export interface TestEntry {
6
+ /** Latest snapshot (state, summary, failure). */
7
+ operation: TestOperationDto;
8
+ /** Latest progress while active. */
9
+ progress?: TestProgressDto;
10
+ /** Runtime generation that owns the operation. */
11
+ generation: string;
12
+ /** Generation was retired before the operation finished; its state is no longer observable. */
13
+ lost: boolean;
14
+ }
15
+ /** Bounds of the parent cache. */
16
+ export interface TestsStateLimits {
17
+ /** Finished operations kept. */
18
+ runs: number;
19
+ /** Serialized bytes of finished summaries plus cached result pages. */
20
+ bytes: number;
21
+ }
22
+ /**
23
+ * Session-lifetime cache of terminal test operations: bounded summaries and
24
+ * fetched result pages. It survives runtime replacement (historical entries
25
+ * stay readable) but never re-executes anything: pages of a retired generation
26
+ * that were not fetched are `unavailable: 'retired'`.
27
+ * @param options Client for page reads, and optional bounds.
28
+ * @param options.client Typed `tests.*` client.
29
+ * @param options.limits Count and byte bounds.
30
+ */
31
+ export declare function createTestsState(options: {
32
+ client: TestsClient;
33
+ limits?: TestsStateLimits;
34
+ }): {
35
+ /** Feeds one bridge event (`bridge.subscribe` listener); unknown or malformed payloads are ignored. */
36
+ onEvent(generation: string, event: string, data: unknown): void;
37
+ /** Subscribes to a bridge so events feed this state; returns the unsubscribe function. */
38
+ attach: (bridge: Pick<TerminalBridge, 'subscribe'>) => () => void;
39
+ /** Marks unfinished operations of a retired generation as lost; finished ones stay as history. */
40
+ onRetired(generation: string): void;
41
+ /**
42
+ * Reads a result page, caching it. Unfetched pages of a lost or replaced
43
+ * generation are explicitly unavailable instead of being reconstructed.
44
+ */
45
+ results(operationId: string, page?: {
46
+ cursor?: string;
47
+ failedOnly?: boolean;
48
+ }): Promise<TestResultsPage>;
49
+ /** Tracked operations, oldest first. */
50
+ snapshot: () => TestEntry[];
51
+ /** One tracked operation. */
52
+ get: (operationId: string) => TestEntry | undefined;
53
+ /** Subscribes to any change; returns the unsubscribe function. */
54
+ subscribe(listener: () => void): () => boolean;
55
+ };
56
+ /** State type returned by {@link createTestsState}. */
57
+ export type TestsState = ReturnType<typeof createTestsState>;
@@ -0,0 +1,134 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { TERMINAL_BOUNDS } from '../protocol/core.js';
3
+ import { isTestOperationDto, isTestProgressEvent, TEST_FINAL_STATES } from '../protocol/tests.js';
4
+ /** Ordering that keeps late or duplicated events from moving an operation backwards. */
5
+ const RANK = { queued: 0, running: 1, cancelling: 2, completed: 3, failed: 3, cancelled: 3 };
6
+ /**
7
+ * Session-lifetime cache of terminal test operations: bounded summaries and
8
+ * fetched result pages. It survives runtime replacement (historical entries
9
+ * stay readable) but never re-executes anything: pages of a retired generation
10
+ * that were not fetched are `unavailable: 'retired'`.
11
+ * @param options Client for page reads, and optional bounds.
12
+ * @param options.client Typed `tests.*` client.
13
+ * @param options.limits Count and byte bounds.
14
+ */
15
+ export function createTestsState(options) {
16
+ const limits = options.limits ?? { runs: TERMINAL_BOUNDS.testRuns, bytes: TERMINAL_BOUNDS.testBytes };
17
+ const entries = new Map();
18
+ const pages = new Map();
19
+ const listeners = new Set();
20
+ const retired = new Set();
21
+ let pageBytes = 0;
22
+ /** Notifies subscribers; faulty listeners never break ingestion. */
23
+ function notify() {
24
+ for (const listener of [...listeners]) {
25
+ try {
26
+ listener();
27
+ }
28
+ catch { }
29
+ }
30
+ }
31
+ /** Drops an entry and everything cached for it. */
32
+ function forget(id) {
33
+ entries.delete(id);
34
+ for (const [key, cached] of pages) {
35
+ if (cached.operationId !== id)
36
+ continue;
37
+ pages.delete(key);
38
+ pageBytes -= cached.bytes;
39
+ }
40
+ }
41
+ /** Enforces run-count and byte bounds, oldest finished first; active entries are never evicted. */
42
+ function trim() {
43
+ const finished = () => [...entries.values()].filter(entry => TEST_FINAL_STATES.includes(entry.operation.state) || entry.lost);
44
+ const size = () => pageBytes + finished().reduce((sum, entry) => sum + Buffer.byteLength(JSON.stringify(entry.operation)), 0);
45
+ while (finished().length > limits.runs)
46
+ forget(finished()[0].operation.id);
47
+ // Cached pages go before whole summaries: the aggregate is the part worth keeping.
48
+ while (size() > limits.bytes && pages.size) {
49
+ const [key, cached] = pages.entries().next().value;
50
+ pages.delete(key);
51
+ pageBytes -= cached.bytes;
52
+ }
53
+ while (size() > limits.bytes && finished().length > 1)
54
+ forget(finished()[0].operation.id);
55
+ }
56
+ /** Merges a snapshot unless it would move the operation backwards. */
57
+ function ingest(generation, operation) {
58
+ const known = entries.get(operation.id);
59
+ if (known && RANK[operation.state] < RANK[known.operation.state])
60
+ return;
61
+ // Map order is eviction order: finishing re-inserts, so a long run is the newest finished entry, not the oldest admitted.
62
+ if (known && TEST_FINAL_STATES.includes(operation.state))
63
+ entries.delete(operation.id);
64
+ entries.set(operation.id, { operation, generation, lost: false, progress: TEST_FINAL_STATES.includes(operation.state) ? undefined : known?.progress });
65
+ trim();
66
+ notify();
67
+ }
68
+ const api = {
69
+ /** Feeds one bridge event (`bridge.subscribe` listener); unknown or malformed payloads are ignored. */
70
+ onEvent(generation, event, data) {
71
+ if (event === 'tests.state' && isTestOperationDto(data)) {
72
+ ingest(generation, data);
73
+ }
74
+ else if (event === 'tests.progress' && isTestProgressEvent(data)) {
75
+ const entry = entries.get(data.operationId);
76
+ if (!entry || entry.generation !== generation || TEST_FINAL_STATES.includes(entry.operation.state))
77
+ return;
78
+ entry.progress = data.progress;
79
+ notify();
80
+ }
81
+ },
82
+ /** Subscribes to a bridge so events feed this state; returns the unsubscribe function. */
83
+ attach: (bridge) => bridge.subscribe(({ generation, event, data }) => api.onEvent(generation, event, data)),
84
+ /** Marks unfinished operations of a retired generation as lost; finished ones stay as history. */
85
+ onRetired(generation) {
86
+ retired.add(generation);
87
+ if (retired.size > 64)
88
+ retired.delete(retired.values().next().value);
89
+ let changed = false;
90
+ for (const entry of entries.values()) {
91
+ if (entry.generation !== generation || entry.lost || TEST_FINAL_STATES.includes(entry.operation.state))
92
+ continue;
93
+ entry.lost = true;
94
+ entry.progress = undefined;
95
+ changed = true;
96
+ }
97
+ if (changed)
98
+ notify();
99
+ },
100
+ /**
101
+ * Reads a result page, caching it. Unfetched pages of a lost or replaced
102
+ * generation are explicitly unavailable instead of being reconstructed.
103
+ */
104
+ async results(operationId, page = {}) {
105
+ const key = `${operationId}|${page.failedOnly ? 1 : 0}|${page.cursor ?? ''}`;
106
+ const cached = pages.get(key);
107
+ if (cached)
108
+ return cached.page;
109
+ const entry = entries.get(operationId);
110
+ if (!entry)
111
+ return { operationId, unavailable: 'unknown', cases: [], total: 0 };
112
+ if (entry.lost || retired.has(entry.generation))
113
+ return { operationId, unavailable: 'retired', cases: [], total: 0 };
114
+ const result = await options.client.results({ operationId, ...page });
115
+ if (!result.unavailable && entries.has(operationId)) {
116
+ const bytes = Buffer.byteLength(JSON.stringify(result));
117
+ pages.set(key, { operationId, page: result, bytes });
118
+ pageBytes += bytes;
119
+ trim();
120
+ }
121
+ return result;
122
+ },
123
+ /** Tracked operations, oldest first. */
124
+ snapshot: () => [...entries.values()],
125
+ /** One tracked operation. */
126
+ get: (operationId) => entries.get(operationId),
127
+ /** Subscribes to any change; returns the unsubscribe function. */
128
+ subscribe(listener) {
129
+ listeners.add(listener);
130
+ return () => listeners.delete(listener);
131
+ },
132
+ };
133
+ return api;
134
+ }
@@ -0,0 +1,6 @@
1
+ import type { TerminalViewFactory } from './registry.js';
2
+ /**
3
+ * `x`: deletes retained log and request history. Test history and running work are
4
+ * not registered, so they are untouched; the visible console is `c`'s concern.
5
+ */
6
+ export declare const createClearHistoryView: TerminalViewFactory;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `x`: deletes retained log and request history. Test history and running work are
3
+ * not registered, so they are untouched; the visible console is `c`'s concern.
4
+ */
5
+ export const createClearHistoryView = host => ({
6
+ id: 'clear-history',
7
+ shortcut: 'x',
8
+ title: 'Clear history',
9
+ run: () => host.notify(host.retained.clear().summary),
10
+ });