diff --git a/CHANGELOG.md b/CHANGELOG.md index a7ae72b..f113aed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/bridge.md b/docs/bridge.md index a63c49d..5ef0c2b 100644 --- a/docs/bridge.md +++ b/docs/bridge.md @@ -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. @@ -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"}} ``` @@ -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 @@ -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` diff --git a/docs/understanding-check.md b/docs/understanding-check.md index f42fd5c..a70865e 100644 --- a/docs/understanding-check.md +++ b/docs/understanding-check.md @@ -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 @@ -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 ``` @@ -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 }} diff --git a/package-lock.json b/package-lock.json index 63ac7d3..1302e1f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "code-notes", - "version": "0.27.0", + "version": "0.27.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "code-notes", - "version": "0.27.0", + "version": "0.27.1", "license": "MIT", "dependencies": { "elkjs": "0.10.0" diff --git a/package.json b/package.json index 766162d..2006f7d 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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": { @@ -982,11 +987,6 @@ } ], "comments/commentThread/title": [ - { - "command": "codeNotes.dismissExplanation", - "group": "navigation@9", - "when": "commentController == codeNotes.bridge" - }, { "command": "codeNotes.cancelClaude", "group": "navigation@1", @@ -1537,7 +1537,7 @@ }, { "command": "codeNotes.dismissExplanation", - "when": "false" + "when": "codeNotes.explanationShown" } ], "explorer/context": [ diff --git a/scripts/keymap.mjs b/scripts/keymap.mjs index c281076..c4dd7a1 100644 --- a/scripts/keymap.mjs +++ b/scripts/keymap.mjs @@ -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' }, ] /** diff --git a/src/bridge/callout.ts b/src/bridge/callout.ts deleted file mode 100644 index 8ad982c..0000000 --- a/src/bridge/callout.ts +++ /dev/null @@ -1,44 +0,0 @@ -// A controller's explanation beside the lines it revealed: a comment thread of its own (not a note: nothing is saved), -// open under the lines until the reader dismisses it (its ✕) or the next reveal replaces it. VS Code draws it, so it -// follows the theme and the editor's width. -import * as vscode from 'vscode' - -/** The controller's id: the manifest's Dismiss button is on its threads only (`commentController == …`). */ -export const CALLOUT_CONTROLLER = 'codeNotes.bridge' - -export interface CalloutState { uri: string; start: number; end: number; text: string; author: string } - -export class Callout implements vscode.Disposable { - private readonly controller = vscode.comments.createCommentController(CALLOUT_CONTROLLER, 'Code Notes: explanations') - private thread: vscode.CommentThread | undefined - private shown: CalloutState | undefined - - /** Shows `text` (Markdown, its links and HTML not run) under lines start..end (0-based) of `uri`. */ - show(uri: vscode.Uri, start: number, end: number, text: string, author: string): void { - this.dismiss() - const body = new vscode.MarkdownString(text) - body.isTrusted = false - body.supportHtml = false - const comment: vscode.Comment = { body, mode: vscode.CommentMode.Preview, author: { name: author } } - const thread = this.controller.createCommentThread(uri, new vscode.Range(start, 0, end, 0), [comment]) - thread.canReply = false - thread.label = 'Explanation' - thread.collapsibleState = vscode.CommentThreadCollapsibleState.Expanded - this.thread = thread - this.shown = { uri: uri.toString(), start, end, text, author } - } - - dismiss(): void { - this.thread?.dispose() - this.thread = undefined - this.shown = undefined - } - - /** For tests: what is shown (none: dismissed). */ - get state(): CalloutState | undefined { return this.shown && { ...this.shown } } - - dispose(): void { - this.dismiss() - this.controller.dispose() - } -} diff --git a/src/bridge/failure.ts b/src/bridge/failure.ts index 745e07a..bc9f973 100644 --- a/src/bridge/failure.ts +++ b/src/bridge/failure.ts @@ -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(r: Read): T { diff --git a/src/bridge/hint.ts b/src/bridge/hint.ts new file mode 100644 index 0000000..8f08274 --- /dev/null +++ b/src/bridge/hint.ts @@ -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}`) +} diff --git a/src/bridge/index.ts b/src/bridge/index.ts index 447a19f..888c64a 100644 --- a/src/bridge/index.ts +++ b/src/bridge/index.ts @@ -11,9 +11,9 @@ 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' @@ -21,7 +21,7 @@ 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('bridge.enabled', true) @@ -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') @@ -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 }), } } diff --git a/src/bridge/lines.ts b/src/bridge/lines.ts index 5800b3a..c4a782a 100644 --- a/src/bridge/lines.ts +++ b/src/bridge/lines.ts @@ -1,4 +1,4 @@ -// The two requests about lines of a file: reveal (lit, with the controller's text beside them) and note.add. +// The two requests about lines of a file: reveal (lit, with the controller's text as a hint beside them) and note.add. import * as vscode from 'vscode' import type { NoteAddParams, RevealParams } from '../protocol/bridge' import { addNote, claudeLinks } from './ports' @@ -14,14 +14,14 @@ async function fileOf(file: string) { return uri } -/** Opens the file, lights the lines (Back above them) and shows the text under them until dismissed. */ +/** Opens the file, lights the lines (Back above them) and shows the text beside them, until the reader moves on. */ export async function reveal(p: RevealParams, c: HandlerContext): Promise<{ start: number; end: number }> { const uri = await fileOf(p.file) await claudeLinks().light(uri, p.start - 1, p.end - 1) const lines = editorOf(uri)?.document.lineCount ?? p.end const end = Math.max(p.start, Math.min(p.end, lines)) - if (p.text) c.callout.show(uri, p.start - 1, end - 1, p.text, c.controller.name) - else c.callout.dismiss() + if (p.text) c.hint.show(uri, p.start - 1, end - 1, p.text, c.controller.name) + else c.hint.dismiss() return { start: p.start, end } } diff --git a/src/bridge/machine.ts b/src/bridge/machine.ts index 73ce1e9..21b037f 100644 --- a/src/bridge/machine.ts +++ b/src/bridge/machine.ts @@ -1,11 +1,13 @@ // The machine the extension runs on, for the bridge: its home, the discovery file's places (inside WSL also the -// Windows user's home, asked once), reading a file, and dialling a WebSocket (Node's own: no dependency). +// Windows user's home, asked once), reading a file, inside WSL the Windows host's address, and dialling a WebSocket +// (Node's own: no dependency). import { execFile } from 'child_process' import * as fs from 'fs' import * as os from 'os' import * as path from 'path' import { discoveryPaths, isWsl, RunProgram, windowsHomeInWsl } from '../core/bridge/discovery' import type { SocketLike } from '../core/bridge/client' +import { defaultGateway } from '../core/bridge/wslHost' /** cmd.exe and wslpath answer in well under a second; one that hangs (interop stuck) is given up. */ const RUN_TIMEOUT_MS = 5_000 @@ -28,6 +30,16 @@ export async function bridgePaths(override: string): Promise { export const readText = (file: string) => fs.promises.readFile(file, 'utf8').catch(() => undefined) +/** Inside WSL, the Windows host's address (the default gateway), read once: a controller there may list it. */ +let wslHosts: Promise | undefined +export const bridgeHosts = () => (wslHosts ??= windowsHosts()) + +async function windowsHosts(): Promise { + if (!isWsl(process.env, kernel())) return [] + const host = defaultGateway(await readText('/proc/net/route') ?? '') + return host ? [host] : [] +} + /** The WSL distro this runs in (none outside WSL). */ export const wslDistro = () => process.env.WSL_DISTRO_NAME || null diff --git a/src/core/bridge/client.ts b/src/core/bridge/client.ts index 0e59e84..b0cbb6e 100644 --- a/src/core/bridge/client.ts +++ b/src/core/bridge/client.ts @@ -1,5 +1,6 @@ -// The connection to a controller: dial its URL, say hello (with the token), answer each request, and dial again with -// a backoff when the connection drops or can't be made. Which controller (if any) is said from outside: use(target). +// The connection to a controller: dial its addresses in turn until one answers, say hello (with the token), answer +// each request, and dial again with a backoff when the connection drops or none can be reached: the address that +// connected first, then the others. Which controller (if any) is said from outside: use(target). // The socket, the timers and the handling are given, so this has no vscode and no network of its own (unit-tested // with a real WebSocket server in test/bridgeClient.test.ts). import type { BridgeRequest, BridgeResponse, FromExtension } from '../../protocol/bridge' @@ -18,6 +19,12 @@ export interface SocketLike { /** WebSocket.OPEN. */ const OPEN = 1 +/** + * How long a dial may take when there are several addresses, before the next one is tried. A wrong address may never + * answer (a firewall drops the packets): without this, the right one would wait for the system's own timeout. + */ +export const DIAL_TIMEOUT_MS = 3_000 + export interface Timers { set(fn: () => void, ms: number): unknown clear(handle: unknown): void @@ -31,11 +38,19 @@ export interface ClientDeps { handle(request: BridgeRequest, target: BridgeTarget): Promise timers: Timers log(line: string): void + /** DIAL_TIMEOUT_MS unless given (tests). */ + dialTimeoutMs?: number } export class BridgeClient { private target: BridgeTarget | undefined private socket: SocketLike | undefined + /** The address dialled or connected now. */ + private url: string | undefined + /** The addresses still to try in this round, in order. */ + private round: string[] = [] + /** The address that connected last: each round starts with it. */ + private preferred: string | undefined private retry: unknown private readonly backoff = new Backoff() /** Whether the drop of the open connection was said (one log line per drop, not one per dial). */ @@ -49,9 +64,10 @@ export class BridgeClient { if (sameTarget(target, this.target)) return this.hangUp() this.target = target + this.preferred = undefined this.backoff.reset() this.quietRetries = false - if (target) this.dial() + if (target) this.startRound() } /** Sends to the controller when connected (dropped otherwise: the next hello says it all again). */ @@ -59,45 +75,87 @@ export class BridgeClient { if (this.socket?.readyState === OPEN) this.socket.send(JSON.stringify(message)) } - /** For tests and the log: who, whether connected, how many dials so far. */ + /** For tests and the log: the address dialled or connected, whether connected, how many dials so far. */ get state(): { target?: string; connected: boolean; dials: number } { - return { target: this.target?.url, connected: this.socket?.readyState === OPEN, dials: this.dials } + const target = this.target && (this.url ?? this.target.urls[0]) + return { target, connected: this.socket?.readyState === OPEN, dials: this.dials } } dispose(): void { this.use(undefined) } - private dial(): void { + /** Every address once: the one that connected last first, then the others in the file's order. */ + private startRound(): void { + const urls = this.target!.urls + this.round = this.preferred ? [this.preferred, ...urls.filter((u) => u !== this.preferred)] : [...urls] + this.dialNext() + } + + /** The next address of the round; after the last, the backoff's wait and a new round. */ + private dialNext(): void { + const url = this.round.shift() + if (url) this.dial(url) + else this.later() + } + + private dial(url: string): void { const target = this.target! this.dials++ + this.url = url let socket: SocketLike try { - socket = this.deps.dial(target.url) + socket = this.deps.dial(url) } catch (e) { - this.deps.log(`bridge: can't dial ${target.url}: ${e}`) - this.later() + this.deps.log(`bridge: can't dial ${url}: ${e}`) + this.dialNext() return } this.socket = socket + let opened = false + const disarm = this.armDialTimeout(socket) socket.addEventListener('open', () => { if (this.socket !== socket) return + disarm() + opened = true + this.preferred = url this.backoff.reset() this.quietRetries = false - this.deps.log(`bridge: connected to ${target.name} (${target.url})`) + this.deps.log(`bridge: connected to ${target.name} (${url})`) socket.send(JSON.stringify(this.deps.hello(target))) }) socket.addEventListener('message', (e) => { if (typeof e.data === 'string') this.received(socket, target, e.data) }) // A dial that fails gets 'error' alone in Node (no 'close'); a drop gets both: the first one counts. const lost = () => { if (this.socket !== socket) return + disarm() this.socket = undefined if (!this.quietRetries) this.deps.log(`bridge: no connection to ${target.name}; trying again`) this.quietRetries = true - this.later() + // A drop waits, then dials every address again; an address that never answered gives way to the next one. + if (opened) this.later() + else this.dialNext() } socket.addEventListener('error', lost) socket.addEventListener('close', lost) } + /** + * With several addresses, gives `socket` DIAL_TIMEOUT_MS to open before the next address is tried (one address: + * nothing else to try, the system's own timeout is waited for). Returns what cancels it. + */ + private armDialTimeout(socket: SocketLike): () => void { + if (this.target!.urls.length < 2) return () => undefined + const timer = this.deps.timers.set(() => this.giveUp(socket), this.deps.dialTimeoutMs ?? DIAL_TIMEOUT_MS) + return () => this.deps.timers.clear(timer) + } + + /** A dial that took too long: closed, so the next address is tried (its 'close' or 'error' comes later or never). */ + private giveUp(socket: SocketLike): void { + if (this.socket !== socket) return + this.socket = undefined + try { socket.close() } catch { /* a socket still connecting may refuse to close: it is forgotten either way */ } + this.dialNext() + } + private received(socket: SocketLike, target: BridgeTarget, data: string): void { const request = readFrame(data) if (!request) return @@ -107,14 +165,16 @@ export class BridgeClient { ) } - /** The next dial, after the backoff's wait. */ + /** The next round, after the backoff's wait. */ private later(): void { - this.retry = this.deps.timers.set(() => { this.retry = undefined; if (this.target) this.dial() }, this.backoff.next()) + this.retry = this.deps.timers.set(() => { this.retry = undefined; if (this.target) this.startRound() }, this.backoff.next()) } private hangUp(): void { if (this.retry !== undefined) this.deps.timers.clear(this.retry) this.retry = undefined + this.round = [] + this.url = undefined const s = this.socket this.socket = undefined if (s) { diff --git a/src/core/bridge/discovery.ts b/src/core/bridge/discovery.ts index a533e71..5460945 100644 --- a/src/core/bridge/discovery.ts +++ b/src/core/bridge/discovery.ts @@ -1,9 +1,12 @@ // Finding a controller: the discovery file it writes (`~/.code-notes/bridge.json`, mode 0600) while it runs, read and -// checked here; where to look for it, inside WSL also in the Windows user's home. No vscode, no fs: the caller reads -// files and runs programs (unit-tested in test/bridgeDiscovery.test.ts). +// checked here (one address or several); where to look for it, inside WSL also in the Windows user's home. No vscode, +// no fs: the caller reads files and runs programs (unit-tested in test/bridgeDiscovery.test.ts). -/** What a discovery file says: where to dial, the token to show, and the controller's name (shown as the author). */ -export interface BridgeTarget { url: string; token: string; name: string } +/** + * What a discovery file says: the addresses to dial, in order (its `url`, then its `urls`), the token to show, and the + * controller's name (shown as the author). + */ +export interface BridgeTarget { urls: string[]; token: string; name: string } /** The discovery file's folder and name, under a home folder. */ export const DISCOVERY_DIR = '.code-notes' @@ -12,28 +15,37 @@ export const DISCOVERY_FILE = 'bridge.json' const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v.trim() !== '' /** - * A discovery file's text as a target, or undefined when it can't be used: not JSON, no token, or a URL that is not - * ws:// on this machine (a token is never sent off the machine, nor in clear text to another one). + * A discovery file's text as a target, or undefined when it can't be used: not JSON, no token, or no URL that is + * ws:// on this machine. A token is never sent off the machine, nor in clear text to another one: the only hosts + * allowed are loopback ones and `hosts` (inside WSL, the Windows host's address: wslHost.ts). */ -export function parseBridgeFile(text: string): BridgeTarget | undefined { +export function parseBridgeFile(text: string, hosts: readonly string[] = []): BridgeTarget | undefined { let v: unknown try { v = JSON.parse(text) } catch { return undefined } if (!v || typeof v !== 'object') return undefined - const { url, token, name } = v as Record - if (!nonEmpty(url) || !nonEmpty(token) || !isLocalWs(url)) return undefined - return { url, token, name: nonEmpty(name) ? name.trim() : 'Controller' } + const { url, urls, token, name } = v as Record + const usable = addresses(url, urls).filter((u) => isLocalWs(u, hosts)) + if (!usable.length || !nonEmpty(token)) return undefined + return { urls: usable, token, name: nonEmpty(name) ? name.trim() : 'Controller' } +} + +/** `url` then each of `urls`, the strings among them, each once. */ +function addresses(url: unknown, urls: unknown): string[] { + const all = [url, ...(Array.isArray(urls) ? urls : [])].filter(nonEmpty).map((u) => u.trim()) + return [...new Set(all)] } -/** ws:// to a loopback host (127.0.0.0/8, ::1, localhost). */ -export function isLocalWs(url: string): boolean { +/** ws:// to a loopback host (127.0.0.0/8, ::1, localhost) or to one of `hosts`. */ +export function isLocalWs(url: string, hosts: readonly string[] = []): boolean { let u: URL try { u = new URL(url) } catch { return false } if (u.protocol !== 'ws:') return false - return u.hostname === 'localhost' || u.hostname === '[::1]' || /^127(\.\d{1,3}){3}$/.test(u.hostname) + const host = u.hostname + return host === 'localhost' || host === '[::1]' || /^127(\.\d{1,3}){3}$/.test(host) || hosts.includes(host) } export const sameTarget = (a: BridgeTarget | undefined, b: BridgeTarget | undefined) => - a === b || (!!a && !!b && a.url === b.url && a.token === b.token && a.name === b.name) + a === b || (!!a && !!b && a.urls.join(' ') === b.urls.join(' ') && a.token === b.token && a.name === b.name) /** Where to look, in order: only `override` when it is set; else this home's file, then the Windows home's (WSL). */ export function discoveryPaths(o: { override?: string; home: string; windowsHome?: string; join(...p: string[]): string }): string[] { diff --git a/src/core/bridge/hint.ts b/src/core/bridge/hint.ts new file mode 100644 index 0000000..2abda30 --- /dev/null +++ b/src/core/bridge/hint.ts @@ -0,0 +1,51 @@ +// A controller's explanation as a transient hint beside the lines it revealed: what is shown, and what ends it. It +// lasts only while the reader looks at those lines: an edit in the file, the caret leaving the lines, Esc or the next +// reveal ends it. Nothing is saved. No vscode (unit-tested in test/bridgeHint.test.ts; bridge/hint.ts draws it). +import { plain } from '../text' + +/** What is shown: `text` (Markdown) beside lines start..end (0-based, inclusive) of the file `uri`. */ +export interface HintState { uri: string; start: number; end: number; text: string; author: string } + +/** What the reader did in a file. `line`: where the caret is now (0-based). (Esc and the command: dismiss().) */ +export type HintEvent = + | { kind: 'edit'; uri: string } + | { kind: 'selection'; uri: string; line: number } + +/** The longest label beside the line; the hover has the whole text. */ +export const LABEL_MAX = 120 + +/** The text beside the line: its first line, plain, cut to LABEL_MAX. */ +export const hintLabel = (text: string) => plain(text, LABEL_MAX) + +/** Whether `e` ends a hint shown at `shown`: an edit in its file, or the caret out of its lines (in its file). */ +export function endsHint(shown: HintState, e: HintEvent): boolean { + if (e.uri !== shown.uri) return false + return e.kind === 'edit' || e.line < shown.start || e.line > shown.end +} + +/** The hint shown, if any; `changed` is told each time it appears, is replaced or goes. */ +export class TransientHint { + private shown: HintState | undefined + + constructor(private readonly changed: (state: HintState | undefined) => void) {} + + /** Shows a hint, replacing the one before. */ + show(state: HintState): void { + this.shown = { ...state } + this.changed(this.state) + } + + /** Ends the hint, if `e` ends it. */ + notice(e: HintEvent): void { + if (this.shown && endsHint(this.shown, e)) this.dismiss() + } + + /** Ends the hint whatever it is (Esc, the command, a reveal without text). */ + dismiss(): void { + if (!this.shown) return + this.shown = undefined + this.changed(undefined) + } + + get state(): HintState | undefined { return this.shown && { ...this.shown } } +} diff --git a/src/core/bridge/requests.ts b/src/core/bridge/requests.ts index 93dbecd..2861b9e 100644 --- a/src/core/bridge/requests.ts +++ b/src/core/bridge/requests.ts @@ -8,7 +8,7 @@ export type Read = { ok: true; value: T } | { ok: false; error: string } const ok = (value: T): Read => ({ ok: true, value }) const no = (error: string): Read => ({ ok: false, error }) -/** The longest text a callout or note takes: a controller's explanation, not a file. */ +/** The longest text an explanation or a note takes: a controller's explanation, not a file. */ export const MAX_TEXT = 20_000 /** A frame as a request: undefined when it is not one (no id to answer: nothing is sent back). */ diff --git a/src/core/bridge/watch.ts b/src/core/bridge/watch.ts index 3369540..c019d29 100644 --- a/src/core/bridge/watch.ts +++ b/src/core/bridge/watch.ts @@ -12,6 +12,8 @@ export interface WatchDeps { paths(): Promise /** A file's text; undefined when it can't be read (missing). */ read(path: string): Promise + /** Hosts besides loopback the token may go to (inside WSL: the Windows host); none when not given. */ + hosts?(): Promise /** The target changed (undefined: there is none now). */ changed(target: BridgeTarget | undefined, path: string | undefined): void timers: Timers @@ -19,10 +21,10 @@ export interface WatchDeps { } /** The first usable discovery file among `paths`, with its path. */ -export async function findTarget(paths: string[], read: WatchDeps['read']): Promise<{ target: BridgeTarget; path: string } | undefined> { +export async function findTarget(paths: string[], read: WatchDeps['read'], hosts: readonly string[] = []): Promise<{ target: BridgeTarget; path: string } | undefined> { for (const path of paths) { const text = await read(path) - const target = text === undefined ? undefined : parseBridgeFile(text) + const target = text === undefined ? undefined : parseBridgeFile(text, hosts) if (target) return { target, path } } return undefined @@ -59,7 +61,7 @@ export class DiscoveryWatch { private async readOnce(): Promise { if (this.stopped) return if (this.timer !== undefined) this.deps.timers.clear(this.timer) - const found = await findTarget(await this.deps.paths(), this.deps.read).catch(() => undefined) + const found = await this.find().catch(() => undefined) if (this.stopped) return if (!sameTarget(found?.target, this.current)) { this.current = found?.target @@ -67,4 +69,8 @@ export class DiscoveryWatch { } this.timer = this.deps.timers.set(() => { this.timer = undefined; this.check().catch(() => undefined) }, this.deps.pollMs ?? POLL_MS) } + + private async find() { + return findTarget(await this.deps.paths(), this.deps.read, (await this.deps.hosts?.()) ?? []) + } } diff --git a/src/core/bridge/wslHost.ts b/src/core/bridge/wslHost.ts new file mode 100644 index 0000000..e3aad33 --- /dev/null +++ b/src/core/bridge/wslHost.ts @@ -0,0 +1,17 @@ +// Inside WSL with its default (NAT) networking, Windows is not 127.0.0.1 but the guest's default gateway: a controller +// on Windows lists that address among its `urls`. It is still this computer, so the token may go there. Read from +// the kernel's route table (/proc/net/route); no vscode, no fs (unit-tested in test/bridgeDiscovery.test.ts). + +/** + * The default gateway in a /proc/net/route table, as a dotted IPv4 address; undefined when there is none. The table's + * addresses are hex in the kernel's byte order (little-endian on every machine WSL runs on). + */ +export function defaultGateway(routeTable: string): string | undefined { + for (const line of routeTable.split('\n').slice(1)) { + const [, destination, gateway] = line.trim().split(/\s+/) + if (destination !== '00000000' || !/^[0-9A-Fa-f]{8}$/.test(gateway ?? '') || gateway === '00000000') continue + const bytes = gateway.match(/../g)!.map((b) => parseInt(b, 16)) + return bytes.reverse().join('.') + } + return undefined +} diff --git a/src/protocol/bridge.ts b/src/protocol/bridge.ts index 6fcaf88..9f7a553 100644 --- a/src/protocol/bridge.ts +++ b/src/protocol/bridge.ts @@ -36,7 +36,7 @@ export type BridgeMethod = typeof BRIDGE_METHODS[number] /** 1-based, inclusive lines of a file: workspace-relative (in the window's first folder that has it) or absolute. */ export interface BridgeLines { file: string; start: number; end: number } -/** reveal: the lines opened and lit; `text` shown beside them until the reader dismisses it. */ +/** reveal: the lines opened and lit; `text` shown beside them as a hint until the reader moves on. */ export interface RevealParams extends BridgeLines { text?: string } /** journey.play: a journey (its id) walked from step `step` (its number, or its id; none: 1). */ export interface JourneyPlayParams { id: string; step?: number | string; folder?: string } diff --git a/test/bridgeClient.test.ts b/test/bridgeClient.test.ts index fb7ade1..37275b2 100644 --- a/test/bridgeClient.test.ts +++ b/test/bridgeClient.test.ts @@ -1,9 +1,11 @@ // The connection to a controller (src/core/bridge/client.ts, backoff.ts) against a real WebSocket server // (helpers/wsServer.ts) with Node's own WebSocket: the hello with the token, requests answered, dialling again after -// a drop with a backoff of 1 s to 30 s, and the discovery file (watch.ts) followed end to end. +// a drop with a backoff of 1 s to 30 s, several addresses tried in turn, and the discovery file (watch.ts) followed +// end to end. import { test } from 'node:test' import assert from 'node:assert/strict' import * as fs from 'fs' +import * as net from 'net' import * as os from 'os' import * as path from 'path' import { Backoff } from '../src/core/bridge/backoff' @@ -15,12 +17,20 @@ import { FakeController } from './helpers/wsServer' const dial = (url: string) => new WebSocket(url) as unknown as SocketLike -/** Real timers, a waited delay shortened to 10 ms; every delay asked for is kept. */ +/** The dial timeout in these tests: long enough for a dial on this machine, short enough to wait for. */ +const DIAL_TIMEOUT = 300 + +/** Real timers, a waited delay shortened to 10 ms; every delay asked for is kept. The dial timeout runs as it is and + * is not kept: it is no wait between dials. */ function fastTimers() { const asked: number[] = [] return { asked, - set: (fn: () => void, ms: number) => { asked.push(ms); return setTimeout(fn, 10) }, + set: (fn: () => void, ms: number) => { + if (ms === DIAL_TIMEOUT) return setTimeout(fn, ms) + asked.push(ms) + return setTimeout(fn, 10) + }, clear: (h: unknown) => clearTimeout(h as NodeJS.Timeout), } } @@ -29,14 +39,22 @@ function fastTimers() { function client(timers = fastTimers(), handle?: ClientDeps['handle']) { const log: string[] = [] const c = new BridgeClient({ - dial, timers, log: (l) => log.push(l), + dial, timers, log: (l) => log.push(l), dialTimeoutMs: DIAL_TIMEOUT, hello: (t) => ({ type: 'hello', protocol: 1, token: t.token, client: 'code-notes', version: '9.9.9', window: { folders: [], remoteName: null, wslDistro: 'Ubuntu' } }), handle: handle ?? (async (r: BridgeRequest): Promise => ({ type: 'response', id: r.id, ok: true, result: { echo: r.method } })), }) return { c, log, timers } } -const target = (ctl: FakeController, token = 'secret'): BridgeTarget => ({ url: ctl.url, token, name: 'Desk' }) +const target = (ctl: FakeController, token = 'secret'): BridgeTarget => ({ urls: [ctl.url], token, name: 'Desk' }) + +/** An address where nobody listens: a port taken, then freed. */ +async function deadUrl(): Promise { + const ctl = await new FakeController().listen() + const url = ctl.url + await ctl.close() + return url +} test('Backoff: 1 s doubling to 30 s; back to 1 s after a reset', () => { const b = new Backoff() @@ -133,6 +151,62 @@ test('use(): none hangs up for good; another target is dialled at once', async ( } finally { c.dispose(); await a.close(); await b.close() } }) +test('several addresses: the second is dialled at once when the first does not answer, and kept', async () => { + const dead = await deadUrl() + const ctl = await new FakeController().listen() + const { c, timers } = client() + try { + c.use({ urls: [dead, ctl.url], token: 'secret', name: 'Desk' }) + assert.equal((await ctl.until('hello', () => ctl.received[0])).token, 'secret') + assert.deepEqual(c.state, { target: ctl.url, connected: true, dials: 2 }) + assert.deepEqual(timers.asked, [], 'no wait between the addresses of a round') + } finally { c.dispose(); await ctl.close() } +}) + +test('several addresses: after a drop and the wait, the one that connected is dialled first', async () => { + const dead = await deadUrl() + const ctl = await new FakeController().listen() + const { c, timers } = client() + try { + c.use({ urls: [dead, ctl.url], token: 'secret', name: 'Desk' }) + await ctl.until('first hello', () => ctl.received.length === 1) + ctl.drop() + await ctl.until('second hello', () => ctl.received.length === 2 && ctl.connections === 2) + assert.deepEqual(timers.asked, [1000], 'the drop waits once') + assert.equal(c.state.dials, 3, 'the dead address is not tried before the one that connected') + } finally { c.dispose(); await ctl.close() } +}) + +test('several addresses, none answering: every one is tried each round, one wait per round', async () => { + const [a, b] = [await deadUrl(), await deadUrl()] + const { c, timers } = client() + try { + c.use({ urls: [a, b], token: 'secret', name: 'Desk' }) + await waitFor(() => timers.asked.length >= 3) + c.dispose() + assert.deepEqual(timers.asked.slice(0, 3), [1000, 2000, 4000]) + assert.ok(c.state.dials >= 6 && c.state.dials <= 8, `two dials per wait: ${c.state.dials}`) + } finally { c.dispose() } +}) + +test('several addresses: one that never answers is given up after the dial timeout', async () => { + const held: net.Socket[] = [] + const silent = net.createServer((socket) => { held.push(socket) }) // accepts, never answers the handshake + await new Promise((resolve) => silent.listen(0, '127.0.0.1', resolve)) + const ctl = await new FakeController().listen() + const { c, timers } = client() + try { + c.use({ urls: [`ws://127.0.0.1:${(silent.address() as net.AddressInfo).port}/`, ctl.url], token: 'secret', name: 'Desk' }) + await ctl.until('hello after the timeout', () => ctl.received[0]) + assert.equal(c.state.dials, 2) + assert.deepEqual(timers.asked, []) + } finally { + c.dispose(); await ctl.close() + for (const socket of held) socket.destroy() + silent.close() + } +}) + test('end to end with a discovery file: found, a new port followed, gone hangs up', async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bridge-')) const file = path.join(dir, 'bridge.json') diff --git a/test/bridgeDiscovery.test.ts b/test/bridgeDiscovery.test.ts index aa81ddd..978b338 100644 --- a/test/bridgeDiscovery.test.ts +++ b/test/bridgeDiscovery.test.ts @@ -1,19 +1,51 @@ -// The bridge's discovery (src/core/bridge/discovery.ts, watch.ts): the file a controller writes, where it is looked -// for (inside WSL also the Windows user's home), and the file followed as it appears, changes and goes. +// The bridge's discovery (src/core/bridge/discovery.ts, watch.ts, wslHost.ts): the file a controller writes (one +// address or several), where it is looked for (inside WSL also the Windows user's home), the Windows host's address +// inside WSL, and the file followed as it appears, changes and goes. import { test } from 'node:test' import assert from 'node:assert/strict' import * as path from 'path' import { discoveryPaths, isLocalWs, isWsl, parseBridgeFile, RunProgram, windowsHomeInWsl } from '../src/core/bridge/discovery' import { DiscoveryWatch, findTarget } from '../src/core/bridge/watch' import type { BridgeTarget } from '../src/core/bridge/discovery' +import { defaultGateway } from '../src/core/bridge/wslHost' const file = (o: object) => JSON.stringify(o) const good = { url: 'ws://127.0.0.1:7777/v1/bridge', token: 't0k', name: 'Desk' } +/** `good` as a target: its one address. */ +const goodTarget: BridgeTarget = { urls: [good.url], token: 't0k', name: 'Desk' } test('parseBridgeFile: url, token and name; a missing name reads "Controller"', () => { - assert.deepEqual(parseBridgeFile(file(good)), good) - assert.deepEqual(parseBridgeFile(file({ ...good, name: '' })), { ...good, name: 'Controller' }) - assert.deepEqual(parseBridgeFile(file({ ...good, name: ' Desk ', extra: 1 })), good, 'trimmed; unknown fields ignored') + assert.deepEqual(parseBridgeFile(file(good)), goodTarget) + assert.deepEqual(parseBridgeFile(file({ ...good, name: '' })), { ...goodTarget, name: 'Controller' }) + assert.deepEqual(parseBridgeFile(file({ ...good, name: ' Desk ', extra: 1 })), goodTarget, 'trimmed; unknown fields ignored') +}) + +test('parseBridgeFile: `urls` after `url`, in order, each once; unusable ones left out', () => { + const a = 'ws://127.0.0.1:1/b', b = 'ws://localhost:2/b' + assert.deepEqual(parseBridgeFile(file({ ...good, urls: [a, b] }))?.urls, [good.url, a, b]) + assert.deepEqual(parseBridgeFile(file({ token: 't', urls: [a, b] }))?.urls, [a, b], '`urls` alone is enough') + assert.deepEqual(parseBridgeFile(file({ token: 't', url: a, urls: [b, a, ` ${b} `] }))?.urls, [a, b]) + assert.deepEqual(parseBridgeFile(file({ token: 't', urls: ['ws://10.0.0.2:1/x', 7, '', b] }))?.urls, [b]) + assert.equal(parseBridgeFile(file({ token: 't', urls: ['ws://10.0.0.2:1/x'] })), undefined, 'no usable address') + assert.equal(parseBridgeFile(file({ token: 't', urls: 'ws://127.0.0.1:1/x' })), undefined, '`urls` is a list') +}) + +test('parseBridgeFile: a host allowed besides loopback (the Windows host inside WSL)', () => { + const host = 'ws://172.20.48.1:7777/v1/bridge' + assert.equal(parseBridgeFile(file({ token: 't', urls: [host] })), undefined, 'not allowed by default') + assert.deepEqual(parseBridgeFile(file({ ...good, urls: [host] }), ['172.20.48.1'])?.urls, [good.url, host]) + assert.equal(parseBridgeFile(file({ token: 't', urls: ['ws://172.20.48.2:1/x'] }), ['172.20.48.1']), undefined, 'only that host') +}) + +test('defaultGateway: the default route\'s gateway in /proc/net/route, as a dotted address', () => { + const table = [ + 'Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT', + 'eth0\t0030A8C0\t00000000\t0001\t0\t0\t0\t00F0FFFF\t0\t0\t0', + 'eth0\t00000000\t0130A8AC\t0003\t0\t0\t0\t00000000\t0\t0\t0', + ].join('\n') + assert.equal(defaultGateway(table), '172.168.48.1') + assert.equal(defaultGateway(table.split('\n').slice(0, 2).join('\n')), undefined, 'no default route') + assert.equal(defaultGateway(''), undefined) }) test('parseBridgeFile: unusable files are none (no token, not JSON, not a local ws:// URL)', () => { @@ -24,7 +56,9 @@ test('parseBridgeFile: unusable files are none (no token, not JSON, not a local } }) -test('isLocalWs: loopback hosts only', () => { +test('isLocalWs: loopback hosts, and the hosts it is given', () => { + assert.equal(isLocalWs('ws://172.20.48.1:1/', ['172.20.48.1']), true) + assert.equal(isLocalWs('wss://172.20.48.1:1/', ['172.20.48.1']), false, 'ws:// only') assert.equal(isLocalWs('ws://127.0.0.1:1/'), true) assert.equal(isLocalWs('ws://127.1.2.3:1/'), true) assert.equal(isLocalWs('ws://localhost:1/'), true) @@ -71,7 +105,7 @@ test('isWsl: the distro variable, or a Microsoft kernel', () => { test('findTarget: the first usable file in order', async () => { const files: Record = { '/b': 'broken', '/c': file(good), '/d': file({ ...good, name: 'Other' }) } const read = async (p: string) => files[p] - assert.deepEqual(await findTarget(['/a', '/b', '/c', '/d'], read), { target: good, path: '/c' }) + assert.deepEqual(await findTarget(['/a', '/b', '/c', '/d'], read), { target: goodTarget, path: '/c' }) assert.equal(await findTarget(['/a', '/b'], read), undefined) }) @@ -93,7 +127,7 @@ test('DiscoveryWatch: silent with no file; the target when it appears, changes a const watch = new DiscoveryWatch({ paths: async () => ['/home/u/.code-notes/bridge.json', '/mnt/c/Users/U/.code-notes/bridge.json'], read: async (p) => files[p], timers, pollMs: 50, - changed: (t: BridgeTarget | undefined, p) => changes.push(t ? `${t.name} ${t.url} @${p}` : undefined), + changed: (t: BridgeTarget | undefined, p) => changes.push(t ? `${t.name} ${t.urls.join(' ')} @${p}` : undefined), }) const poll = async () => { timers.tick(); await watch.check() } await watch.start() @@ -124,3 +158,21 @@ test('DiscoveryWatch: silent with no file; the target when it appears, changes a assert.equal(changes.at(-1), 'Desk ws://127.0.0.1:7777/v1/bridge @/home/u/.code-notes/bridge.json', 'started again: said again') watch.stop() }) + +test('DiscoveryWatch: the hosts it is given allow their addresses; a new address list is a new target', async () => { + const path = '/home/u/.code-notes/bridge.json' + const files: Record = { [path]: file({ ...good, urls: ['ws://172.20.48.1:7777/v1/bridge'] }) } + const timers = manualTimers() + const changes: string[][] = [] + const watch = new DiscoveryWatch({ + paths: async () => [path], read: async (p) => files[p], hosts: async () => ['172.20.48.1'], timers, + changed: (t) => changes.push(t?.urls ?? []), + }) + await watch.start() + assert.deepEqual(changes, [[good.url, 'ws://172.20.48.1:7777/v1/bridge']]) + files[path] = file({ ...good, urls: ['ws://127.0.0.2:7777/v1/bridge'] }) + timers.tick() + await watch.check() + assert.deepEqual(changes.at(-1), [good.url, 'ws://127.0.0.2:7777/v1/bridge']) + watch.stop() +}) diff --git a/test/bridgeHint.test.ts b/test/bridgeHint.test.ts new file mode 100644 index 0000000..8bdf16f --- /dev/null +++ b/test/bridgeHint.test.ts @@ -0,0 +1,70 @@ +// A controller's explanation as a transient hint (src/core/bridge/hint.ts): shown beside the revealed lines, gone on +// the next edit in that file, when the caret leaves the lines, on Esc (dismiss), or when another reveal replaces it. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { endsHint, HintState, hintLabel, LABEL_MAX, TransientHint } from '../src/core/bridge/hint' + +const FILE = 'file:///shop/src/cart.ts' +const OTHER = 'file:///shop/src/tax.ts' +const shown: HintState = { uri: FILE, start: 11, end: 19, text: 'Adds the **tax**, then rounds.', author: 'Desk' } + +/** A hint whose every change is kept (each state, none for gone). */ +function hint() { + const changes: (HintState | undefined)[] = [] + return { h: new TransientHint((s) => changes.push(s)), changes } +} + +test('endsHint: an edit in its file, the caret out of its lines', () => { + assert.equal(endsHint(shown, { kind: 'edit', uri: FILE }), true) + assert.equal(endsHint(shown, { kind: 'selection', uri: FILE, line: 10 }), true, 'above the lines') + assert.equal(endsHint(shown, { kind: 'selection', uri: FILE, line: 20 }), true, 'below the lines') +}) + +test('endsHint: the caret within its lines, or anything in another file, leaves it', () => { + for (const line of [11, 15, 19]) assert.equal(endsHint(shown, { kind: 'selection', uri: FILE, line }), false, `line ${line}`) + assert.equal(endsHint(shown, { kind: 'edit', uri: OTHER }), false) + assert.equal(endsHint(shown, { kind: 'selection', uri: OTHER, line: 0 }), false) +}) + +test('TransientHint: shown, replaced by the next reveal, gone on the first event that ends it', () => { + const { h, changes } = hint() + h.show(shown) + assert.deepEqual(h.state, shown) + h.notice({ kind: 'selection', uri: FILE, line: 12 }) + assert.equal(changes.length, 1, 'the caret within the lines: still shown') + const next = { ...shown, uri: OTHER, start: 0, end: 0, text: 'Another.' } + h.show(next) + assert.deepEqual(h.state, next, 'another reveal replaces it') + h.notice({ kind: 'edit', uri: FILE }) + assert.deepEqual(h.state, next, 'an edit in the old file: nothing shown there any more') + h.notice({ kind: 'edit', uri: OTHER }) + assert.equal(h.state, undefined) + assert.deepEqual(changes, [shown, next, undefined]) +}) + +test('TransientHint: dismiss (Esc, the command) ends it once; with nothing shown it says nothing', () => { + const { h, changes } = hint() + h.dismiss() + assert.deepEqual(changes, [], 'nothing shown: nothing to say') + h.show(shown) + h.dismiss() + h.dismiss() + assert.deepEqual(changes, [shown, undefined]) +}) + +test('TransientHint: its state is a copy (a caller cannot change what is shown)', () => { + const { h } = hint() + const given = { ...shown } + h.show(given) + given.text = 'changed' + h.state!.end = 99 + assert.deepEqual(h.state, shown) +}) + +test('hintLabel: the first line, as plain text, cut to fit beside the code', () => { + assert.equal(hintLabel('Adds the **tax**, then [rounds](https://x).\n\nMore below.'), 'Adds the tax, then rounds.') + assert.equal(hintLabel('\n\n `total` is cents '), 'total is cents') + const long = hintLabel('word '.repeat(60)) + assert.equal(long.length, LABEL_MAX) + assert.ok(long.endsWith('…')) +}) diff --git a/test/integration/main/bridge.ts b/test/integration/main/bridge.ts index f40f2a3..02a3230 100644 --- a/test/integration/main/bridge.ts +++ b/test/integration/main/bridge.ts @@ -1,6 +1,6 @@ // The bridge: a local program (a controller, here helpers/wsServer.ts) drives the window over a WebSocket. It writes // the discovery file; the extension dials it, says hello with the token and the window's folders, and answers reveal, -// journey.play, note.add and context.get; it dials again after a drop and hangs up when the file goes. +// journey.play, note.add and context.get (reveal's text a transient hint); it dials again after a drop and hangs up when the file goes. // Source: src/bridge/ (the requests), src/core/bridge/ (discovery, the connection), src/notes/agentNote.ts. import * as vscode from 'vscode' import * as fs from 'fs' @@ -9,7 +9,7 @@ import * as path from 'path' import assert from 'assert' import { readJson, test } from '../helpers' import { FakeController } from '../../helpers/wsServer' -import { closeAllEditors, ctx, journeyById, noteById, notePath, snap, until, wsPath } from './context' +import { caretAt, closeAllEditors, ctx, journeyById, lenses, noteById, notePath, snap, until, wsPath } from './context' import { savingTs, writeSavingJourney } from './fixtures' /* eslint-disable @typescript-eslint/no-explicit-any */ @@ -40,20 +40,46 @@ export const bridgeTests = [ await until('connected', () => bridge().connected && bridge().file === discovery) }), - test('reveal: the lines open and light, the text shows under them until dismissed', async () => { + test('reveal: the lines open and light, the text shows beside them as a hint until dismissed', async () => { await closeAllEditors() + const notesBefore = fs.readdirSync(ctx.notesDir).sort() const r = await ctl.request('reveal', { file: 'src/saving.ts', start: 3, end: 8, text: 'Writes the note, then logs its id.' }) assert.deepEqual([r.ok, r.result], [true, { start: 3, end: 8 }]) assert.equal(vscode.window.activeTextEditor?.document.uri.fsPath, savingUri().fsPath) assert.deepEqual(snap().claudeLinks.lit, { uri: savingUri().toString(), start: 2, end: 7 }) - assert.deepEqual(bridge().callout, { uri: savingUri().toString(), start: 2, end: 7, text: 'Writes the note, then logs its id.', author: 'Desk' }) + assert.deepEqual(bridge().hint, { uri: savingUri().toString(), start: 2, end: 7, text: 'Writes the note, then logs its id.', author: 'Desk' }) + assert.ok(!(await lenses(savingUri())).some((l) => /Writes the note/.test(l)), 'no CodeLens') + assert.deepEqual(fs.readdirSync(ctx.notesDir).sort(), notesBefore, 'nothing written to .code-notes/') await vscode.commands.executeCommand('codeNotes.dismissExplanation') - assert.equal(bridge().callout, undefined, 'dismissed') - // An absolute path, no text: lit, no callout; lines past the end end at the last line. + assert.equal(bridge().hint, undefined, 'dismissed (the command Esc runs)') + // An absolute path, no text: lit, no hint; lines past the end end at the last line. const abs = await ctl.request('reveal', { file: wsPath('src', 'saving.ts'), start: 10, end: 99 }) assert.equal(abs.ok, true) assert.deepEqual(abs.result, { start: 10, end: savingTs.length }) - assert.equal(bridge().callout, undefined) + assert.equal(bridge().hint, undefined) + }), + + test('reveal: the hint goes when the caret leaves the lines, on an edit in the file, and on the next reveal', async () => { + const show = (text: string) => ctl.request('reveal', { file: 'src/saving.ts', start: 3, end: 5, text }) + await show('one') + const ed = vscode.window.activeTextEditor! + caretAt(ed, 3) + await new Promise((r) => setTimeout(r, 200)) + assert.equal(bridge().hint?.text, 'one', 'the caret within the lines: still shown') + caretAt(ed, 8) + await until('gone: the caret left the lines', () => !bridge().hint) + + await show('two') + await ed.edit((b) => b.insert(new vscode.Position(0, 0), ' ')) + await until('gone: an edit in the file', () => !bridge().hint) + await vscode.commands.executeCommand('undo') + + await show('three') + await ctl.request('reveal', { file: 'src/saving.ts', start: 1, end: 1, text: 'four' }) + assert.equal(bridge().hint?.text, 'four', 'the next reveal replaces it') + await ctl.request('reveal', { file: 'src/saving.ts', start: 1, end: 1 }) + assert.equal(bridge().hint, undefined, 'a reveal without text removes it') + await vscode.commands.executeCommand('workbench.action.files.revert') }), test('reveal: a missing file, bad params and an unknown method are refused with the reason', async () => { diff --git a/test/keybindings.test.ts b/test/keybindings.test.ts index 8838623..53e710d 100644 --- a/test/keybindings.test.ts +++ b/test/keybindings.test.ts @@ -40,7 +40,7 @@ test('one chord scheme on two prefixes: Ctrl+< by scan code (ISO key) and Ctrl+\ } } } - assert.equal(keys.length, PREFIXES.length * Object.keys(CHORDS).length * 2 + 3, 'nothing else but Esc and Enter (below)') + assert.equal(keys.length, PREFIXES.length * Object.keys(CHORDS).length * 2 + 4, 'nothing else but Esc and Enter (below)') // VS Code shows the last binding of a command: the plain chord, "Ctrl+' D". for (const command of Object.values(CHORDS)) assert.equal(keys.filter((k) => k.command === command).pop()!.key.replace(/^\S+ /, ''), Object.keys(CHORDS).find((k) => CHORDS[k] === command)) assert.ok(keys.some((k) => k.key === 'escape' && k.command === 'codeNotes.cancelMove')) @@ -54,6 +54,8 @@ test('outside the chords: Esc and Enter only where they belong to Code Notes', ( { command: 'codeNotes.moveToSelection', key: 'enter', when: 'codeNotes.moving && editorTextFocus && !suggestWidgetVisible' }, // Esc in an empty new note box of ours closes it (the draft is kept); other comment boxes keep their Esc. { command: 'codeNotes.closeNoteBox', key: 'escape', when: 'commentEditorFocused && commentController == codeNotes && commentThreadIsEmpty' }, + // Esc puts away a controller's explanation (the bridge's hint), when the editor has no other use for it. + { command: 'codeNotes.dismissExplanation', key: 'escape', when: 'codeNotes.explanationShown && editorTextFocus && !suggestWidgetVisible && !findWidgetVisible && !inSnippetMode && !codeNotes.moving' }, ]) })