From fd0e52496d7937fe25940b77639db07fd5728cd4 Mon Sep 17 00:00:00 2001 From: Devvyn <22340871+opticon454@users.noreply.github.com> Date: Wed, 28 Oct 2026 23:03:45 +0800 Subject: [PATCH] fix(links): preserve workspace openers after lookup refusals --- .changeset/Repair-FilePathLinks.md | 2 +- CLAUDE.md | 2 +- docs/architecture-invariants.md | 3 +- src/web/public/constants.js | 2 + src/web/public/terminal-ui.js | 11 +++--- test/file-path-link-forms.test.ts | 52 +++++++++++++++++++++++-- test/wrapped-file-paths.browser.test.ts | 37 ++++++++++-------- 7 files changed, 80 insertions(+), 29 deletions(-) diff --git a/.changeset/Repair-FilePathLinks.md b/.changeset/Repair-FilePathLinks.md index 17c6d62b..c9cafa3b 100644 --- a/.changeset/Repair-FilePathLinks.md +++ b/.changeset/Repair-FilePathLinks.md @@ -2,4 +2,4 @@ 'aicodeman': patch --- -Keep parenthesised filenames with spaces clickable as one complete file path, including `.conf` configuration files. For an ambiguous hard wrap, check the original concatenated filename through the existing guarded attachment route when clicked, and try the spaced filename only after a not-found response. Existing filenames take priority, and permission or connection failures stop resolution. Preserve clickable row positions and share the spaced-path detector between the terminal and Response Viewer. +Keep parenthesised filenames with spaces clickable as one complete file path, including `.conf` configuration files. For an ambiguous hard wrap, check the original concatenated filename through the existing guarded attachment route when clicked, and try the spaced filename only after a not-found response. Every original response other than not-found retains the normal opener, including workspace files whose extensions the attachment registry rejects. A spaced alternative opens only after successful registration. Preserve clickable row positions and share the spaced-path detector between the terminal and Response Viewer. diff --git a/CLAUDE.md b/CLAUDE.md index 3926a6b0..d1234f37 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -226,7 +226,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Prompt uploads** (`POST /api/sessions/:id/paste-image`: clipboard paste, drop, the Compose Attach key and the phone toolbar's Attach button; client wiring in `image-input.js` and `keyboard-accessory.js`): a pick is written to `/.codeman-uploads/` and its path lands on the prompt as unsent text. The folder is IN the workspace because that is the only path identical for a local and a container agent, FLAT because `/.codeman/` would BE the data dir when the workspace is the home directory, and self-ignoring through a `.gitignore` of `*` written ONCE with `wx` (a file already there is the user's and is never overwritten; the user's own ignore file is never touched). ⚠️ The directory names live ONLY in `paste-image-gc.ts` (`UPLOAD_DIR_NAMES`): the pre-move `.claude-images/` receives nothing but stays readable for one release, so the GC sweep and the delete cleanup (through `uploadDirs()`) and the image watcher's ignore filter (reading the names) cover BOTH; retire the legacy entry there, never by hand elsewhere. ⚠️ `uploadDirs()` is async and probes the workspace BOUNDED first (`probePathKind()`, the #516 rule: an `unknown` path is skipped, never touched; the sweep keeps the stall cap and the delete passes `pastCap`), then returns only REAL directories (lstat, so a planted symlink is never one), none that is or contains `getDataDir()` (one strictly inside it only holds uploads and is listed), and none for a remote session, since both consumers delete; the check is made at list time, and the same-user race after it is accepted. Images are buffered in memory under `MAX_PASTE_IMAGE_BYTES` (50MB) after a client-side canvas re-encode; a DOCUMENT (pdf, docx, pptx, xlsx, zip and the text family txt/md/csv/tsv/json/log/yaml/yml/xml; the curated `ALLOWED_DOCUMENT_EXTS`, never `SUPPORTED_ATTACHMENT_EXTENSIONS` or `EDITABLE_EXTENSIONS`, which carry sh/py/js/html) is admitted by its name's extension alone, buffered like an image, judged on its bytes by the same fail-closed `imageMagicMatchesExt` (`%PDF-`, `PK\x03\x04` for the OOXML trio and zip, UTF-8 without a NUL byte for text: a SIGNATURE or ENCODING check, never a structure or content check, so generic zip bytes pass as `.docx` and a script renamed `.txt` is text; the sh/py/js/html exclusion is a SCOPE choice by extension, keeping the server from storing what it would serve or run, not a content filter: the agent can already write any of those) and saved as `paste---` with a sanitized stem (`[A-Za-z0-9._-]`, 40 chars, a wholly non-ASCII name leaves no stem; the `paste-` prefix is what the GC matches). A VIDEO is never buffered: `?kind=video` streams it to disk under `MAX_PASTE_VIDEO_BYTES` (1GB, env `CODEMAN_MAX_PASTE_VIDEO_BYTES`), judges the container on the first 12 bytes as they arrive (ISO BMFF / QuickTime atom, EBML for webm, Ogg for ogv; a mislabeled body is drained unwritten from there, never parked on disk first) and unlinks on any failure, a dead transfer included. ⚠️ The flag is the ONLY way onto that path and admits video types alone (the registry's `VIDEO_ATTACHMENT_EXTENSIONS`, single-sourced: mp4/webm/mov/m4v/ogv, so an uploaded video is one the file viewer can also play; 3gp/mkv are out, since a phone's camera roll produces neither and neither previews), so an image can never ride the larger cap through memory; without it the route is byte-identical to the image-only version. Busboy takes its size limit before the part is seen, which is why the choice rides the URL and not the file. ⚠️ A video draws on its OWN per-(IP, session) rate bucket (`consumeVideoToken`, 3/min) beside the image bucket (`consumePasteToken`, 30/min): at 1GB each, 30/min would be 30GB of disk a minute, so the lower rate bounds it to 3GB; the image path keeps the 30/min bucket and is unchanged without the flag. A remote (SSH) session is refused (400) before any disk touch: its `workingDir` is the remote path, so the file would land on THIS host where the agent cannot read it (Docker is fine, the workspace is bind-mounted at the same absolute path). ⚠️ A live session's workspace can still sit on a network mount that stopped answering, so the route probes it BOUNDED (`probePathKind(session.workingDir, { pastCap: true })`, the #516 rule) before the first disk touch and refuses an `unknown` mount through `describeUnknownPath()` (OPERATION_FAILED), the way session create does, so a mount already unreachable cannot freeze a libuv worker on every upload (a mount that dies after the probe is the same residual race create accepts). ⚠️ Dispatch mirrors the client: an `image/*` MIME takes the IMAGE path whatever the name says (a GIF named `animation.txt` stays a GIF), a document extension takes the document branch, and anything else takes the image path exactly as before, where the HEIC sniff still recovers a HEIC under a generic name; a foreign extension with no image MIME gets its `Unsupported file type` 400 only AFTER that sniff fails, never before, so nothing the image path ever accepted by its bytes is refused. A text mismatch is refused as not UTF-8 text (UTF-16 when the file opens with a UTF-16 BOM, as Excel's "Unicode Text" and Notepad's "Unicode" do), telling the user to save it as UTF-8, and its log line names the failure (`utf16-bom`/`nul-byte`/`not-utf8`) and never prints the bytes, since the head of a text file is user content. ⚠️ The client classifies a pick through ONE helper, `_promptAttachKind()` (MIME type first, then the name's extension, because some Android file managers hand over a File with none; returns `image`, `video` or `document`); every pick and paste filter (Attach, drop, the tile grid's drop in `tile-grid.js`, the Compose and paste-dialog pickers, the clipboard handlers), the flag and the re-encode gate read it, never `file.type` directly. Those surfaces ADMIT through `_admitPromptAttachments()` (image-input.js), which calls it and toasts what a pick skipped (how many files of a mixed pick, `Unsupported file type` when none pass, nothing for a text paste); a new surface admits through that helper too, never by filtering on `_promptAttachKind()` itself, or it loses the toasts. ⚠️ A pick that lands while the tile grid owns the terminal goes to the PTY, never the main terminal's overlay: that terminal is parked and hidden then, and a tile's Enter cannot flush it (`_tilesOwnTerminal()` in the `_attachFromToolbar` guard). Tests: `test/toolbar-attach.test.ts`, `test/mobile-prompt-composer.test.ts`, `test/paste-image-gc.test.ts`, `test/paste-image-dir-shared.test.ts`, `test/upload-document-list-parity.test.ts` (the browser's copies of `ALLOWED_DOCUMENT_EXTS`: `_promptAttachKind()`, the three pickers' `accept=` and the two file-path link patterns), the paste-image block of `test/routes/session-routes.test.ts`. → [architecture-invariants#buffers-uploads-and-terminal-history](docs/architecture-invariants.md#buffers-uploads-and-terminal-history) -**File-path links (terminal + chat)**: a path an agent prints is clickable on BOTH surfaces and opens the file-preview overlay. ⚠️ ONE pattern (`FILE_PATH_LINK_PATTERN` / `absoluteFilePathPattern()` in constants.js) feeds the xterm link provider AND `_linkifyFilePaths()`, a fresh instance per call (`lastIndex`). Both call `findFilePathLinks()`, which reserves spaced-path spans first (an unlinkable one only while its last word holds a `/`; any label, before an absolute or relative path, must be an explicit path label, prose after that label stays out, and an earlier connective or verb such as `and` or `has` (`SPACED_PATH_PROSE_WORD`) makes any candidate prose; rules and trade-offs in the architecture-invariants paragraph linked below), then adds rooted, `~/`, relative and folder paths without overlapping a reservation, earlier match or URL; a relative path resolves against `workingDir` (`resolveLinkedFilePath`), `~/` only server-side on the session's host (attachment route), and `terminalPathLine()` joins a path a program hard-wrapped short of the edge. ⚠️ A folder link opens the **folder grid**: `POST /api/sessions/:id/folders` guards + GRANTS the folder (`folder-listing.ts`, own registry, never the 200-capped attachment registry), files come by bare name via `…/folders/:folderId/files/:name/*` through `resolveServableAttachmentPath` plus the same extension/regular-file gate on the symlink's resolved target, so no browser request carries a path; `~/` is refused in a Docker case (the container's home is not this host's). The chat linkifier walks TEXT NODES with DOM APIs, never rebuilds sanitized markup as a string. ⚠️ An out-of-workspace path goes through the ATTACHMENT routes (`POST /api/sessions/:id/attachments` with `notify: false`), never by widening `file-content`/`file-raw` or `file-stream-manager`'s `tail -f` allowlist. ⚠️ `TEXT_ATTACHMENT_EXTENSIONS` IS `EDITABLE_EXTENSIONS` (never a second list), and widening READ must never widen RUN: `html`/`htm`/`svg` stay download-only, other text is inert `text/plain`+`nosniff`. ⚠️ The ONE place HTML renders is `/html-view//...` (`html-view-routes.ts`, `html-view-capabilities.ts`): `POST /api/sessions/:id/html-view` mints a capability for the file's own directory, every response carries `Content-Security-Policy: sandbox` WITHOUT `allow-same-origin` (opaque origin even as a top-level tab, so the page can never read Codeman or drive its API) and with NO fetch directive (open network, owner decision 2026-10-13: never restrict it or add `allow-same-origin` without the owner), and only non-dot, asset-allowlisted files under that directory are served (GET/HEAD only; capabilities revoked with the web-tab ones on logout). That tree is served recursively, so minting is refused for a hidden directory or a broad root (`isBroadHtmlViewRoot`); the preview renders by default and the **Page** pill (or a refused mint) falls through to the source view and its Edit button. Never serve HTML same-origin anywhere else. Tests: `test/routes/html-view-routes.test.ts`. Media extensions are single-sourced in `attachment-registry.ts`. ⚠️ **XLSX previews parse in the BROWSER**, never on the server; the admission limits that keep a hostile workbook from freezing the worker live in `src/web/CLAUDE.md` (Spreadsheet preview). → [architecture-invariants#file-path-links-terminal--response-viewer](docs/architecture-invariants.md#file-path-links-terminal--response-viewer) +**File-path links (terminal + chat)**: a path an agent prints is clickable on BOTH surfaces and opens the file-preview overlay. ⚠️ ONE pattern (`FILE_PATH_LINK_PATTERN` / `absoluteFilePathPattern()` in constants.js) feeds the xterm link provider AND `_linkifyFilePaths()`, a fresh instance per call (`lastIndex`). Both call `findFilePathLinks()`, which reserves spaced-path spans first (an unlinkable one only while its last word holds a `/`; any label, before an absolute or relative path, must be an explicit path label, prose after that label stays out, and an earlier connective or verb such as `and` or `has` (`SPACED_PATH_PROSE_WORD`) makes any candidate prose; rules and trade-offs in the architecture-invariants paragraph linked below), then adds rooted, `~/`, relative and folder paths without overlapping a reservation, earlier match or URL; a relative path resolves against `workingDir` (`resolveLinkedFilePath`), `~/` only server-side on the session's host (attachment route), and `terminalPathLine()` joins a path a program hard-wrapped short of the edge. ⚠️ A folder link opens the **folder grid**: `POST /api/sessions/:id/folders` guards + GRANTS the folder (`folder-listing.ts`, own registry, never the 200-capped attachment registry), files come by bare name via `…/folders/:folderId/files/:name/*` through `resolveServableAttachmentPath` plus the same extension/regular-file gate on the symlink's resolved target, so no browser request carries a path; `~/` is refused in a Docker case (the container's home is not this host's). The chat linkifier walks TEXT NODES with DOM APIs, never rebuilds sanitized markup as a string. ⚠️ An out-of-workspace path goes through the ATTACHMENT routes (`POST /api/sessions/:id/attachments` with `notify: false`), never by widening `file-content`/`file-raw` or `file-stream-manager`'s `tail -f` allowlist. An ambiguous parenthesised hard wrap is checked only on activation, original first: only a 404 permits a spaced-path lookup, and only a registered alternative is opened; every other original result uses the normal opener, never an attachment-policy gate on workspace files, and hover performs no lookup. ⚠️ `TEXT_ATTACHMENT_EXTENSIONS` IS `EDITABLE_EXTENSIONS` (never a second list), and widening READ must never widen RUN: `html`/`htm`/`svg` stay download-only, other text is inert `text/plain`+`nosniff`. ⚠️ The ONE place HTML renders is `/html-view//...` (`html-view-routes.ts`, `html-view-capabilities.ts`): `POST /api/sessions/:id/html-view` mints a capability for the file's own directory, every response carries `Content-Security-Policy: sandbox` WITHOUT `allow-same-origin` (opaque origin even as a top-level tab, so the page can never read Codeman or drive its API) and with NO fetch directive (open network, owner decision 2026-10-13: never restrict it or add `allow-same-origin` without the owner), and only non-dot, asset-allowlisted files under that directory are served (GET/HEAD only; capabilities revoked with the web-tab ones on logout). That tree is served recursively, so minting is refused for a hidden directory or a broad root (`isBroadHtmlViewRoot`); the preview renders by default and the **Page** pill (or a refused mint) falls through to the source view and its Edit button. Never serve HTML same-origin anywhere else. Tests: `test/routes/html-view-routes.test.ts`. Media extensions are single-sourced in `attachment-registry.ts`. ⚠️ **XLSX previews parse in the BROWSER**, never on the server; the admission limits that keep a hostile workbook from freezing the worker live in `src/web/CLAUDE.md` (Spreadsheet preview). → [architecture-invariants#file-path-links-terminal--response-viewer](docs/architecture-invariants.md#file-path-links-terminal--response-viewer) The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLine()` for URL continuations in indented paragraphs and table cells. List markers, bare numbers, version tokens, whole email addresses, labels ending in `:`, measurements and clock times (`45%`, `12.3ms`, `10:00:00`) and a `name=value` field under a URL ending in `/` never continue a URL; a token with only `-`, `_` or `.` is also refused when it carries a call paren (`client.get()`) or ends a sentence (`Done.`). A URL in the last column of a space-aligned table never takes the next row's first cell: a continuation row must start inside the URL's own cell, so a gap of two or more spaces between its indent and where the URL starts on the row above means it is the next record. `terminalCellWrappedPaths()` follows each table cell independently: a fragment carries on into the next row only when it ends its cell on `/` or `-` (where a wrapper breaks a path; codex's cell wrap never breaks at `_`), the continuation row is blank to the left of the cell (a wrapper wraps every column of a table row together, so a label there such as `Entry` or `│ Log │` is the next record, unless a left column's path continued on that row too; a left column of wrapped prose, as in a `Description | Path` table, fills that row as well, so the path beside it keeps its per-row fragment links, the safe direction), the next row's token passes `pathContinuation()`, and the cell is no wider than the one above. So a directory that is a whole cell value (`/home/u/proj` over `config.yaml`, or `/home/u/proj/app/` over a labelled `main.py`) keeps its folder link and the next row keeps its own file link. With no label to tell them apart, a directory written with its trailing slash over a relative path in the same column (`/home/u/proj/src/` over `lib/util.ts`) still joins, a known trade-off: it reads exactly like a wrap at `/`. Accepted paths displace other links on their cells. Full-width divider rows stop `terminalLogicalLine()` stitching for both links and touch selection. OSC 8 links confirm the real target URI before the shared opener runs. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index d26a8814..31e792f1 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -415,8 +415,7 @@ Spaced paths are considered first by `findFilePathLinks()`: accepted candidates Parentheses also bound an inline spaced path, such as `Updated (/mnt/c/My Docs/report.conf)`. The whole candidate is reserved before fragment detectors run; existing root, prose and traversal guards still apply. A comma at the end of an earlier word marks a list, not one filename. -Hard-wrapped filenames keep the existing concatenation without inserted spaces. A parenthesised final filename broken between words also carries a spaced alternative without changing its cell mapping. On activation only, the terminal checks the original path through the existing guarded attachment registration route (`notify: false`), tries the alternative only after HTTP 404, and retains the clicked session throughout. If both exist, the original wins. Permission, connection and server errors stop resolution; hover performs no lookup. Text alone cannot distinguish the two filenames, so this uses the filesystem result rather than a spacing guess. - +Hard-wrapped filenames keep the existing concatenation without inserted spaces. A parenthesised final filename broken between words also carries a spaced alternative without changing its cell mapping. On activation only, the terminal checks the original path through the existing guarded attachment registration route (`notify: false`), tries the alternative only after HTTP 404, and retains the clicked session throughout. If both exist, the original wins. Every original result other than HTTP 404 goes to the normal opener, preserving workspace previews and log viewing even for extensions the attachment registry rejects; for an external path that opener retains the same attachment guards and errors. After an original 404, a spaced alternative opens only if it registers successfully. Hover performs no lookup. Text alone cannot distinguish the two filenames, so this uses the filesystem result rather than a spacing guess. The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLine()` for URL continuations in indented paragraphs and table cells. List markers, bare numbers and version tokens never continue a URL. A token with only hyphens, underscores or dots must end its cell (row end or a gap of at least two spaces), so prose such as `self-hosted runners` is not appended. A row end counts as a cell end, so `⏺ Docs live at https://example.com/guide/` followed by ` self-hosted` still links `.../guide/self-hosted`, and an indented `and/or the API reference covers it.` still links `.../guide/and/or`; both are pinned as known trade-offs. Such a token is still refused when it is code with a call paren (`client.get()`, `expect(x).toBe(y)`; a wiki title like `Mercury_(planet)` keeps its paren) or a word ending a sentence (`ready.`, `Done.`, `self-hosted.`; a file name keeps its period, so `install.html.` still joins). Whatever its punctuation, a token never continues a URL when it ends with a colon (a label such as `Failure/Error:` or `prometheus.io/scrape:`), when it is a measurement or clock time (`45%`, `45%|####`, `12.3MB/45.0MB`, `12.3ms`, `10:00:00`; percent-encoding such as `2026%20Plan` still joins), or when it is a `name=value` field (`API_KEY=...`, `level=info`) under a URL ending in `/`, since a query needs a `?` first (after `?`, `&` or `_` it is a query parameter and joins). A continuation must be indented (a column-0 row is new output, which keeps `status=200`, `24/7` and `really?` out), and a shell prompt (`user@host:`), a home path (`~/`), a whole email address or an HTTP status line never continues a URL. A URL in the last column of a space-aligned table never takes the next row's first cell: a continuation row must start inside the URL's own cell, so a gap of two or more spaces between its indent and where the URL starts on the row above means it is the next record. When other columns follow a wrapped URL on its first row (a codex table's path or date column), the URL is stitched without them, and they still link on that row: `terminalLinkLine()` scans them after the stitched rows as a segment of their own, mapped back to their cells. A URL in such a column is the row's last URL, and only the last URL on a row is continued, so that row is never stitched. A divider row never continues the row above it, so a URL that reaches the right edge does not absorb a full-width `────` row below. A real plain slug followed by prose falls back to the original fragment link; `%`, `&`, `=`, `/` or `?` still qualify as stronger URL punctuation. `terminalCellWrappedPaths()` follows each table cell independently: a fragment carries on into the next row only when it ends its cell on `/` or `-` (where a wrapper breaks a path; codex's cell wrap never breaks at `_`), the continuation row is blank to the left of the cell (a wrapper wraps every column of a table row together, so a label there such as `Entry` or `│ Log │` is the next record, unless a left column's path continued on that row too; a left column of wrapped prose, as in a `Description | Path` table, fills that row as well, so the path beside it keeps its per-row fragment links, the safe direction), the next row's token passes `pathContinuation()`, and the cell is no wider than the one above. So a directory that is a whole cell value (`/home/u/proj` over `config.yaml`, or `/home/u/proj/app/` over a labelled `main.py`) keeps its folder link and the next row keeps its own file link. With no label to tell them apart, a directory written with its trailing slash over a relative path in the same column (`/home/u/proj/src/` over `lib/util.ts`) still joins, a known trade-off: it reads exactly like a wrap at `/`. Accepted paths displace other links on their cells. Full-width divider rows stop `terminalLogicalLine()` stitching for both links and touch selection. OSC 8 links confirm the real target URI before the shared opener runs. diff --git a/src/web/public/constants.js b/src/web/public/constants.js index 9ef42ceb..36a1c7d1 100644 --- a/src/web/public/constants.js +++ b/src/web/public/constants.js @@ -2656,6 +2656,8 @@ function terminalPathLine(buffer, row, cols, maxRows) { if (!prev || rows + rowsOf(prev) > bound) break; first = prev; rows += rowsOf(prev); + const tail = /[^\s"'<>|;&]+$/.exec(first.text.trimEnd())?.[0] || ''; + if (!tail.includes('/')) continue; const candidate = extend(first); if (candidate.parts[candidate.parts.length - 1].endRow >= base.startRow) extended = candidate; } diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 0f6d5042..d52e6bba 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -2342,12 +2342,11 @@ Object.assign(CodemanApp.prototype, { const alternative = !folder && logical.pathAlternatives?.find((candidate) => candidate.path === text); if (alternative && !verifiedSessionId) { return (async () => { - let path = target; - let registered = await self._registerExternalPreview(path, sessionId); - if (registered.status === 404) { - path = self._resolveLinkedFilePath(alternative.spacedPath, sessionId); - registered = await self._registerExternalPreview(path, sessionId); - } + const original = await self._registerExternalPreview(target, sessionId); + // Attachment policy must not gate the workspace's normal opener. + if (original.status !== 404) return activateFilePath(target, false, sessionId); + const path = self._resolveLinkedFilePath(alternative.spacedPath, sessionId); + const registered = await self._registerExternalPreview(path, sessionId); if (!registered.attachmentId) { self.showToast(registered.error || 'Cannot open this file', 'error'); return; diff --git a/test/file-path-link-forms.test.ts b/test/file-path-link-forms.test.ts index ffd430b6..b80615d5 100644 --- a/test/file-path-link-forms.test.ts +++ b/test/file-path-link-forms.test.ts @@ -259,6 +259,27 @@ function linksOn(lines: string[], row: number, cols = 80, wrappedRows = new Set< } describe('terminal link provider', () => { + it.each(['svg', 'markdown', 'avif', 'bmp', 'ico', 'zip'])( + 'keeps the workspace opener for a hard-wrapped .%s rejected by the attachment registry', + async (extension) => { + for (const row of [1, 2]) { + const path = `/home/me/proj/out/system_architecture.${extension}`; + const { app, links } = linksOn( + ['Saved the diagram (/home/me/proj/out/system_archi', ` tecture.${extension}).`], + row, + 120 + ); + app.sessions = new Map([['s1', { workingDir: '/home/me/proj' }]]); + app._registerExternalPreview.mockResolvedValue({ status: 400, error: 'Unsupported attachment type' }); + await links[0].activate({}, links[0].text); + const opener = extension === 'zip' ? app.openLogViewerWindow : app.openFilePreview; + expect(opener).toHaveBeenCalledWith(path, 's1'); + expect(app._registerExternalPreview.mock.calls).toEqual([[path, 's1']]); + expect(app.showToast).not.toHaveBeenCalled(); + } + } + ); + it.each([ [ ['Saved the screenshot (/home/me/proj/out/ghost1b_game', ' play.png).'], @@ -310,11 +331,36 @@ describe('terminal link provider', () => { app._registerExternalPreview.mockResolvedValue({ status, error: 'Lookup refused' }); await links[0].activate({}, links[0].text); expect(app._registerExternalPreview).toHaveBeenCalledTimes(1); - expect(app.openFilePreview).not.toHaveBeenCalled(); - expect(app.openLogViewerWindow).not.toHaveBeenCalled(); - expect(app.showToast).toHaveBeenCalledWith('Lookup refused', 'error'); + expect(app.openLogViewerWindow).toHaveBeenCalledWith('/mnt/data/KoboeReader.conf', 's1'); + expect(app.showToast).not.toHaveBeenCalled(); }); + it('keeps the original opener when the lookup cannot reach the server', async () => { + const { app, links } = linksOn(['Saved (/mnt/data/Kobo', ' eReader.conf).'], 1, 120); + app._registerExternalPreview.mockResolvedValue({ error: 'Connection lost' }); + await links[0].activate({}, links[0].text); + expect(app._registerExternalPreview).toHaveBeenCalledTimes(1); + expect(app.openLogViewerWindow).toHaveBeenCalledWith('/mnt/data/KoboeReader.conf', 's1'); + }); + + it.each([400, 403, 404, 500, 503])( + 'does not open an unregistered spaced alternative after HTTP %s', + async (status) => { + const { app, links } = linksOn(['Saved (/mnt/data/Kobo', ' eReader.conf).'], 1, 120); + app._registerExternalPreview + .mockResolvedValueOnce({ status: 404, error: 'File not found' }) + .mockResolvedValueOnce({ status, error: 'Alternative unavailable' }); + await links[0].activate({}, links[0].text); + expect(app._registerExternalPreview.mock.calls).toEqual([ + ['/mnt/data/KoboeReader.conf', 's1'], + ['/mnt/data/Kobo eReader.conf', 's1'], + ]); + expect(app.openFilePreview).not.toHaveBeenCalled(); + expect(app.openLogViewerWindow).not.toHaveBeenCalled(); + expect(app.showToast).toHaveBeenCalledWith('Alternative unavailable', 'error'); + } + ); + it('keeps the session selected at click time while a path lookup is pending', async () => { const { app, links } = linksOn(['Saved (/mnt/data/Kobo', ' eReader.conf).'], 1, 120); const pending = links[0].activate({}, links[0].text); diff --git a/test/wrapped-file-paths.browser.test.ts b/test/wrapped-file-paths.browser.test.ts index 983e695c..3890bae7 100644 --- a/test/wrapped-file-paths.browser.test.ts +++ b/test/wrapped-file-paths.browser.test.ts @@ -5,7 +5,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { chromium, type Browser } from 'playwright'; const publicDir = resolve(import.meta.dirname, '../src/web/public'); -const path = '/mnt/user/Scratch/Kobo/Set-KoboCovers/Kobo eReader.conf'; +const basePath = '/mnt/user/Scratch/Kobo/Set-KoboCovers/Kobo eReader.conf'; describe('wrapped configuration file links (Chromium)', () => { let browser: Browser; @@ -17,12 +17,15 @@ describe('wrapped configuration file links (Chromium)', () => { }); it.each([ - { wrap: 'soft', originalExists: false }, - { wrap: 'hard', originalExists: false }, - { wrap: 'hard', originalExists: true }, + { wrap: 'soft', originalExists: false, extension: 'conf', registrationStatus: 200 }, + { wrap: 'hard', originalExists: false, extension: 'conf', registrationStatus: 200 }, + { wrap: 'hard', originalExists: true, extension: 'conf', registrationStatus: 200 }, + { wrap: 'hard', originalExists: true, extension: 'svg', registrationStatus: 400 }, + { wrap: 'hard', originalExists: true, extension: 'markdown', registrationStatus: 400 }, ])( - 'opens the existing file from both rows: $wrap, original exists: $originalExists', - async ({ wrap, originalExists }) => { + 'opens the existing .$extension file from both rows: $wrap, original exists: $originalExists', + async ({ wrap, originalExists, extension, registrationStatus }) => { + const path = basePath.replace('.conf', `.${extension}`); const original = path.replace('Kobo eReader', 'KoboeReader'); const expected = wrap === 'hard' && originalExists ? original : path; const lookups: string[] = []; @@ -39,11 +42,13 @@ describe('wrapped configuration file links (Chromium)', () => { expect(body.notify).toBe(false); lookups.push(body.path); const exists = body.path === path || (originalExists && body.path === original); + const status = exists ? registrationStatus : 404; await route.fulfill({ - status: exists ? 200 : 404, - json: exists - ? { success: true, data: { attachmentId: 'att-fixture' } } - : { success: false, error: 'File not found' }, + status, + json: + status === 200 + ? { success: true, data: { attachmentId: 'att-fixture' } } + : { success: false, error: status === 400 ? 'Unsupported attachment type' : 'File not found' }, }); }); await page.goto('http://fixture.test/'); @@ -54,28 +59,28 @@ describe('wrapped configuration file links (Chromium)', () => { await page.addScriptTag({ content: readFileSync(resolve(publicDir, file), 'utf8') }); } await page.evaluate( - async ({ path, wrap }) => { + async ({ path, wrap, workingDir }) => { const w = window as any; - const first = `Found it: prepared a corrected configuration (${path.slice(0, -' eReader.conf'.length)}`; + const boundary = path.lastIndexOf(' '); + const first = `Found it: prepared a corrected configuration (${path.slice(0, boundary)}`; const terminal = new w.Terminal({ cols: first.length + (wrap === 'soft' ? 1 : 20), rows: 6 }); terminal.open(document.getElementById('terminal')); w.opened = []; w.app = Object.assign(new w.CodemanApp(), { terminal, activeSessionId: 'fixture', - sessions: new Map([['fixture', { workingDir: '/workspace' }]]), - _isExternalPreviewPath: () => true, + sessions: new Map([['fixture', { workingDir }]]), openFilePreview: (file: string) => w.opened.push(file), openLogViewerWindow: (file: string) => w.opened.push(`log:${file}`), openFolderGrid: (file: string) => w.opened.push(`folder:${file}`), showToast: (message: string) => w.opened.push(`error:${message}`), }); w.app.registerFilePathLinkProvider(); - const text = `${first}${wrap === 'soft' ? ' ' : '\r\n '}eReader.conf).`; + const text = `${first}${wrap === 'soft' ? ' ' : '\r\n '}${path.slice(boundary + 1)}).`; await new Promise((done) => terminal.write(text, done)); await new Promise((done) => requestAnimationFrame(() => requestAnimationFrame(() => done()))); }, - { path, wrap } + { path, wrap, workingDir: registrationStatus === 400 ? '/mnt/user/Scratch/Kobo' : '/workspace' } ); expect(lookups).toEqual([]);