Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/extension-selection-current-line.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hunkdiff": minor
---

Let extension commands inspect `ctx.selection.currentLine`; TypeScript authors constructing `ExtensionReviewSelection` must add its required field.
4 changes: 3 additions & 1 deletion docs/extension-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,9 @@ commands. Extension
chord at a time and detected by probing matchers with a synthesized event
(`src/lib/commandKeys.ts`). Command handlers receive pane controls and a selection snapshot from
`src/ui/lib/extensionSelection.ts`, derived from the same frozen file views the
panes render. App reads it through a ref so the dispatch table stays stable.
panes render plus a copied source address for the active current-line cursor.
App reads it through a ref so the dispatch table stays stable while line
navigation moves.

`src/ui/lib/extensionNavigation.ts` mints the guarded navigation behind both
`ctx.navigation` and a pane's `actions`, so a jump from either surface is
Expand Down
22 changes: 13 additions & 9 deletions docs/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,8 +278,9 @@ new instances and run that shutdown/startup pair around the replacement.

### `hunk.apiVersion`

The API generation this Hunk speaks (currently `6`). Branch on it if you want
one file to support several Hunk versions. Version 6 adds session behavior,
The API generation this Hunk speaks (currently `7`). Branch on it if you want
one file to support several Hunk versions. Version 7 adds the current source
line to command selection snapshots. Version 6 adds session behavior,
terminal-command observation, and live navigation/dialogs in event handlers;
version 5 added line highlighters and line-granular navigation (`revealLine`);
version 4 added keyboard modes and docked panes, with API-v3 sidebar names
Expand Down Expand Up @@ -1352,13 +1353,16 @@ hunk.registerCommand(
```

`selection.file` is a frozen read-only view, identical to the entries in a
pane's `files` prop. Hunk keeps the selection inside the visible files, so
it is `null` only when nothing is visible at all — a filter that matches no
files. `selection.hunkIndex` is that file's
selected hunk, and `null` whenever `file` is — or when the file has no hunks to
select. The values are captured when the command fires: a handler that awaits
still sees the selection it was run from, not wherever the user navigated to
meanwhile.
pane's `files` prop. Extensions only receive visible files, so it is `null`
when filtering hides the selected file or when no files are visible.
`selection.hunkIndex` is that file's selected hunk, and `null` whenever `file`
is — or when the file has no hunks to select. `selection.currentLine` is the
one-based `{ side, line }` source address carrying the current-line marker, or
`null` when the marker is off or the review has not settled on a rendered line.
It belongs to this file and hunk, uses Hunk's canonical new-side address for a
context row, and can be passed directly to `navigation.revealLine`. The values
are captured when the command fires: a handler that awaits still sees the
selection it was run from, not wherever the user navigated to meanwhile.

`ctx.commands` invokes Hunk's documented semantic commands through the exact same live command
table used by the keyboard, menus, and help:
Expand Down
7 changes: 6 additions & 1 deletion scripts/check-pack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,13 @@ import type {
export default function (hunk: HunkExtensionAPI) {
const sessionOptions: ExtensionSessionOptions = { viewPreferences: "transient" };
hunk.configureSession(sessionOptions);
const noSelection: ExtensionReviewSelection = { file: null, hunkIndex: null };
const noSelection: ExtensionReviewSelection = {
file: null,
hunkIndex: null,
currentLine: null,
};
hunk.log(noSelection.file === null ? "nothing selected" : noSelection.file.path);
hunk.log(noSelection.currentLine?.side ?? "no current line");

const theme: NamedCustomThemeConfig = {
id: "midnight-review",
Expand Down
7 changes: 4 additions & 3 deletions skills/hunk-extensions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ bad or duplicate id is skipped with a startup notice.
| React to loads, selection, view movement, notes, reloads | `hunk.on(event, handler)` |
| Coordinate with another loaded extension | `hunk.events.emit` / `hunk.events.on` |
| Read user-supplied settings | `hunk.config` (`[extension.<id>]` table) |
| Branch on the API generation (currently `6`) | `hunk.apiVersion` |
| Branch on the API generation (currently `7`) | `hunk.apiVersion` |

Registration is only valid while the factory runs — Hunk seals the API object
afterwards.
Expand All @@ -124,8 +124,9 @@ transform — gets `ctx.cwd` and `ctx.notify(message, type?)`. A file view's
`ctx.events.emit`. `ctx.sidebars` is a deprecated alias for `ctx.panes`.
- **Command handlers** get `ctx.panes`, `ctx.fileViews` (select/toggle/isActive/
refresh/enterMode/exitMode), `ctx.highlights` (refresh prepared line marks,
whole or `{ fileId }`-scoped), `ctx.selection` (a snapshot of file + hunk index),
`ctx.navigation` (live, guarded `selectFile`/`selectHunk`/`revealLine`, the
whole or `{ fileId }`-scoped), `ctx.selection` (a snapshot of file, hunk index,
and nullable current `{ side, line }` source address), `ctx.navigation` (live,
guarded `selectFile`/`selectHunk`/`revealLine`, the
last landing one exact `(side, line)` near the viewport top), `ctx.commands`
(`isEnabled`/`execute` for public semantic `hunk.*` commands),
`ctx.keyboardModes` (enter/exit/probe this extension's session modes), `ctx.dialogs`
Expand Down
23 changes: 17 additions & 6 deletions src/extension-api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
* Extensions can branch on `hunk.apiVersion` so a newer Hunk can keep loading
* older extensions without guessing at their expectations.
*/
export const HUNK_EXTENSION_API_VERSION = 6;
export const HUNK_EXTENSION_API_VERSION = 7;
export type HunkExtensionApiVersion = typeof HUNK_EXTENSION_API_VERSION;

export type ExtensionNotifyType = "info" | "warning" | "error";
Expand Down Expand Up @@ -1376,11 +1376,9 @@ export interface ExtensionReviewSelection {
* The selected file among the currently visible (filtered) files, or `null`.
*
* The same frozen read-only view a pane component receives in its `files`
* prop, so holding or mutating it cannot reach the review model. Hunk keeps
* the selection inside the visible list — filtering away the selected file
* immediately reselects the first visible one — so in practice this is
* `null` only when nothing is visible at all, such as a filter matching no
* files.
* prop, so holding or mutating it cannot reach the review model. Extensions
* only receive visible files, so this is `null` when filtering hides the
* selected file or when no files are visible.
*/
readonly file: ExtensionDiffFile | null;
/**
Expand All @@ -1389,6 +1387,19 @@ export interface ExtensionReviewSelection {
* hunks to select (a binary or skipped file).
*/
readonly hunkIndex: number | null;
/**
* The source line carrying Hunk's current-line marker, or `null` when line
* navigation is off or the review has not settled on a rendered line yet.
*
* `line` is one-based on `side`, matching patch line numbers and
* `navigation.revealLine`. Context rows use Hunk's canonical new-side
* address. This copied, frozen target belongs to `file` and `hunkIndex` in
* this same snapshot; it never exposes renderer cursor state.
*/
readonly currentLine: {
readonly side: ExtensionFileSide;
readonly line: number;
} | null;
}

/** One question put to the user as a modal confirm dialog. */
Expand Down
19 changes: 14 additions & 5 deletions src/ui/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -520,8 +520,16 @@ export function App({
source: typeof filteredFiles;
views: ReturnType<typeof toReadOnlyFileViews>;
} | null>(null);
const extensionSelectionInputsRef = useRef({ filteredFiles, selectedFileId, selectedHunkIndex });
extensionSelectionInputsRef.current = { filteredFiles, selectedFileId, selectedHunkIndex };
const extensionSelectionInputsRef = useRef({
filteredFiles,
getSelection: review.getSelection,
getActiveLineCursor: () => (cursorLine === "off" ? null : review.getLineCursor()),
});
extensionSelectionInputsRef.current = {
filteredFiles,
getSelection: review.getSelection,
getActiveLineCursor: () => (cursorLine === "off" ? null : review.getLineCursor()),
};
// What `ctx.workspace` decides against, re-read on every render because a soft
// reload swaps the bootstrap under a mounted App: the input can change what is
// writable at all, and the changeset decides which ids exist and which source
Expand Down Expand Up @@ -604,17 +612,18 @@ export function App({

/** Build the selection snapshot a command handler receives, at invocation. */
const getExtensionSelection = useCallback(() => {
const { selectedFileId: fileId, selectedHunkIndex: hunkIndex } =
extensionSelectionInputsRef.current;
const { getSelection, getActiveLineCursor } = extensionSelectionInputsRef.current;
const { fileId, hunkIndex } = getSelection();
return buildExtensionReviewSelection({
files: getExtensionFileViews(),
selectedFileId: fileId,
selectedHunkIndex: hunkIndex,
lineCursor: getActiveLineCursor(),
});
}, [getExtensionFileViews]);
/** Read the live internal selection id independently from the frozen public selection. */
const getSelectedFileId = useCallback(
() => extensionSelectionInputsRef.current.selectedFileId,
() => extensionSelectionInputsRef.current.getSelection().fileId,
[],
);
const jumpToFile = useCallback(
Expand Down
105 changes: 96 additions & 9 deletions src/ui/AppHost.extension-sidebar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "bun:test";
import { KeyEvent, type ParsedKey } from "@opentui/core";
import { testRender } from "@opentui/react/test-utils";
import { act } from "react";
import { removeTestDirectory } from "../../test/helpers/filesystem";
Expand Down Expand Up @@ -43,6 +44,23 @@ function createTempDir(prefix: string) {
return dir;
}

/** Build one key event to publish without allowing a render between input events. */
function createTestKeyEvent(fields: Partial<ParsedKey>): KeyEvent {
return new KeyEvent({
name: "",
sequence: "",
raw: "",
ctrl: false,
meta: false,
option: false,
shift: false,
number: false,
eventType: "press",
source: "raw",
...fields,
});
}

/** Create a Git checkout with two committed files carrying working-tree changes. */
function createTestRepo(prefix: string) {
const repo = createTempDir(prefix);
Expand Down Expand Up @@ -274,12 +292,19 @@ describe("extension sidebar views", () => {
`export default function (hunk) {\n` +
` hunk.registerCommand({ id: "probe", title: "Probe selection", key: "y" }, (ctx) => {\n` +
` const file = ctx.selection.file;\n` +
` const line = ctx.selection.currentLine;\n` +
` appendFileSync(\n` +
` ${JSON.stringify(logPath)},\n` +
` "selection " + (file ? file.path : "none") + "#" + ctx.selection.hunkIndex +\n` +
` " frozen=" + Object.isFrozen(file) + "\\n",\n` +
` " line=" + (line ? line.side + ":" + line.line : "none") +\n` +
` " frozen=" + Object.isFrozen(file) + "/" + Object.isFrozen(line) + "\\n",\n` +
` );\n` +
` });\n` +
` hunk.registerCommand({ id: "delayed", title: "Probe delayed selection", key: "x" }, async (ctx) => {\n` +
` const line = ctx.selection.currentLine;\n` +
` await Bun.sleep(100);\n` +
` appendFileSync(${JSON.stringify(logPath)}, "delayed " + (line ? line.side + ":" + line.line : "none") + "\\n");\n` +
` });\n` +
`}\n`,
);

Expand All @@ -298,24 +323,86 @@ describe("extension sidebar views", () => {
});
await flushUntil(
setup,
() => readProbeLog(logPath).includes("selection alpha.txt#0 frozen=true"),
() => readProbeLog(logPath).some((line) => line.startsWith("selection alpha.txt#0 line=")),
"the command to report the startup selection",
);
const initialSelection = readProbeLog(logPath).find((line) =>
line.startsWith("selection alpha.txt#0 line="),
);
expect(initialSelection).toMatch(/line=new:1 frozen=true\/true$/);

// `]` moves the review stream to the next hunk, which is the one hunk of
// the second file; the next run reports the new selection rather than a
// snapshot captured when the command was registered.
// These events share one input flush. The line move updates the review
// controller's ref before React renders, so the following command must
// still observe line 2 instead of the previous rendered line.
await act(async () => {
await setup.mockInput.typeText("]");
setup.renderer.keyInput.emit("keypress", createTestKeyEvent({ name: "x", sequence: "x" }));
setup.renderer.keyInput.emit("keypress", createTestKeyEvent({ name: "j", sequence: "j" }));
setup.renderer.keyInput.emit("keypress", createTestKeyEvent({ name: "y", sequence: "y" }));
});
await flush(setup);
await flushUntil(
setup,
() =>
readProbeLog(logPath).filter((line) => line.startsWith("selection alpha.txt#0")).length >=
2,
"the command to report the moved current line",
);
const alphaSelections = readProbeLog(logPath).filter((line) =>
line.startsWith("selection alpha.txt#0"),
);
expect(alphaSelections[1]).toBe("selection alpha.txt#0 line=new:2 frozen=true/true");
await flushUntil(
setup,
() => readProbeLog(logPath).includes("delayed new:1"),
"the delayed handler to retain its invocation-time current line",
);

// Crossing into beta updates both the cursor and semantic selection in
// one input flush. The command must receive them as one coherent address.
await act(async () => {
setup.renderer.keyInput.emit("keypress", createTestKeyEvent({ name: "j", sequence: "j" }));
setup.renderer.keyInput.emit("keypress", createTestKeyEvent({ name: "y", sequence: "y" }));
});
await flushUntil(
setup,
() =>
readProbeLog(logPath).some((line) =>
/^selection beta\.txt#0 line=new:1 frozen=true\/true$/.test(line),
),
"the command to report the current line and selection after crossing files",
);
});
});

test("a command handler reports no current line when the marker is off", async () => {
const repo = createTestRepo("hunk-ext-selection-line-off-");
const extDir = createTempDir("hunk-ext-selection-line-off-ext-");
const logPath = join(extDir, "probe.log");
const extPath = join(extDir, "ext.ts");
writeFileSync(
extPath,
`import { appendFileSync } from "node:fs";\n` +
`export default function (hunk) {\n` +
` hunk.registerCommand({ id: "probe", title: "Probe selection", key: "y" }, (ctx) => {\n` +
` appendFileSync(${JSON.stringify(logPath)}, String(ctx.selection.currentLine === null) + "\\n");\n` +
` });\n` +
`}\n`,
);

const bootstrap = await launchWithExtension(repo, extPath);
bootstrap.initialCursorLine = "off";
await withAppHost(bootstrap, async (setup) => {
await flushUntil(
setup,
() => setup.captureCharFrame().includes("alpha.txt"),
"the review to render with its current-line marker disabled",
);
await act(async () => {
await setup.mockInput.typeText("y");
});
await flushUntil(
setup,
() => readProbeLog(logPath).includes("selection beta.txt#0 frozen=true"),
"the command to report the selection after navigating",
() => readProbeLog(logPath).includes("true"),
"the command to receive a null current line",
);
});
});
Expand Down
1 change: 1 addition & 0 deletions src/ui/fileViews/useFilePresentationController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ async function renderController(initial: HarnessState) {
files: live.current.visibleFileViews,
selectedFileId: live.current.state.selectedFileId,
selectedHunkIndex: 0,
lineCursor: null,
}),
[],
);
Expand Down
15 changes: 15 additions & 0 deletions src/ui/hooks/useTerminalReview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ export interface TerminalReview {
showAgentNotes: boolean;
userNotesByFileId: Record<string, UserReviewNote[]>;
lineCursor: LineCursor | null;
/** Read the current cursor synchronously between terminal key events. */
getLineCursor: () => LineCursor | null;
/** Read the current normalized selection synchronously with the cursor. */
getSelection: () => { fileId: string | null; hunkIndex: number | null };
lineCursorRevealRequest: LineCursorRevealRequest;
anchorLineCursor: (cursor: LineCursor) => void;
/** Adopt the hunk a viewport settled on, without asking any viewport to move. */
Expand Down Expand Up @@ -384,6 +388,8 @@ export function useTerminalReview({
// A held key drains as one stdin chunk, so every press in the burst would otherwise read the
// same pre-batch state and the cursor would advance a single row.
const lineCursorRef = useRef<LineCursor | null>(null);
/** Read the latest cursor without waiting for React to publish a render. */
const getLineCursor = useCallback(() => lineCursorRef.current, []);
const [lineCursorRevealRequest, setLineCursorRevealRequest] = useState<LineCursorRevealRequest>({
id: 0,
placement: "nearest",
Expand Down Expand Up @@ -477,6 +483,13 @@ export function useTerminalReview({
: undefined;
const selectedHunk = selectedFile?.metadata.hunks[selectedHunkIndex];

/** Read the normalized selection from the store without waiting for a React render. */
const getSelection = useCallback(() => {
const selection = selectNormalizedSelection(store.getSnapshot());
const file = selection.fileKey ? fileByKey.get(selection.fileKey) : undefined;
return { fileId: file?.id ?? null, hunkIndex: file ? selection.hunkIndex : null };
}, [fileByKey, store]);

/** Run one semantic intent against the review store. */
const runIntent = useCallback(
<T extends ReviewIntent>(intent: T, facts?: ReviewIntentFacts) =>
Expand Down Expand Up @@ -1428,6 +1441,8 @@ export function useTerminalReview({
liveCommentSummaries,
liveCommentsByFileId,
lineCursor,
getLineCursor,
getSelection,
lineCursorRevealRequest,
reviewNoteCount: reviewNoteSummaries.length,
reviewNoteSummaries,
Expand Down
Loading
Loading