@cueloop/client 0.1.0-alpha.4 → 0.1.0-alpha.41

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 (138) hide show
  1. package/native/build.sh +56 -0
  2. package/native/darwin-arm64/libcueloopvt.dylib +0 -0
  3. package/native/src/shim.c +107 -0
  4. package/package.json +34 -24
  5. package/src/App.autoclose.test.tsx +137 -0
  6. package/src/App.diff.test.tsx +158 -22
  7. package/src/App.export.test.tsx +44 -37
  8. package/src/App.plan-review.test.tsx +632 -0
  9. package/src/App.readonly.test.tsx +60 -36
  10. package/src/App.rendering.test.tsx +132 -0
  11. package/src/App.review-panel.test.tsx +136 -0
  12. package/src/App.submit-confirm.test.tsx +220 -0
  13. package/src/App.test.tsx +128 -69
  14. package/src/App.toast.test.tsx +75 -0
  15. package/src/App.tsx +0 -0
  16. package/src/App.walk.test.tsx +288 -0
  17. package/src/attribution.test.ts +31 -0
  18. package/src/attribution.ts +38 -0
  19. package/src/clipboard.test.ts +23 -0
  20. package/src/clipboard.ts +30 -0
  21. package/src/components/AnnotationCard.compose-rows.test.ts +49 -0
  22. package/src/components/AnnotationCard.stories.tsx +94 -0
  23. package/src/components/AnnotationCard.tsx +228 -0
  24. package/src/components/Breadcrumb.stories.tsx +19 -0
  25. package/src/components/Breadcrumb.tsx +44 -0
  26. package/src/components/CodeBlock.stories.tsx +42 -0
  27. package/src/components/CodeBlock.tsx +83 -0
  28. package/src/components/CompletionOverlay.stories.tsx +23 -0
  29. package/src/components/CompletionOverlay.tsx +59 -0
  30. package/src/components/ConfirmCard.stories.tsx +56 -0
  31. package/src/components/ConfirmCard.tsx +135 -0
  32. package/src/components/ConfirmDialog.stories.tsx +21 -0
  33. package/src/components/ConfirmDialog.tsx +64 -0
  34. package/src/components/DiffSheet.scroll.test.tsx +123 -0
  35. package/src/components/DiffSheet.stories.tsx +78 -0
  36. package/src/components/DiffSheet.syntax.test.tsx +62 -0
  37. package/src/components/DiffSheet.tsx +355 -0
  38. package/src/components/InboxList.stories.tsx +31 -0
  39. package/src/components/InboxList.tsx +62 -0
  40. package/src/components/KeybindsDialog.stories.tsx +31 -0
  41. package/src/components/KeybindsDialog.tsx +58 -0
  42. package/src/components/MarkerPopover.stories.tsx +58 -0
  43. package/src/components/MarkerPopover.tsx +102 -0
  44. package/src/components/MenuBar.stories.tsx +37 -0
  45. package/src/components/MenuBar.tsx +74 -0
  46. package/src/components/PlanSheet.stories.tsx +113 -0
  47. package/src/components/PlanSheet.tsx +389 -0
  48. package/src/components/PromptDialog.stories.tsx +36 -0
  49. package/src/components/PromptDialog.tsx +78 -0
  50. package/src/components/ReviewPanel.stories.tsx +86 -0
  51. package/src/components/ReviewPanel.tsx +101 -0
  52. package/src/components/ReviewRail.stories.tsx +220 -0
  53. package/src/components/ReviewRail.tsx +324 -0
  54. package/src/components/SettingsDialog.stories.tsx +111 -0
  55. package/src/components/SettingsDialog.tsx +141 -0
  56. package/src/components/SettingsRows.stories.tsx +18 -0
  57. package/src/components/SettingsRows.tsx +108 -0
  58. package/src/components/Toast.stories.tsx +12 -0
  59. package/src/components/Toast.tsx +44 -0
  60. package/src/components/WalkWizard.stories.tsx +100 -0
  61. package/src/components/WalkWizard.tsx +152 -0
  62. package/src/components/__snapshots__/stories.test.tsx.snap +1829 -0
  63. package/src/components/agent-launcher.stories.tsx +26 -0
  64. package/src/components/agent-launcher.test.tsx +21 -0
  65. package/src/components/agent-launcher.tsx +180 -0
  66. package/src/components/diff-sheet-layout.test.ts +127 -0
  67. package/src/components/diff-sheet-layout.ts +167 -0
  68. package/src/components/primitives/Button.stories.tsx +32 -0
  69. package/src/components/primitives/Button.tsx +48 -0
  70. package/src/components/primitives/Card.stories.tsx +25 -0
  71. package/src/components/primitives/Card.tsx +59 -0
  72. package/src/components/primitives/Dialog.stories.tsx +24 -0
  73. package/src/components/primitives/Dialog.tsx +64 -0
  74. package/src/components/primitives/StatusBar.stories.tsx +11 -0
  75. package/src/components/primitives/StatusBar.tsx +22 -0
  76. package/src/components/primitives/Tabs.stories.tsx +29 -0
  77. package/src/components/primitives/Tabs.tsx +98 -0
  78. package/src/components/primitives/Toolbar.stories.tsx +17 -0
  79. package/src/components/primitives/Toolbar.tsx +14 -0
  80. package/src/components/primitives/frame.test.ts +12 -0
  81. package/src/components/primitives/frame.ts +14 -0
  82. package/src/components/quick-actions-editor.stories.tsx +54 -0
  83. package/src/components/quick-actions-editor.tsx +136 -0
  84. package/src/components/stories-app.tsx +123 -0
  85. package/src/components/stories.test.tsx +62 -0
  86. package/src/components/story-fixtures.ts +98 -0
  87. package/src/components/story.ts +69 -0
  88. package/src/components/syntax-highlight.ts +92 -0
  89. package/src/components/terminal-pane.test.tsx +40 -0
  90. package/src/components/terminal-pane.ts +174 -0
  91. package/src/components/theme-context.stories.tsx +46 -0
  92. package/src/components/theme-context.tsx +36 -0
  93. package/src/components/truncate-text.ts +6 -0
  94. package/src/config.test.ts +430 -31
  95. package/src/config.ts +304 -26
  96. package/src/diff-hunk-curate.test.ts +315 -0
  97. package/src/diff-hunk-curate.ts +233 -0
  98. package/src/diff-intraline.test.ts +164 -0
  99. package/src/diff-intraline.ts +132 -0
  100. package/src/diff-syntax.test.ts +96 -0
  101. package/src/diff-syntax.ts +154 -0
  102. package/src/editor.test.ts +143 -0
  103. package/src/editor.ts +123 -9
  104. package/src/ghostty-terminal.test.ts +45 -0
  105. package/src/ghostty-terminal.ts +168 -0
  106. package/src/herdr.test.ts +41 -0
  107. package/src/herdr.ts +27 -0
  108. package/src/index.ts +10 -0
  109. package/src/integrations.test.ts +41 -0
  110. package/src/integrations.ts +30 -0
  111. package/src/intent-dispatch.test.ts +492 -0
  112. package/src/intent-dispatch.ts +428 -0
  113. package/src/key-bindings.test.ts +152 -0
  114. package/src/key-bindings.ts +424 -0
  115. package/src/keymap.test.ts +622 -0
  116. package/src/keymap.ts +339 -0
  117. package/src/review-panel.test.ts +113 -0
  118. package/src/review-panel.ts +83 -0
  119. package/src/run.ts +9 -5
  120. package/src/serve.test.ts +24 -9
  121. package/src/serve.ts +7 -7
  122. package/src/session-controller.curate.test.ts +253 -0
  123. package/src/session-controller.share.test.ts +309 -0
  124. package/src/session-controller.ts +900 -0
  125. package/src/share.ts +113 -0
  126. package/src/test-support.test.ts +55 -0
  127. package/src/test-support.ts +187 -0
  128. package/src/theme-presets.ts +168 -0
  129. package/src/theme.ts +36 -15
  130. package/src/version.ts +5 -0
  131. package/src/view-diff.test.ts +19 -8
  132. package/src/view-diff.ts +34 -23
  133. package/src/view-plan.test.ts +294 -0
  134. package/src/view-plan.ts +408 -0
  135. package/src/walk.test.ts +121 -0
  136. package/src/walk.ts +70 -0
  137. package/src/view.test.ts +0 -157
  138. package/src/view.ts +0 -0
