Skip to content
Open
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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# Changelog

## 0.27.1

### Changed

- **A program's explanation is a hint, not a comment.** When a program on your computer shows you lines with an
explanation (the bridge), the explanation appears after the first line, in the inlay hints' colours, with the whole
text in a hover on the lines. It goes away when you edit the file, move the caret out of the lines, press Esc, or
when the program shows something else. Nothing is saved.
- **The bridge tries every address it is given.** `bridge.json` may list several addresses in `urls`; Code Notes tries
each in turn and keeps the one that answers. Inside WSL, a program on Windows can list the Windows host's address
(WSL's default gateway), so it is found without mirrored networking.

## 0.27.0

### Added
Expand Down
30 changes: 20 additions & 10 deletions docs/bridge.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,15 @@ While it runs, the controller writes a discovery file and removes it when it exi

| field | |
|---|---|
| `url` | where to dial: `ws://` on a loopback address (`127.x.x.x`, `localhost`, `[::1]`); any other is ignored |
| `url` | where to dial: `ws://` on a loopback address (`127.x.x.x`, `localhost`, `[::1]`) or, inside WSL, on the Windows host's (below); any other is ignored |
| `urls` | optional: more addresses of the same kinds, dialled in order after `url` (either one alone is enough) |
| `token` | a secret the extension sends back in its hello, so the controller knows the caller read this file |
| `name` | shown as the author of the controller's explanations and notes (default `Controller`) |

The extension dials the addresses in turn until one answers, and keeps that one: after a drop it dials it first, then
the others. An address that hasn't answered within 3 seconds gives way to the next. List every address the
controller may be reached on when it can't know which one the extension sees, as with WSL below.

Where the extension looks, in order (the first usable file wins):

1. `~/.code-notes/bridge.json` in the home of the machine the extension runs on.
Expand All @@ -31,15 +36,18 @@ Write the file with mode `0600`, and write it whole (a temporary file renamed ov
be used makes it hang up. With no file, the extension does nothing and says nothing. `codeNotes.bridge.enabled: false`
turns the bridge off.

From WSL, the extension dials `127.0.0.1` inside WSL: a controller on Windows is reached when WSL's **mirrored
networking** is on (`networkingMode=mirrored` in `%USERPROFILE%\.wslconfig`).
From WSL, a controller on Windows is reached on `127.0.0.1` when WSL's **mirrored networking** is on
(`networkingMode=mirrored` in `%USERPROFILE%\.wslconfig`). With WSL's default networking, WSL sees Windows on its
default gateway instead (`ip route show default` inside WSL; on Windows, the address of the `vEthernet (WSL)`
adapter): list it too, `"urls": ["ws://172.20.48.1:47321/v1/bridge"]`, and listen on it. Inside WSL, that address is
the only one besides loopback the extension dials: the token never leaves the computer.

## The connection

Every message is one JSON text frame. When a connection opens, the extension's first message is its hello:

```json
{"type": "hello", "protocol": 1, "token": "a long random string", "client": "code-notes", "version": "0.27.0",
{"type": "hello", "protocol": 1, "token": "a long random string", "client": "code-notes", "version": "0.27.1",
"window": {"folders": [{"name": "shop", "path": "/home/sam/shop", "uri": "file:///home/sam/shop"}],
"remoteName": "wsl", "wslDistro": "Ubuntu"}}
```
Expand All @@ -49,8 +57,8 @@ apart by its `window`. `path` is a path on the machine the extension runs on (in
`remoteName` is VS Code's (`wsl`, `ssh-remote`, … or `null` locally); `wslDistro` is `null` outside WSL. When the
window's folders change, the extension sends `{"type": "window", "window": {…}}`.

When the connection drops or can't be made, the extension dials again after 1 s, then 2, 4, 8, 16 and at most every
30 s, until the file changes or goes; a connection that opens starts the waits over at 1 s.
When the connection drops or none of the addresses can be reached, the extension dials again after 1 s, then 2, 4, 8,
16 and at most every 30 s, until the file changes or goes; a connection that opens starts the waits over at 1 s.

## Requests

Expand All @@ -68,10 +76,12 @@ folders (the first that has it). The extension sends no file contents or note bo

### `reveal`

`{file, start, end, text?}`: opens the file, lights the lines (with **← Back** above them, as a code link from a chat
does) and, with `text`, shows it under the lines as an explanation (Markdown; links and HTML are not run) until the
reader dismisses it or the next `reveal` replaces it. A `reveal` without `text` removes the last explanation. Result:
`{start, end}`, the lines lit (`end` stops at the file's last line).
`{file, start, end, text?}`: opens the file and lights the lines (with **← Back** above them, as a code link from a
chat does). With `text`, the explanation shows beside them as a hint: its first line, cut short, after the first
line lit, and the whole text (Markdown; links and HTML are not run) in a hover on the lines, under the controller's
`name`. The hint is not a note: nothing is saved. It goes when the reader edits the file, moves the caret out of the
lines, presses Esc, or when the next `reveal` arrives (one without `text` only removes it). Result: `{start, end}`,
the lines lit (`end` stops at the file's last line).

### `journey.play`

Expand Down
6 changes: 3 additions & 3 deletions docs/understanding-check.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ comment record "waived (approved by @bob)". GitLab doesn't re-run the job on an

## In CI

The recipes below download the CLI of the release they were written for (`v0.27.0`, this version);
The recipes below download the CLI of the release they were written for (`v0.27.1`, this version);
test/docs.test.ts keeps that tag and the actions' pins in step with the repository.

GitLab (`.gitlab-ci.yml`). `GITLAB_TOKEN`: a project access token with `api` scope (CI/CD variable, masked), used to
Expand All @@ -469,7 +469,7 @@ understanding:
allow_failure:
exit_codes: [3] # advisory mode: "passed with warnings", never blocks
script:
- curl -fsSL https://raw.githubusercontent.com/tomeyer97/code-notes/v0.27.0/cli/understanding.mjs -o /tmp/understanding.mjs
- curl -fsSL https://raw.githubusercontent.com/tomeyer97/code-notes/v0.27.1/cli/understanding.mjs -o /tmp/understanding.mjs
- node /tmp/understanding.mjs ci
```

Expand All @@ -496,7 +496,7 @@ jobs:
with:
node-version: 22
- run: |
curl -fsSL https://raw.githubusercontent.com/tomeyer97/code-notes/v0.27.0/cli/understanding.mjs -o /tmp/understanding.mjs
curl -fsSL https://raw.githubusercontent.com/tomeyer97/code-notes/v0.27.1/cli/understanding.mjs -o /tmp/understanding.mjs
node /tmp/understanding.mjs ci
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "code-notes",
"displayName": "Code Notes",
"description": "Understand code you did not write: notes your coding agent answers, journeys through how it works, and an understanding check before you merge.",
"version": "0.27.0",
"version": "0.27.1",
"publisher": "tomeyer97",
"license": "MIT",
"icon": "media/icon.png",
Expand Down Expand Up @@ -920,6 +920,11 @@
"command": "codeNotes.closeNoteBox",
"key": "escape",
"when": "commentEditorFocused && commentController == codeNotes && commentThreadIsEmpty"
},
{
"command": "codeNotes.dismissExplanation",
"key": "escape",
"when": "codeNotes.explanationShown && editorTextFocus && !suggestWidgetVisible && !findWidgetVisible && !inSnippetMode && !codeNotes.moving"
}
],
"menus": {
Expand Down Expand Up @@ -982,11 +987,6 @@
}
],
"comments/commentThread/title": [
{
"command": "codeNotes.dismissExplanation",
"group": "navigation@9",
"when": "commentController == codeNotes.bridge"
},
{
"command": "codeNotes.cancelClaude",
"group": "navigation@1",
Expand Down Expand Up @@ -1537,7 +1537,7 @@
},
{
"command": "codeNotes.dismissExplanation",
"when": "false"
"when": "codeNotes.explanationShown"
}
],
"explorer/context": [
Expand Down
2 changes: 2 additions & 0 deletions scripts/keymap.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ export const OTHERS = [
{ command: 'codeNotes.moveToSelection', key: 'enter', when: 'codeNotes.moving && editorTextFocus && !suggestWidgetVisible' },
// Esc in an empty new note box closes it and keeps the draft.
{ command: 'codeNotes.closeNoteBox', key: 'escape', when: 'commentEditorFocused && commentController == codeNotes && commentThreadIsEmpty' },
// Esc puts away a controller's explanation beside the code (the bridge), unless the editor has its own use for it.
{ command: 'codeNotes.dismissExplanation', key: 'escape', when: 'codeNotes.explanationShown && editorTextFocus && !suggestWidgetVisible && !findWidgetVisible && !inSnippetMode && !codeNotes.moving' },
]

/**
Expand Down
44 changes: 0 additions & 44 deletions src/bridge/callout.ts

This file was deleted.

6 changes: 3 additions & 3 deletions src/bridge/failure.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
// What every handler shares: the failure it says as it is, and what it has besides its params.
import type { Read } from '../core/bridge/requests'
import type { BridgeTarget } from '../core/bridge/discovery'
import type { Callout } from './callout'
import type { ExplanationHint } from './hint'

/** A failure to say as it is (a missing file, an unknown journey), not a bug to log. */
export class RequestError extends Error {}

/** What a handler has besides its params: who asks (its name is a note's author) and the callout. */
export interface HandlerContext { controller: BridgeTarget; callout: Callout }
/** What a handler has besides its params: who asks (its name is a note's author) and the explanation hint. */
export interface HandlerContext { controller: BridgeTarget; hint: ExplanationHint }

/** The params read, or the reason as the request's error. */
export function valid<T>(r: Read<T>): T {
Expand Down
83 changes: 83 additions & 0 deletions src/bridge/hint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// A controller's explanation in the editor: a short label after the first revealed line, the whole text in a hover on
// the lines. Transient (core/bridge/hint.ts says what ends it): no comment thread, no CodeLens, nothing saved. Drawn
// in the inlay hints' colours, so it follows the theme; the label is one line, cut, so it fits a narrow editor.
import * as vscode from 'vscode'
import { HintState, hintLabel, TransientHint } from '../core/bridge/hint'
import { setCtx } from '../platform/context'
import { setDecorations } from '../platform/editorDecorations'
import { fireAndForget } from '../platform/run'

/** True while a hint is shown: Esc dismisses it then (the manifest's key). */
export const HINT_SHOWN_KEY = 'codeNotes.explanationShown'

const hintType = () => vscode.window.createTextEditorDecorationType({
after: {
color: new vscode.ThemeColor('editorInlayHint.foreground'),
backgroundColor: new vscode.ThemeColor('editorInlayHint.background'),
fontStyle: 'italic',
margin: '0 0 0 2em',
},
})

export class ExplanationHint implements vscode.Disposable {
private readonly type = hintType()
private readonly hint = new TransientHint(() => this.changed())
private readonly subs: vscode.Disposable[] = [
vscode.window.onDidChangeVisibleTextEditors(() => this.paint()),
vscode.workspace.onDidChangeTextDocument((e) => {
if (e.contentChanges.length) this.hint.notice({ kind: 'edit', uri: e.document.uri.toString() })
}),
vscode.window.onDidChangeTextEditorSelection((e) => {
const caret = e.selections[0]?.active
if (caret) this.hint.notice({ kind: 'selection', uri: e.textEditor.document.uri.toString(), line: caret.line })
}),
]

/** Shows `text` (Markdown, its links and HTML not run) beside lines start..end (0-based) of `uri`. */
show(uri: vscode.Uri, start: number, end: number, text: string, author: string): void {
this.hint.show({ uri: uri.toString(), start, end, text, author })
}

/** Esc, a reveal without text, or the command. */
dismiss(): void { this.hint.dismiss() }

/** For tests: what is shown (none: dismissed). */
get state(): HintState | undefined { return this.hint.state }

dispose(): void {
this.hint.dismiss()
this.type.dispose()
for (const s of this.subs) s.dispose()
}

private changed(): void {
fireAndForget(setCtx(HINT_SHOWN_KEY, !!this.hint.state), 'bridge: setCtx codeNotes.explanationShown')
this.paint()
}

private paint(): void {
const shown = this.hint.state
for (const ed of vscode.window.visibleTextEditors) {
const here = shown && ed.document.uri.toString() === shown.uri
setDecorations(ed, this.type, here ? decorations(shown, ed.document) : [])
}
}
}

/** The label at the end of the first line (no hover of its own), and the hover over all the lines. */
function decorations(s: HintState, doc: vscode.TextDocument): vscode.DecorationOptions[] {
const last = Math.min(s.end, doc.lineCount - 1)
const firstEnd = doc.lineAt(Math.min(s.start, last)).range.end
return [
{ range: new vscode.Range(firstEnd, firstEnd), renderOptions: { after: { contentText: hintLabel(s.text) } } },
{ range: new vscode.Range(s.start, 0, last, doc.lineAt(last).range.end.character), hoverMessage: hover(s) },
]
}

/** The author, then the text as Markdown that runs nothing: no command links, no HTML. */
function hover(s: HintState): vscode.MarkdownString {
const md = new vscode.MarkdownString()
md.isTrusted = false
md.supportHtml = false
return md.appendText(`${s.author}:`).appendMarkdown(`\n\n${s.text}`)
}
18 changes: 9 additions & 9 deletions src/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import { extVersion, log } from '../platform/host'
import { registerCommands } from '../platform/registerCommands'
import { fireAndForget } from '../platform/run'
import { cfg } from '../platform/settings'
import { Callout } from './callout'
import { handleRequest } from './handlers'
import { bridgePaths, nodeTimers, readText, webSocketDialer } from './machine'
import { ExplanationHint } from './hint'
import { bridgeHosts, bridgePaths, nodeTimers, readText, webSocketDialer } from './machine'
import { BridgePorts, useBridgePorts } from './ports'
import { windowInfo } from './window'

export interface BridgeFeature {
/** Looks for a controller from now on (once everything is shown: its first request finds the journeys read). */
start(): void
/** For tests: the discovery file used, the connection, the explanation shown. */
snapshot(): { file?: string; target?: string; connected: boolean; dials: number; callout: Callout['state'] }
snapshot(): { file?: string; target?: string; connected: boolean; dials: number; hint: ExplanationHint['state'] }
}

const enabled = () => cfg().get<boolean>('bridge.enabled', true)
Expand All @@ -32,16 +32,16 @@ const hello = (t: BridgeTarget): FromExtension =>

export function activateBridge(context: vscode.ExtensionContext, ports: BridgePorts): BridgeFeature {
useBridgePorts(ports)
const callout = new Callout()
const hint = new ExplanationHint()
const dial = webSocketDialer()
const client = dial && new BridgeClient({
dial, hello, timers: nodeTimers,
handle: (request, controller) => handleRequest(request, { controller, callout }),
handle: (request, controller) => handleRequest(request, { controller, hint }),
log: (line) => log().info(line),
})
let file: string | undefined
const watch = new DiscoveryWatch({
paths: () => bridgePaths(discoveryOverride()), read: readText, timers: nodeTimers,
paths: () => bridgePaths(discoveryOverride()), read: readText, hosts: bridgeHosts, timers: nodeTimers,
changed: (target, path) => {
file = path
if (target && !client) log().warn('bridge: this VS Code has no WebSocket (Node 22 or newer is needed): not connecting')
Expand All @@ -52,15 +52,15 @@ export function activateBridge(context: vscode.ExtensionContext, ports: BridgePo
if (enabled()) fireAndForget(watch.start(), 'bridge: read the discovery file')
else { watch.stop(); client?.use(undefined) }
}
registerCommands(context, { [Cmd.dismissExplanation]: () => callout.dismiss() })
registerCommands(context, { [Cmd.dismissExplanation]: () => hint.dismiss() })
let started = false
context.subscriptions.push(callout,
context.subscriptions.push(hint,
vscode.workspace.onDidChangeConfiguration((e) => { if (started && e.affectsConfiguration('codeNotes.bridge')) follow() }),
vscode.workspace.onDidChangeWorkspaceFolders(() => client?.send({ type: 'window', window: windowInfo() })),
{ dispose: () => { watch.stop(); client?.dispose() } },
)
return {
start: () => { started = true; follow() },
snapshot: () => ({ file, ...(client?.state ?? { connected: false, dials: 0 }), callout: callout.state }),
snapshot: () => ({ file, ...(client?.state ?? { connected: false, dials: 0 }), hint: hint.state }),
}
}
Loading
Loading