@@ -0,0 +1,164 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { intralineRunsByRow, wordLevelChanges, type IntralineRun } from "./diff-intraline";
3
+ import type { DiffRow } from "./view-diff";
4
+
5
+ function line(kind: DiffRow["kind"], text: string): DiffRow {
6
+ return { kind, text, file: "a.ts" };
7
+ }
8
+
9
+ function joinText(runs: IntralineRun[]): string {
10
+ return runs.map((run) => run.text).join("");
11
+ }
12
+
13
+ function changedText(runs: IntralineRun[]): string {
14
+ return runs
15
+ .filter((run) => run.changed)
16
+ .map((run) => run.text)
17
+ .join("");
18
+ }
19
+
20
+ describe("wordLevelChanges", () => {
21
+ test("marks only the changed word and stays whitespace-lossless", () => {
22
+ // Arrange
23
+ const oldText = "const foo = 1";
24
+ const newText = "const foo = 2";
25
+
26
+ // Act
27
+ const changes = wordLevelChanges(oldText, newText);
28
+
29
+ // Assert
30
+ expect(
31
+ changes
32
+ .filter((change) => change.kind === "common")
33
+ .map((change) => change.text)
34
+ .join(""),
35
+ ).toBe("const foo = ");
36
+ expect(
37
+ changes
38
+ .filter((change) => change.kind === "removed")
39
+ .map((change) => change.text)
40
+ .join(""),
41
+ ).toBe("1");
42
+ expect(
43
+ changes
44
+ .filter((change) => change.kind === "added")
45
+ .map((change) => change.text)
46
+ .join(""),
47
+ ).toBe("2");
48
+ // old text reconstructs from common + removed, new text from common + added
49
+ expect(
50
+ changes
51
+ .filter((change) => change.kind !== "added")
52
+ .map((change) => change.text)
53
+ .join(""),
54
+ ).toBe(oldText);
55
+ expect(
56
+ changes
57
+ .filter((change) => change.kind !== "removed")
58
+ .map((change) => change.text)
59
+ .join(""),
60
+ ).toBe(newText);
61
+ });
62
+ });
63
+
64
+ describe("intralineRunsByRow", () => {
65
+ test("pairs a deletion with its addition and highlights the changed word on each side", () => {
66
+ // Arrange
67
+ const rows = [
68
+ line("ctx", "unchanged"),
69
+ line("del", "const foo = 1"),
70
+ line("add", "const foo = 2"),
71
+ ];
72
+
73
+ // Act
74
+ const runsByRow = intralineRunsByRow(rows);
75
+
76
+ // Assert
77
+ const deletionRuns = runsByRow.get(1)!;
78
+ const additionRuns = runsByRow.get(2)!;
79
+ expect(joinText(deletionRuns)).toBe("const foo = 1");
80
+ expect(joinText(additionRuns)).toBe("const foo = 2");
81
+ expect(changedText(deletionRuns)).toBe("1");
82
+ expect(changedText(additionRuns)).toBe("2");
83
+ });
84
+
85
+ test("omits context rows and rows with no counterpart", () => {
86
+ // Arrange
87
+ const rows = [line("ctx", "keep me"), line("add", "brand new line")];
88
+
89
+ // Act
90
+ const runsByRow = intralineRunsByRow(rows);
91
+
92
+ // Assert
93
+ expect(runsByRow.size).toBe(0);
94
+ });
95
+
96
+ test("pairs only min(deletions, additions); the surplus stays a plain row", () => {
97
+ // Arrange - two deletions, one addition
98
+ const rows = [line("del", "alpha one"), line("del", "beta two"), line("add", "alpha ONE")];
99
+
100
+ // Act
101
+ const runsByRow = intralineRunsByRow(rows);
102
+
103
+ // Assert
104
+ expect(runsByRow.has(0)).toBe(true); // first deletion pairs with the addition
105
+ expect(runsByRow.has(1)).toBe(false); // second deletion has no counterpart
106
+ expect(runsByRow.has(2)).toBe(true);
107
+ expect(changedText(runsByRow.get(0)!)).toBe("one");
108
+ expect(changedText(runsByRow.get(2)!)).toBe("ONE");
109
+ });
110
+
111
+ test("a fully rewritten single line marks the whole line changed on both sides", () => {
112
+ // Arrange - a lone deletion opposite a lone addition is unambiguously one edit
113
+ const rows = [line("del", "aaa"), line("add", "zzz")];
114
+
115
+ // Act
116
+ const runsByRow = intralineRunsByRow(rows);
117
+
118
+ // Assert
119
+ expect(changedText(runsByRow.get(0)!)).toBe("aaa");
120
+ expect(changedText(runsByRow.get(1)!)).toBe("zzz");
121
+ });
122
+
123
+ test("in a shifted block, alignment matches the real counterpart, not by position", () => {
124
+ // Arrange - "beta gamma" is modified and an unrelated line sits at each end;
125
+ // positional pairing would word-diff "alpha" against "beta gamma delta"
126
+ const rows = [
127
+ line("del", "alpha"),
128
+ line("del", "beta gamma"),
129
+ line("add", "beta gamma delta"),
130
+ line("add", "zulu"),
131
+ ];
132
+
133
+ // Act
134
+ const runsByRow = intralineRunsByRow(rows);
135
+
136
+ // Assert
137
+ // the modified pair is found and word-diffed
138
+ expect(runsByRow.has(1)).toBe(true); // "beta gamma"
139
+ expect(runsByRow.has(2)).toBe(true); // "beta gamma delta"
140
+ expect(changedText(runsByRow.get(2)!).trim()).toBe("delta");
141
+ // the genuinely unrelated lines stay whole-line
142
+ expect(runsByRow.has(0)).toBe(false); // "alpha"
143
+ expect(runsByRow.has(3)).toBe(false); // "zulu"
144
+ });
145
+
146
+ test("in a multi-line block, related positional pairs still highlight the changed word", () => {
147
+ // Arrange - a same-shape 2x2 edit: each row lines up with its counterpart
148
+ const rows = [
149
+ line("del", "one two"),
150
+ line("del", "three four"),
151
+ line("add", "one TWO"),
152
+ line("add", "three FOUR"),
153
+ ];
154
+
155
+ // Act
156
+ const runsByRow = intralineRunsByRow(rows);
157
+
158
+ // Assert
159
+ expect(changedText(runsByRow.get(0)!)).toBe("two");
160
+ expect(changedText(runsByRow.get(1)!)).toBe("four");
161
+ expect(changedText(runsByRow.get(2)!)).toBe("TWO");
162
+ expect(changedText(runsByRow.get(3)!)).toBe("FOUR");
163
+ });
164
+ });
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Intra-line word diff: the char-precise "what changed within this line" engine
3
+ * shared by the plan tracked-changes view and the diff review sheet. Backed by
4
+ * jsdiff diffWordsWithSpace, so it is punctuation-aware and whitespace-lossless:
5
+ * the run values always concatenate back to the exact inputs, which keeps quote
6
+ * anchors intact. Supersedes the coarse LCS wordDiff.
7
+ */
8
+
9
+ import { diffWordsWithSpace } from "diff";
10
+ import { lcsDiff } from "@cueloop/schema";
11
+ import type { DiffRow } from "./view-diff";
12
+
13
+ export type WordChangeKind = "common" | "added" | "removed";
14
+
15
+ /** One word-level change between two strings; text is verbatim (lossless). */
16
+ export interface WordChange {
17
+ text: string;
18
+ kind: WordChangeKind;
19
+ }
20
+
21
+ /** Word-level changes between two strings, whitespace-lossless and ordered. */
22
+ export function wordLevelChanges(oldText: string, newText: string): WordChange[] {
23
+ return diffWordsWithSpace(oldText, newText).map((change) => ({
24
+ text: change.value,
25
+ kind: change.added ? "added" : change.removed ? "removed" : "common",
26
+ }));
27
+ }
28
+
29
+ /** One rendered segment of a diff row: changed marks the intra-line change. */
30
+ export interface IntralineRun {
31
+ text: string;
32
+ changed: boolean;
33
+ }
34
+
35
+ function stripTrailingNewline(text: string): string {
36
+ return text.replace(/\n$/, "");
37
+ }
38
+
39
+ /**
40
+ * Char-precise intra-line runs for modified diff rows. Within a change block - a
41
+ * run of deletions immediately followed by additions - lines are aligned to their
42
+ * real counterpart (see alignedPairs) and each matched pair is word-diffed so the
43
+ * removed/added words are marked changed. Rows with no counterpart (pure add, pure
44
+ * delete, or an unmatched line in a shifted block) are omitted, so the caller
45
+ * renders those as a single run. Each row's runs concatenate back to that row's text.
46
+ */
47
+ export function intralineRunsByRow(rows: DiffRow[]): Map<number, IntralineRun[]> {
48
+ const runsByRow = new Map<number, IntralineRun[]>();
49
+ let index = 0;
50
+ while (index < rows.length) {
51
+ if (rows[index]!.kind !== "del") {
52
+ index++;
53
+ continue;
54
+ }
55
+ const deletionStart = index;
56
+ while (index < rows.length && rows[index]!.kind === "del") index++;
57
+ const additionStart = index;
58
+ while (index < rows.length && rows[index]!.kind === "add") index++;
59
+ const deletionTexts = rows
60
+ .slice(deletionStart, additionStart)
61
+ .map((row) => stripTrailingNewline(row.text));
62
+ const additionTexts = rows
63
+ .slice(additionStart, index)
64
+ .map((row) => stripTrailingNewline(row.text));
65
+ for (const [deletionOffset, additionOffset] of alignedPairs(deletionTexts, additionTexts)) {
66
+ const changes = wordLevelChanges(
67
+ deletionTexts[deletionOffset]!,
68
+ additionTexts[additionOffset]!,
69
+ );
70
+ runsByRow.set(deletionStart + deletionOffset, sideRuns(changes, "removed"));
71
+ runsByRow.set(additionStart + additionOffset, sideRuns(changes, "added"));
72
+ }
73
+ }
74
+ return runsByRow;
75
+ }
76
+
77
+ /** Lines this similar (word-set overlap) are treated as the same line edited. */
78
+ const SIMILAR_MIN_WORD_OVERLAP = 0.3;
79
+
80
+ /** Whether two lines are the same line edited, by case-insensitive word-set
81
+ * overlap - the matching gate, distinct from the case-sensitive word diff. */
82
+ function linesSimilar(oldText: string, newText: string): boolean {
83
+ const words = (text: string) => new Set(text.toLowerCase().split(/\s+/).filter(Boolean));
84
+ const oldWords = words(oldText);
85
+ const newWords = words(newText);
86
+ if (oldWords.size === 0 && newWords.size === 0) return true;
87
+ let intersection = 0;
88
+ for (const word of oldWords) if (newWords.has(word)) intersection++;
89
+ const union = oldWords.size + newWords.size - intersection;
90
+ return union === 0 ? true : intersection / union >= SIMILAR_MIN_WORD_OVERLAP;
91
+ }
92
+
93
+ /**
94
+ * Pair each modified line with the addition it became. A lone deletion opposite
95
+ * a lone addition is one edit (always paired). Otherwise align the lines by
96
+ * similarity, order-preserving (LCS over `linesSimilar`), so an inserted, removed,
97
+ * or shifted line finds its real counterpart instead of mispairing by position -
98
+ * unmatched lines get no pair and render whole-line. Returns [deletionOffset,
99
+ * additionOffset] pairs into the block.
100
+ */
101
+ function alignedPairs(deletionTexts: string[], additionTexts: string[]): Array<[number, number]> {
102
+ if (deletionTexts.length === 1 && additionTexts.length === 1) return [[0, 0]];
103
+ const pairs: Array<[number, number]> = [];
104
+ let deletionOffset = 0;
105
+ let additionOffset = 0;
106
+ for (const op of lcsDiff(deletionTexts, additionTexts, linesSimilar)) {
107
+ if (op.kind === "ctx") {
108
+ pairs.push([deletionOffset, additionOffset]);
109
+ deletionOffset++;
110
+ additionOffset++;
111
+ } else if (op.kind === "del") {
112
+ deletionOffset++;
113
+ } else {
114
+ additionOffset++;
115
+ }
116
+ }
117
+ return pairs;
118
+ }
119
+
120
+ /** Runs for one side of a word diff: common plus this side's changes, adjacent
121
+ * runs of equal changed-ness coalesced so highlighting stays as few spans. */
122
+ function sideRuns(changes: WordChange[], side: "added" | "removed"): IntralineRun[] {
123
+ const runs: IntralineRun[] = [];
124
+ for (const change of changes) {
125
+ if (change.kind !== "common" && change.kind !== side) continue;
126
+ const changed = change.kind === side;
127
+ const last = runs[runs.length - 1];
128
+ if (last && last.changed === changed) last.text += change.text;
129
+ else runs.push({ text: change.text, changed });
130
+ }
131
+ return runs;
132
+ }
@@ -0,0 +1,96 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { highlightJobs, spansByLine } from "./diff-syntax";
3
+ import type { DiffRow } from "./view-diff";
4
+ import type { SimpleHighlight } from "@opentui/core";
5
+
6
+ function row(kind: DiffRow["kind"], text: string, file = "src/x.ts"): DiffRow {
7
+ return { kind, text, file };
8
+ }
9
+
10
+ describe("spansByLine", () => {
11
+ test("maps absolute offsets to line-relative spans", () => {
12
+ // Arrange
13
+ const source = "const x = 1;\nfoo";
14
+ const highlights: SimpleHighlight[] = [
15
+ [0, 5, "keyword"],
16
+ [6, 7, "variable"],
17
+ [13, 16, "variable"],
18
+ ];
19
+
20
+ // Act
21
+ const lineSpans = spansByLine(source, highlights);
22
+
23
+ // Assert
24
+ expect(lineSpans[0]).toEqual([
25
+ { start: 0, end: 5, group: "keyword" },
26
+ { start: 6, end: 7, group: "variable" },
27
+ ]);
28
+ expect(lineSpans[1]).toEqual([{ start: 0, end: 3, group: "variable" }]);
29
+ });
30
+
31
+ test("spreads a capture that crosses newlines onto every line it covers", () => {
32
+ // Arrange - one capture spanning both lines, as a block comment would
33
+ const source = "aa\nbb";
34
+ const highlights: SimpleHighlight[] = [[0, 5, "comment"]];
35
+
36
+ // Act
37
+ const lineSpans = spansByLine(source, highlights);
38
+
39
+ // Assert
40
+ expect(lineSpans[0]).toEqual([{ start: 0, end: 2, group: "comment" }]);
41
+ expect(lineSpans[1]).toEqual([{ start: 0, end: 2, group: "comment" }]);
42
+ });
43
+
44
+ test("resolves overlapping captures with later winning", () => {
45
+ // Arrange
46
+ const source = "foo";
47
+ const highlights: SimpleHighlight[] = [
48
+ [0, 3, "variable"],
49
+ [0, 3, "type"],
50
+ ];
51
+
52
+ // Act
53
+ const lineSpans = spansByLine(source, highlights);
54
+
55
+ // Assert
56
+ expect(lineSpans[0]).toEqual([{ start: 0, end: 3, group: "type" }]);
57
+ });
58
+ });
59
+
60
+ describe("highlightJobs", () => {
61
+ test("reconstructs old and new sides of a hunk with row indices", () => {
62
+ // Arrange
63
+ const rows = [
64
+ row("file", "src/x.ts", "src/x.ts"),
65
+ row("hunk", "@@ -1,2 +1,2 @@"),
66
+ row("ctx", "const a = 1;"),
67
+ row("del", "const b = 2;"),
68
+ row("add", "const b = 3;"),
69
+ ];
70
+
71
+ // Act
72
+ const jobs = highlightJobs(rows);
73
+
74
+ // Assert
75
+ // old side = context + deletion; new side = context + addition
76
+ expect(jobs).toEqual([
77
+ { filetype: "typescript", source: "const a = 1;\nconst b = 2;", rowIndexByLine: [2, 3] },
78
+ { filetype: "typescript", source: "const a = 1;\nconst b = 3;", rowIndexByLine: [2, 4] },
79
+ ]);
80
+ });
81
+
82
+ test("skips files with no known filetype", () => {
83
+ // Arrange
84
+ const rows = [
85
+ row("file", "notes/thing.unknownext", "notes/thing.unknownext"),
86
+ row("hunk", "@@"),
87
+ row("add", "whatever"),
88
+ ];
89
+
90
+ // Act
91
+ const jobs = highlightJobs(rows);
92
+
93
+ // Assert
94
+ expect(jobs).toEqual([]);
95
+ });
96
+ });
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Syntax highlighting for diff rows: tree-sitter token colors mapped onto the
3
+ * diff sheet's hand-rolled rows, so annotation cards still interleave. A hunk is
4
+ * highlighted as a contiguous fragment (its context+addition lines as the new
5
+ * side, context+deletion lines as the old side) - never per single line, which
6
+ * would lose the multi-line grammar context - and the resulting token spans are
7
+ * mapped back to each row in line-relative columns. Async: the shared tree-sitter
8
+ * client resolves off the render path, so callers draw unstyled first.
9
+ */
10
+
11
+ import { getTreeSitterClient, type SimpleHighlight } from "@opentui/core";
12
+ import type { DiffRow } from "./view-diff";
13
+ import { filetypeForPath } from "./components/syntax-highlight";
14
+
15
+ /** A syntax-colored run within one row, in line-relative columns [start, end). */
16
+ export interface SyntaxSpan {
17
+ start: number;
18
+ end: number;
19
+ group: string;
20
+ }
21
+
22
+ function stripTrailingNewline(text: string): string {
23
+ return text.replace(/\n$/, "");
24
+ }
25
+
26
+ interface HighlightJob {
27
+ filetype: string;
28
+ source: string;
29
+ /** Row index for each line of `source`, in order. */
30
+ rowIndexByLine: number[];
31
+ }
32
+
33
+ /**
34
+ * Split diff rows into per-hunk highlight jobs, one per side. A hunk's rows are
35
+ * contiguous file lines, so each side reconstructs to valid code; file/hunk
36
+ * header rows and files without a known filetype are skipped.
37
+ */
38
+ export function highlightJobs(rows: DiffRow[]): HighlightJob[] {
39
+ const jobs: HighlightJob[] = [];
40
+ let oldLines: string[] = [];
41
+ let newLines: string[] = [];
42
+ let oldRowIndexByLine: number[] = [];
43
+ let newRowIndexByLine: number[] = [];
44
+ let filetype: string | undefined;
45
+
46
+ const flush = (): void => {
47
+ if (filetype) {
48
+ if (oldLines.length)
49
+ jobs.push({ filetype, source: oldLines.join("\n"), rowIndexByLine: oldRowIndexByLine });
50
+ if (newLines.length)
51
+ jobs.push({ filetype, source: newLines.join("\n"), rowIndexByLine: newRowIndexByLine });
52
+ }
53
+ oldLines = [];
54
+ newLines = [];
55
+ oldRowIndexByLine = [];
56
+ newRowIndexByLine = [];
57
+ };
58
+
59
+ for (let rowIndex = 0; rowIndex < rows.length; rowIndex++) {
60
+ const row = rows[rowIndex]!;
61
+ if (row.kind === "file" || row.kind === "hunk") {
62
+ flush();
63
+ filetype = row.kind === "file" ? filetypeForPath(row.file) : filetype;
64
+ continue;
65
+ }
66
+ const text = stripTrailingNewline(row.text);
67
+ if (row.kind === "ctx" || row.kind === "del") {
68
+ oldLines.push(text);
69
+ oldRowIndexByLine.push(rowIndex);
70
+ }
71
+ if (row.kind === "ctx" || row.kind === "add") {
72
+ newLines.push(text);
73
+ newRowIndexByLine.push(rowIndex);
74
+ }
75
+ }
76
+ flush();
77
+ return jobs;
78
+ }
79
+
80
+ /**
81
+ * Resolve one source's flat, possibly-overlapping token highlights into
82
+ * per-line spans. Offsets are absolute into `source`; later highlights win on
83
+ * overlap, and a highlight is clamped to the line its start falls on.
84
+ */
85
+ export function spansByLine(source: string, highlights: SimpleHighlight[]): SyntaxSpan[][] {
86
+ const lineStarts: number[] = [0];
87
+ for (let index = 0; index < source.length; index++) {
88
+ if (source[index] === "\n") lineStarts.push(index + 1);
89
+ }
90
+ const lineOf = (offset: number): number => {
91
+ let low = 0;
92
+ let high = lineStarts.length - 1;
93
+ while (low < high) {
94
+ const mid = (low + high + 1) >> 1;
95
+ if (lineStarts[mid]! <= offset) low = mid;
96
+ else high = mid - 1;
97
+ }
98
+ return low;
99
+ };
100
+ // Per-line char->group, later highlights overriding, then coalesce into spans.
101
+ const groupsByLine: Array<Array<string | undefined>> = lineStarts.map((start, line) => {
102
+ const end = line + 1 < lineStarts.length ? lineStarts[line + 1]! - 1 : source.length;
103
+ return Array.from({ length: Math.max(0, end - start) }, () => undefined);
104
+ });
105
+ for (const [start, end, group] of highlights) {
106
+ // A capture can span newlines (block comments, template literals); color the
107
+ // covered columns on every line it crosses, not just the starting line.
108
+ let cursor = start;
109
+ while (cursor < end) {
110
+ const line = lineOf(cursor);
111
+ const lineStart = lineStarts[line]!;
112
+ const lineEnd = line + 1 < lineStarts.length ? lineStarts[line + 1]! - 1 : source.length;
113
+ const chars = groupsByLine[line]!;
114
+ const to = Math.min(end, lineEnd) - lineStart;
115
+ for (let column = cursor - lineStart; column < to; column++) chars[column] = group;
116
+ cursor = lineEnd + 1;
117
+ }
118
+ }
119
+ return groupsByLine.map((chars) => {
120
+ const spans: SyntaxSpan[] = [];
121
+ for (let column = 0; column < chars.length; column++) {
122
+ const group = chars[column];
123
+ if (group === undefined) continue;
124
+ const previous = spans[spans.length - 1];
125
+ if (previous && previous.group === group && previous.end === column)
126
+ previous.end = column + 1;
127
+ else spans.push({ start: column, end: column + 1, group });
128
+ }
129
+ return spans;
130
+ });
131
+ }
132
+
133
+ /**
134
+ * Highlight the diff's rows and return the token spans per row index. Rows in a
135
+ * file with no known filetype, and any row while highlighting is still resolving,
136
+ * are absent - the caller renders those unstyled.
137
+ */
138
+ export async function highlightDiffRows(rows: DiffRow[]): Promise<Map<number, SyntaxSpan[]>> {
139
+ const spansByRow = new Map<number, SyntaxSpan[]>();
140
+ const jobs = highlightJobs(rows);
141
+ if (!jobs.length) return spansByRow;
142
+ const client = getTreeSitterClient();
143
+ await client.initialize();
144
+ for (const job of jobs) {
145
+ const result = await client.highlightOnce(job.source, job.filetype);
146
+ if (!result.highlights) continue;
147
+ const lineSpans = spansByLine(job.source, result.highlights);
148
+ job.rowIndexByLine.forEach((rowIndex, line) => {
149
+ const spans = lineSpans[line];
150
+ if (spans && spans.length) spansByRow.set(rowIndex, spans);
151
+ });
152
+ }
153
+ return spansByRow;
154
+ }
@@ -0,0 +1,143 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { editInEditor, resolveEditor, resolveEditorCommand } from "./editor";
6
+
7
+ describe("resolveEditor", () => {
8
+ test("a clean environment falls back to nano so editing always works", () => {
9
+ // Assert
10
+ expect(resolveEditor(undefined, {})).toBe("nano");
11
+ });
12
+
13
+ test("the environment chain wins in order: CUELOOP_EDITOR, VISUAL, EDITOR", () => {
14
+ // Assert
15
+ expect(resolveEditor(undefined, { EDITOR: "vim", VISUAL: "code", CUELOOP_EDITOR: "hx" })).toBe(
16
+ "hx",
17
+ );
18
+ expect(resolveEditor(undefined, { EDITOR: "vim", VISUAL: "code" })).toBe("code");
19
+ expect(resolveEditor(undefined, { EDITOR: "vim" })).toBe("vim");
20
+ });
21
+
22
+ test("the [ui] editor config overrides the environment", () => {
23
+ // Assert
24
+ expect(resolveEditor("code --wait", { EDITOR: "vim" })).toBe("code --wait");
25
+ });
26
+ });
27
+
28
+ describe("resolveEditorCommand", () => {
29
+ test("a known GUI editor gets its wait flag appended and is trusted to wait", () => {
30
+ // Assert
31
+ expect(resolveEditorCommand("code")).toEqual({ argv: ["code", "--wait"], waits: true });
32
+ expect(resolveEditorCommand("subl")).toEqual({
33
+ argv: ["subl", "--new-window", "--wait"],
34
+ waits: true,
35
+ });
36
+ });
37
+
38
+ test("an existing wait flag is not duplicated", () => {
39
+ // Assert
40
+ expect(resolveEditorCommand("code --wait").argv).toEqual(["code", "--wait"]);
41
+ });
42
+
43
+ test("a terminal editor is left alone and trusted to hold the tty", () => {
44
+ // Assert
45
+ expect(resolveEditorCommand("vim")).toEqual({ argv: ["vim"], waits: true });
46
+ });
47
+
48
+ test("an unknown editor is neither flagged nor trusted to wait", () => {
49
+ // Assert
50
+ expect(resolveEditorCommand("my-editor")).toEqual({ argv: ["my-editor"], waits: false });
51
+ });
52
+ });
53
+
54
+ describe("editInEditor", () => {
55
+ let dir: string;
56
+ beforeEach(() => {
57
+ dir = mkdtempSync(join(tmpdir(), "cueloop-edit-test-"));
58
+ });
59
+ afterEach(() => {
60
+ rmSync(dir, { recursive: true, force: true });
61
+ });
62
+
63
+ /** A runnable editor stub with a chosen base name and body. */
64
+ function stubEditor(name: string, body: string): string {
65
+ const script = join(dir, name);
66
+ writeFileSync(script, `#!/bin/sh\n${body}\n`);
67
+ chmodSync(script, 0o755);
68
+ return script;
69
+ }
70
+
71
+ const instant = (): (() => number) => {
72
+ let value = 0;
73
+ return () => (value += 5);
74
+ };
75
+
76
+ test("an editor that changes the file reports the new content", () => {
77
+ // Act
78
+ const result = editInEditor("old", "plan.md", {
79
+ editor: stubEditor("writer.sh", `printf 'new' > "$1"`),
80
+ });
81
+
82
+ // Assert
83
+ expect(result).toEqual({ content: "new", changed: true });
84
+ });
85
+
86
+ test("a fast, unchanged return opens the gate; confirming re-reads the saved file", () => {
87
+ // Arrange
88
+ let askedLabel = "";
89
+
90
+ // Act
91
+ const result = editInEditor("keep", "plan.md", {
92
+ editor: stubEditor("gui-like.sh", "exit 0"),
93
+ now: instant(),
94
+ confirmSaved: (label, path) => {
95
+ askedLabel = label;
96
+ writeFileSync(path, "saved in the GUI");
97
+ return true;
98
+ },
99
+ });
100
+
101
+ // Assert
102
+ expect(askedLabel).toContain("gui-like.sh");
103
+ expect(result).toEqual({ content: "saved in the GUI", changed: true });
104
+ });
105
+
106
+ test("declining the gate keeps the original content", () => {
107
+ // Act
108
+ const result = editInEditor("keep", "plan.md", {
109
+ editor: stubEditor("gui-like.sh", "exit 0"),
110
+ now: instant(),
111
+ confirmSaved: () => false,
112
+ });
113
+
114
+ // Assert
115
+ expect(result).toEqual({ content: "keep", changed: false });
116
+ });
117
+
118
+ test("a terminal editor that makes no change never opens the gate", () => {
119
+ // Arrange
120
+ let asked = false;
121
+
122
+ // Act
123
+ const result = editInEditor("keep", "plan.md", {
124
+ editor: stubEditor("vi", "exit 0"),
125
+ now: instant(),
126
+ confirmSaved: () => {
127
+ asked = true;
128
+ return true;
129
+ },
130
+ });
131
+
132
+ // Assert
133
+ expect(asked).toBeFalse();
134
+ expect(result).toEqual({ content: "keep", changed: false });
135
+ });
136
+
137
+ test("a nonzero editor exit throws", () => {
138
+ // Assert
139
+ expect(() => editInEditor("x", "plan.md", { editor: stubEditor("fail.sh", "exit 3") })).toThrow(
140
+ "editor exited 3",
141
+ );
142
+ });
143
+ });