Skip to content

Commit 463b89c

Browse files
sahrizviclaude
andauthored
feat: make linked workspace names clickable in the sidebar, CLI, and post-scan dialog (#1274)
* feat: make linked workspace names clickable in the sidebar, CLI link picker, and post-scan dialog - `workspace-sidebar.tsx`: the workspace name + manage URL in the TUI sidebar tile now render underlined/accent-styled and open the browser on click (mouse events land on the enclosing `<text>`, not the inline `<span>`, matching the pattern already used for the footer's docs/ community links since raw `<a href>` crashes in this JSX layer). - `workspace.tsx`: extracted the guarded `open()` + toast-on-failure logic from `WorkspaceLinkedDialog` into a shared `openManageUrl()` helper, and added an "Open in browser" option to `AlreadyLinkedDialog` (shown on re-entering an already-linked project) using the same helper. - `cli/cmd/link.ts`: `altimate-code link`'s "Currently linked to X" prompt and the matching picker row now wrap the workspace name in a real OSC 8 terminal hyperlink (+ underline for visual affordance), so clicking it in a supporting terminal opens the workspace directly — no click-handler needed since the terminal itself renders the link. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address bot review findings on #1274 — control-char injection, URL join, dead export - `cli/cmd/link.ts`: sanitize workspace names (strip C0/C1 control bytes, including ESC) before they reach the OSC 8 hyperlink wrapper — an attacker/account-controlled workspace name containing its own `\x1b]8;;` could otherwise prematurely close our hyperlink and open a spoofed one with our trusted URL as inert visible prefix text. (CodeRabbit + cubic) - `cli/cmd/link.ts`: only emit the underline visual affordance when the terminal is one we're reasonably confident renders OSC 8 (conservative TERM_PROGRAM/VTE/Konsole/Windows Terminal allowlist) — SGR underline is far more universally rendered than OSC 8 itself, so emitting it unconditionally made names look clickable in terminals where they weren't. (cubic) - `cli/cmd/link.ts` + `workspace.tsx` + `workspace-sidebar.tsx`: build the manage URL via real `URL` pathname/search/hash manipulation instead of string-concatenating `toString()` — the dev-only `ALTIMATE_WORKSPACE_WEB_URL` override can carry its own path/query, and naive concatenation landed `/w/<id>` inside the query string instead of the path. Fixed in all three occurrences of the same pattern, not just the one CodeRabbit/cubic flagged in link.ts. (CodeRabbit + cubic) - `workspace.tsx`: drop the `export` on `isSafeHttpUrl` — no external importers; `link.ts` deliberately keeps its own private copy. (Kilo) Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-2 bot review findings on #1274 — Apple_Terminal false positive, C1 control bytes - `terminalSupportsHyperlinks`: drop `Apple_Terminal` from the allowlist. macOS Terminal.app only gained OSC 8 support in Sequoia (Sept 2024); older versions only auto-linkify plain URLs. `TERM_PROGRAM` alone can't tell a Sequoia+ install apart from an older one, and this function's own documented bias is toward false negatives — so it's excluded rather than assumed current. Verified via search before reverting; my earlier inclusion was an unverified assumption. (Kilo) - `stripControlChars`: extend the stripped range to also cover C1 control bytes (`\x80`-`\x9f`), not just C0 + DEL. ESC (the actual OSC 8 breakout vector) was always covered, but the doc comment overstated what the regex did. (Kilo) Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address multi-model review findings on #1274 — dialog selection race, missing CLI URL fallback, unit tests - `workspace.tsx`: fix a real selection-desync race in `AlreadyLinkedDialog`. `manageUrl` was fetched async inside the dialog via `onMount`, so the options array could grow from 3 to 4 items ("Open in browser" inserted at index 2, pushing "Skip for now" to 3) after the dialog had already painted. dialog-select.tsx's `store.selected` is a raw numeric index, and the only effect that resyncs it fires on `props.current`/`store.filter` changes — not on the options array changing shape. A user who pressed Down twice to reach "Skip for now" before the promise resolved could press Enter and launch a browser instead. Fixed by resolving `manageUrl` in the caller (`runFlow`) before `dialog.replace()`, matching the synchronous-prop pattern `WorkspaceLinkedDialog`/`showLinkedConfirmation` already use — `AlreadyLinkedDialog` no longer has any async state. - `cli/cmd/link.ts`: print the plain manage URL as a `prompts.log.info` fallback when `terminalSupportsHyperlinks()` is false — previously a non-allowlisted terminal had no way to discover the URL at all (the OSC 8 bytes are invisible there), unlike the TUI side which falls back to a copyable toast on open() failure. - `cli/cmd/link.ts`: guard `hyperlink()` against an empty `text` (would otherwise emit an invisible zero-width clickable region). - `workspace-sidebar.tsx`: scope the sidebar tile's click target to just the name line — "(pinned via --workspace)" now renders on its own non-interactive line instead of being appended inside the clickable `<text>` block, and `onMouseUp` is omitted entirely (not attached as a no-op) until a manage URL actually resolves. - Add `test/cli/cmd/link.test.ts` — unit coverage for the four pure helpers introduced in this PR (`stripControlChars`, `terminalSupportsHyperlinks`, `buildManageUrl`, `hyperlink`), including the control-character-injection and URL-join regressions directly. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-3 cubic findings on #1274 — non-TTY OSC 8 leak, second URL-join duplicate - `hyperlink()`: skip OSC 8 wrapping entirely (return bare sanitized text) when stdout isn't a TTY. Stdin can be a TTY (satisfying the handler's interactive-input check) while stdout is redirected to a file or piped — in that case no terminal is reading the bytes, so the previous "harmless when unrecognized" reasoning didn't hold: raw OSC 8 would land as literal junk in the captured output. `terminalSupportsHyperlinks()` already checked `isTTY` for the underline decision; this applies the same check before emitting any escape bytes at all. - `manageUrlFor`: delegate to `buildManageUrl` instead of its own copy of the pre-fix string-concatenation bug. Two near-identical URL builders in the same file had drifted — the first round's fix only touched `currentManageUrl`'s construction and missed this second one, used by the browser-handoff and create-flow "Manage it at:" lines. - Declined (with reasoning in `buildManageUrl`'s comment): moving the URL-join helper to a module shared with the TUI side. Contradicts this codebase's existing, documented CLI/TUI self-containment convention (same rationale as `isSafeHttpUrl`'s deliberate duplication) — the fix is consolidating within this file, not spanning the boundary. - Updated `link.test.ts` for `hyperlink()`'s new non-TTY early return, and added a test isolating "TTY but unrecognized terminal" (OSC 8, no underline) from "not a TTY at all" (no escape bytes whatsoever) — the previous tests conflated the two via a shared `isTTY: false` setup. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-4 review findings on #1274 — sanitize every raw name interpolation, not just hyperlink()'s - `hyperlink()`: sanitize `text` before the null-URL early return, not after — the null-URL branch previously returned the raw name unchanged (BYOK/unresolvable deployments), meaning callers relying on hyperlink() as their sanitization boundary got the raw name in exactly that case. - Validating this finding against the code showed the actual gap was much broader than the one call site flagged: every OTHER raw workspace-name interpolation in this file (~10 sites across the picker's non-current rows, the "Currently linked"/"Kept" messages, and every bind/create/ rebind success and ConflictError message) was never sanitized at all, since it never went through hyperlink() in the first place. Sanitized each — `currentName` and each picker row's `dm.name` once at their declaration/mapping, `created.datamate.name` once per function via a local, and each `res.binding.datamate_name` / `existing_datamate_name` call site individually (control flow there has multiple branches reassigning `res`, so hoisting one local was riskier than wrapping each use). - Test fixes: `link.test.ts`'s `hyperlink` describe block only cleared `TERM_PROGRAM` between tests, not the other terminalSupportsHyperlinks() signals (`WT_SESSION`/`KONSOLE_VERSION`/`VTE_VERSION`) its sibling block already isolated — an ambient one of those on the host/CI runner could make an "unsupported terminal" test spuriously pass. Also, the TTY restore helper used `Object.defineProperty(..., { value, configurable: true })`, which defaults every omitted attribute (enumerable, writable) to false — silently collapsing those flags from whatever the real descriptor had, rather than truly restoring it. Both fixed via two small shared helpers instead of duplicating cleanup per describe block. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-5 cubic finding on #1274 — restoreTTY() was a silent no-op The round-4 fix for the TTY-descriptor-restoration finding introduced a new bug of its own: `process.stdout.isTTY` has no OWN property descriptor in the common case (stdout piped/redirected, which is how it always runs under a test runner) — Node only sets it as an own property when the stream genuinely is a TTY. So `ORIGINAL_TTY_DESCRIPTOR` was `undefined` in virtually every real test run, and `restoreTTY()`'s `if (descriptor)` guard made it a complete no-op: the property `setTTY()` added stayed shadowed on `process.stdout` for the rest of the process instead of being restored, contradicting the comment's stated intent. Verified empirically (bun -e) before fixing: process.stdout.isTTY genuinely has no own descriptor and isn't found anywhere on its prototype chain when not a real TTY. Fixed by deleting the property when there was no original descriptor to restore. Added a regression test, and confirmed by temporarily reverting the fix that the test actually fails without it (not vacuously green). Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-6 cubic finding, decline incorrect Kilo finding on #1274 - cubic (valid): the round-5 regression test didn't wrap its first assertion in try/finally, so a failure there would skip restoreTTY() and leak the mutated process.stdout.isTTY into every later test. Fixed. - Kilo (declined — verified factually wrong): claimed `isTTY` is "an inherited prototype property... regardless of whether stdout is a TTY" and that the `if (ORIGINAL_TTY_DESCRIPTOR)` branch in restoreTTY() is dead code, suggesting it be simplified to an unconditional `delete`. Checked empirically in a real pty (`tmux new-session ... bun -e`, because the sandboxed shell always pipes stdout) rather than trusting either the bot's claim or my own prior comment: when process.stdout genuinely IS a TTY, `isTTY` IS a real own property (`{value: true, writable: true, enumerable: true, configurable: true}`), not inherited, not undefined. Applying Kilo's suggested "fix" would have made restoreTTY() permanently delete the real isTTY property instead of restoring it whenever these tests run in an actual interactive terminal — a regression, not a fix. Left the conditional as-is; expanded the comment to document the verification so this doesn't get relitigated incorrectly again. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-7 multi-model review on #1274 — third sanitization gap, wider hyperlink() contract, deduplicate URL-join across CLI/TUI - `bindOrRebind`'s `ConflictError` handler had a third, unsanitized `existing_datamate_name` interpolation — round 4's sanitization sweep fixed the other two occurrences of this exact pattern (in `runBrowserHandoff` and `createThenBindOrRebind`) but missed this one in a third function, making round 4's "every raw name-interpolation" claim inaccurate. Fixed, and swept the whole file again to confirm no others remain (all display sites go through `stripControlChars`; the three `recordApprovedBinding` cache-storage calls deliberately still store the raw value, which is correct — sanitization belongs at display time, not storage time). - `hyperlink()` now also validates `url` via the existing `isSafeHttpUrl`, not just sanitizing `text`. It's an exported function now (tests import it), so its contract is wider than its two in-file callers — both of which only ever pass a `buildManageUrl(...)`-derived trusted URL, but an external caller passing something unvalidated wouldn't get the same protection the `text` side already has. - Moved `buildManageUrl` (the URL-join helper, previously duplicated as three near-identical private copies across `link.ts`, `workspace.tsx`, and `workspace-sidebar.tsx`) to `browser-handoff.ts`, beside `resolveWorkspaceWebUrl` — a module all three files already import for that function, so this doesn't cross the deliberate CLI/TUI self-containment boundary the way `isSafeHttpUrl`'s split exists to avoid. Round 3's URL-join bug needed three separate edits because of this exact duplication; consolidating deletes the bug class instead of leaving three instances of it to individually stay in sync. Moved its tests to `browser-handoff.test.ts` alongside the function. - Fixed a stale/circular doc comment on `openManageUrl` that described itself via a "same behavior as WorkspaceLinkedDialog's open action" cross-reference — that action now just calls `openManageUrl` directly (round-1 refactor), making the comment confusing rather than useful. - Declined (per the review's own "possibly deliberate — ignore if so"): the differing "open in browser" wording across `WorkspaceLinkedDialog` and `AlreadyLinkedDialog` — one is a post-creation success card, the other a you're-already-linked prompt; the differing phrasing fits the differing context. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG * fix: address round-8 bot findings on #1274 — url control-byte bypass, third conflict-name duplicate, naming collision - `hyperlink()`: `isSafeHttpUrl(url)` only checks that `url` parses as http(s) via `new URL()` — it doesn't sanitize, and doesn't return the re-serialized/encoded form. Verified empirically that a string can contain a live ESC byte and still parse successfully as a valid https: URL, so a hypothetical external caller could pass a URL that both (a) passes `isSafeHttpUrl` and (b) still carries the raw control bytes that get interpolated directly — defeating the OSC 8 boundary the same way the `text` sanitization exists to prevent, just on the other side of the wrapper. Now rejects (falls back to plain text) rather than stripping, since a mangled URL is worse than no link. Added tests for both the plain non-http(s)-scheme case and this control-byte case. - Extracted `conflictExistingName()` — a third near-identical copy of the `existing_datamate_name ? stripControlChars(...) : "another workspace"` ternary had appeared in a third catch block (this file's own `buildManageUrl` duplication history predicted exactly this failure mode). All three call sites now share one implementation. - `workspace.tsx` imported the shared `buildManageUrl` under an alias (`as joinManageUrlPath`) solely to avoid colliding with its own local async wrapper of the same name — which made the *real* `buildManageUrl` invisible under that name inside the file, and left `workspace.tsx` and `workspace-sidebar.tsx` importing the same function under two different local names. Renamed the local wrapper to `resolveManageUrl` and import the shared function under its real name in both files. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JsVwcBQP6VUwqEej3vK2zG --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
1 parent 342370e commit 463b89c

6 files changed

Lines changed: 633 additions & 93 deletions

File tree

‎packages/opencode/src/altimate/workspace/browser-handoff.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,30 @@ export function resolveWorkspaceWebUrl(altimateUrl: string, tenant: string): URL
184184
}
185185
}
186186

187+
/** Append ``/w/<id>`` to ``base``'s pathname using real URL semantics, rather
188+
* than string-concatenating ``toString()``. The dev-only
189+
* ``ALTIMATE_WORKSPACE_WEB_URL`` override (above) can carry its own path/
190+
* query/fragment (e.g. a local dev server), and naive concatenation would
191+
* land ``/w/<id>`` inside the query string instead of the path — clears
192+
* search/hash for the same reason.
193+
*
194+
* Lives beside ``resolveWorkspaceWebUrl`` (this module is already imported
195+
* by both the CLI (``cli/cmd/link.ts``) and the TUI plugin
196+
* (``plugin/tui/altimate/workspace.tsx`` / ``workspace-sidebar.tsx``) for
197+
* that function, so sharing this one too doesn't cross the deliberate CLI/
198+
* TUI self-containment boundary the way importing FROM one side INTO the
199+
* other would (see ``isSafeHttpUrl``'s split in ``link.ts`` for that
200+
* reasoning). Previously duplicated as three near-identical private copies
201+
* — one bug (missing this exact fix) needed three separate edits to close.
202+
* (multi-model review, PR #1274 round 7.) */
203+
export function buildManageUrl(base: URL, workspaceId: number): string {
204+
const u = new URL(base)
205+
u.pathname = `${u.pathname.replace(/\/+$/, "")}/w/${workspaceId}`
206+
u.search = ""
207+
u.hash = ""
208+
return u.toString()
209+
}
210+
187211
interface HandoffPending {
188212
state: string
189213
expectedTenant: string

‎packages/opencode/src/cli/cmd/link.ts‎

Lines changed: 176 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
resolveProjectIdentifier,
3434
} from "@/altimate/workspace/detect"
3535
import {
36+
buildManageUrl,
3637
openWorkspaceBrowserHandoff,
3738
resolveWorkspaceWebUrl,
3839
type HandoffResult,
@@ -42,6 +43,121 @@ import { recordApprovedBinding } from "@/altimate/workspace/state"
4243
const CREATE_NEW_SENTINEL = "__create_new__"
4344
const SET_UP_IN_BROWSER_SENTINEL = "__browser_handoff__"
4445

46+
/** Strip C0/C1 control bytes (including ESC) from server-controlled text
47+
* before it reaches a raw-stdout escape-sequence wrapper. Workspace names
48+
* come from ``WorkspaceApi.listDatamates()`` with no charset validation — an
49+
* attacker-controlled name containing its own ``\x1b]8;;`` could otherwise
50+
* prematurely close our hyperlink and open a spoofed one pointing wherever
51+
* they choose, with our trusted URL as the visible (but inert) prefix.
52+
* (CodeRabbit + cubic, PR #1274.) */
53+
export function stripControlChars(text: string): string {
54+
// C0 (\x00-\x1f) + DEL (\x7f) + C1 (\x80-\x9f) — the previous range only
55+
// covered C0/DEL, leaving C1 controls unstripped. ESC (the OSC 8 breakout
56+
// vector) was always covered, but the doc comment claimed C1 coverage it
57+
// didn't have. (Kilo, PR #1274.)
58+
// eslint-disable-next-line no-control-regex
59+
return text.replace(/[\x00-\x1f\x7f-\x9f]/g, "")
60+
}
61+
62+
/** Sanitized display name for a ``ConflictError``'s existing-binding name,
63+
* with a stable fallback when the server didn't send one. A third
64+
* near-identical copy of this exact ternary appeared across three different
65+
* catch blocks in this file before being extracted here — same drift risk
66+
* ``buildManageUrl``'s move to ``browser-handoff.ts`` (see that function's
67+
* comment) was extracted to avoid: a security-relevant pattern duplicated
68+
* per call site only stays in sync by accident. (Kilo, PR #1274 round 8.) */
69+
function conflictExistingName(detail: { existing_datamate_name?: string | null }): string {
70+
return detail.existing_datamate_name ? stripControlChars(detail.existing_datamate_name) : "another workspace"
71+
}
72+
73+
/** Conservative allowlist of terminals known to render OSC 8 hyperlinks.
74+
* There's no capability query as reliable as opentui's device-attribute
75+
* detection (used by the TUI side) available to a plain CLI process, so this
76+
* errs toward false negatives — worst case a supporting terminal renders
77+
* plain text instead of a link, which is a strict improvement over the
78+
* inverse (underlining text that turns out not to be clickable). Mirrors the
79+
* checks the `supports-hyperlinks` package uses, inlined to avoid a new
80+
* dependency for one CLI affordance.
81+
*
82+
* Deliberately excludes ``Apple_Terminal`` (macOS Terminal.app): OSC 8
83+
* support only landed there in macOS Sequoia (Sept 2024) — older versions
84+
* (Ventura/Sonoma and earlier) only auto-linkify plain-text URLs, not OSC 8.
85+
* ``TERM_PROGRAM`` carries no OS/Terminal-version signal to tell those apart,
86+
* and this function's own stated bias is toward false negatives, so it's
87+
* left off the list rather than guessing the user is on a current-enough
88+
* macOS. (Kilo, PR #1274 — corrects an earlier version of this list that
89+
* included it.) */
90+
export function terminalSupportsHyperlinks(): boolean {
91+
if (!process.stdout.isTTY) return false
92+
if (process.env.TERM === "dumb" || process.env.TERM === "linux") return false
93+
const termProgram = process.env.TERM_PROGRAM
94+
if (termProgram && ["iTerm.app", "WezTerm", "Hyper", "vscode", "ghostty", "Tabby", "rio"].includes(termProgram))
95+
return true
96+
if (process.env.WT_SESSION) return true // Windows Terminal
97+
if (process.env.KONSOLE_VERSION) return true
98+
const vte = Number(process.env.VTE_VERSION)
99+
if (!Number.isNaN(vte) && vte >= 5000) return true // VTE >= 0.50.0 (GNOME Terminal and other VTE-based terms)
100+
return false
101+
}
102+
103+
/** Wrap ``text`` in an OSC 8 terminal hyperlink pointing at ``url``, or return
104+
* ``text`` unchanged when ``url`` is null. Unlike the TUI's `<a href>` (which
105+
* crashes in the current @opentui/solid JSX layer — see workspace-sidebar.tsx),
106+
* plain stdout can emit OSC 8 directly: a terminal directly interpreting the
107+
* bytes either renders a real clickable link or silently skips the sequence
108+
* it doesn't recognize — the visible text is unaffected either way. That
109+
* "harmless when unrecognized" argument only holds when a terminal emulator
110+
* is actually the one reading the bytes, though: with stdout redirected to a
111+
* file or piped into another program (stdin can still be a TTY — the
112+
* interactive-stdin check in the handler doesn't imply stdout is a terminal
113+
* too), there's no interpreter to skip them, so the raw escape sequence
114+
* would land as literal junk in the captured output. Skip the OSC 8 wrapping
115+
* entirely in that case. The *underline* is additionally gated on
116+
* ``terminalSupportsHyperlinks`` — a much older and more universally-rendered
117+
* SGR code than OSC 8, so emitting it unconditionally would make the name
118+
* look clickable in terminals where it isn't. (cubic, PR #1274, rounds 2 + 3.) */
119+
export function hyperlink(text: string, url: string | null): string {
120+
if (!text) return text
121+
const safeText = stripControlChars(text)
122+
// Sanitize before checking `url` — the null-URL early return used to skip
123+
// stripControlChars entirely, so a caller relying on hyperlink() as its
124+
// sanitization boundary got the raw name whenever no manage URL existed
125+
// (BYOK/unresolvable deployments). Every caller in this file now also
126+
// sanitizes independently before calling this (defense in depth, not the
127+
// sole boundary), but this fixes the function's own contract too.
128+
// (CodeRabbit, PR #1274 round 4.)
129+
//
130+
// Also validate `url` itself, not just `text` — hyperlink() is exported
131+
// (tests import it directly), so its contract is wider than its two
132+
// in-file callers, both of which only ever pass a `buildManageUrl(...)`-
133+
// derived trusted URL. A hypothetical external caller passing something
134+
// unvalidated (e.g. a raw `manage_url` straight from an API response)
135+
// would otherwise defeat the escaping this function is careful about on
136+
// the `text` side while doing nothing for `url`. (multi-model review, PR
137+
// #1274 round 7.)
138+
//
139+
// isSafeHttpUrl only checks that `url` PARSES as http(s) via `new URL()`
140+
// — it doesn't sanitize, and doesn't return the re-serialized/encoded
141+
// form. `new URL()` itself percent-encodes control bytes when it builds
142+
// its own `.toString()`, but that encoding never reaches the ORIGINAL
143+
// `url` string this function actually interpolates below — a string can
144+
// contain a live ESC byte and still parse successfully as a valid
145+
// https: URL (verified: `new URL("https://evil.example/\x1b]8;;...")`
146+
// does not throw). So `isSafeHttpUrl` returning true does not mean `url`
147+
// is free of control bytes; reject it separately, the same way `text` is
148+
// sanitized above — rejecting (falling back to plain text) rather than
149+
// stripping, since a mangled URL is worse than no link at all. (cubic,
150+
// PR #1274 round 8.)
151+
if (!url || stripControlChars(url) !== url || !isSafeHttpUrl(url)) return safeText
152+
if (!process.stdout.isTTY) return safeText
153+
const OSC8 = "\x1b]8;;"
154+
const ST = "\x1b\\"
155+
if (!terminalSupportsHyperlinks()) return `${OSC8}${url}${ST}${safeText}${OSC8}${ST}`
156+
const UNDERLINE = "\x1b[4m"
157+
const UNDERLINE_OFF = "\x1b[24m"
158+
return `${OSC8}${url}${ST}${UNDERLINE}${safeText}${UNDERLINE_OFF}${OSC8}${ST}`
159+
}
160+
45161
export const LinkCommand = cmd({
46162
command: "link",
47163
describe: "Link this project to an Altimate workspace",
@@ -122,14 +238,35 @@ export const LinkCommand = cmd({
122238
? projectNameFromRemote(identifier.repoRemote)
123239
: projectNameFromPath(identifier.projectPath)
124240
const currentId = existing?.datamate.id
125-
const currentName = existing?.datamate.name
241+
// Sanitized once here so every downstream display (the picker message,
242+
// the "Kept" outro, hyperlink()'s own text) is covered — hyperlink()
243+
// only sanitized its own `text` param, not the raw name reaching
244+
// `prompts.outro`/`prompts.select`'s message directly. (CodeRabbit,
245+
// PR #1274 round 4 — flagged one call site; the underlying gap was
246+
// every raw name-interpolation in this file, not just that one.)
247+
const currentName = existing ? stripControlChars(existing.datamate.name) : undefined
126248

127249
// Only offer the browser-based handoff when the deployment supports it
128250
// (freemium only today). Enterprise / localhost / custom-domain callers
129251
// silently fall back to the CLI-side quick create.
130252
const creds = await AltimateApi.getCredentials()
131-
const browserAvailable =
132-
resolveWorkspaceWebUrl(creds.altimateUrl, creds.altimateInstanceName) !== null
253+
const workspaceWebBase = resolveWorkspaceWebUrl(creds.altimateUrl, creds.altimateInstanceName)
254+
const browserAvailable = workspaceWebBase !== null
255+
// Deterministic from tenant + id, same derivation as the TUI's
256+
// buildManageUrl (workspace.tsx) — null on BYOK/unresolvable, in which
257+
// case the name below prints as plain (non-clickable) text.
258+
const currentManageUrl =
259+
currentId !== undefined && workspaceWebBase ? buildManageUrl(workspaceWebBase, currentId) : null
260+
// On a terminal `terminalSupportsHyperlinks()` doesn't recognize, the
261+
// OSC 8 wrapping below is invisible bytes and the name renders as plain
262+
// text with no indication a URL exists at all — unlike the TUI, which
263+
// falls back to a toast ("Could not open browser. Copy this URL: ...").
264+
// Print the plain URL once as a fallback the terminal can't hide, rather
265+
// than leaving it unreachable outside the allowlist. (multi-model
266+
// review, PR #1274.)
267+
if (currentManageUrl && !terminalSupportsHyperlinks()) {
268+
prompts.log.info(`Manage it at: ${currentManageUrl}`)
269+
}
133270

134271
const options: Array<{ value: string; label: string; hint?: string }> = [
135272
// Only offer browser handoff for UNLINKED projects (CodeRabbit cycle 5).
@@ -160,16 +297,22 @@ export const LinkCommand = cmd({
160297
? "Creates a new workspace and repoints this project to it (no browser step)."
161298
: "No browser step; configure integrations later in the SaaS.",
162299
},
163-
...list.map((dm) => ({
164-
value: String(dm.id),
165-
label: dm.id === currentId ? `● ${dm.name}` : ` ${dm.name}`,
166-
hint: dm.id === currentId ? "currently linked here" : undefined,
167-
})),
300+
...list.map((dm) => {
301+
// Every row's name is server-controlled (any workspace the account
302+
// can see, not just ones this user created) — sanitize regardless
303+
// of whether this row also goes through hyperlink() below.
304+
const safeDmName = stripControlChars(dm.name)
305+
return {
306+
value: String(dm.id),
307+
label: dm.id === currentId ? `● ${hyperlink(safeDmName, currentManageUrl)}` : ` ${safeDmName}`,
308+
hint: dm.id === currentId ? "currently linked here" : undefined,
309+
}
310+
}),
168311
]
169312

170313
const pick = await prompts.select<string>({
171314
message: existing
172-
? `Currently linked to "${currentName}". Pick a workspace (or create a new one):`
315+
? `Currently linked to "${hyperlink(currentName!, currentManageUrl)}". Pick a workspace (or create a new one):`
173316
: "Pick a workspace to link (or create a new one):",
174317
options,
175318
initialValue: currentId !== undefined ? String(currentId) : CREATE_NEW_SENTINEL,
@@ -261,16 +404,17 @@ async function runBrowserHandoff(
261404
projectPath: res.binding.project_path,
262405
linkedAt: Date.now(),
263406
}, { awaitBackfill: true })
264-
bindSpin.stop(`Linked to "${res.binding.datamate_name}".`)
407+
bindSpin.stop(`Linked to "${stripControlChars(res.binding.datamate_name)}".`)
265408
prompts.log.info("Saved memory blocks will sync to this workspace if memory is enabled for it.")
266409
const manageUrl = await manageUrlFor(res.binding.datamate_id)
267410
if (manageUrl) prompts.log.info(`Manage it at: ${manageUrl}`)
268411
prompts.outro("Done.")
269412
} catch (err) {
270413
bindSpin.stop("Link failed.", 1)
271414
if (err instanceof ConflictError) {
415+
const existingName = conflictExistingName(err.detail)
272416
prompts.log.error(
273-
`This project is already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Workspace "${projectName}" was created but is not linked — re-run \`altimate-code link\` and pick a different action to switch, or delete the new workspace in the SaaS.`,
417+
`This project is already linked to "${existingName}". Workspace "${projectName}" was created but is not linked — re-run \`altimate-code link\` and pick a different action to switch, or delete the new workspace in the SaaS.`,
274418
)
275419
} else if (err instanceof NotFoundError) {
276420
prompts.log.error("Workspace not found — the tenant or workspace may have changed.")
@@ -284,13 +428,17 @@ async function runBrowserHandoff(
284428
}
285429

286430
/** Best-effort manage-workspace URL for the current credentials. Returns null
287-
* on BYOK / unresolvable deployments — callers omit the "Manage it at" line. */
431+
* on BYOK / unresolvable deployments — callers omit the "Manage it at" line.
432+
* Delegates the actual join to ``buildManageUrl`` rather than re-deriving it —
433+
* this function had its own copy of the pre-fix string-concatenation bug
434+
* (cubic, PR #1274 round 3): two near-identical builders in the same file
435+
* drifted, and only one got fixed the first time around. */
288436
async function manageUrlFor(workspaceId: number): Promise<string | null> {
289437
try {
290438
const creds = await AltimateApi.getCredentials()
291439
const base = resolveWorkspaceWebUrl(creds.altimateUrl, creds.altimateInstanceName)
292440
if (!base) return null
293-
return `${base.toString().replace(/\/$/, "")}/w/${workspaceId}`
441+
return buildManageUrl(base, workspaceId)
294442
} catch {
295443
return null
296444
}
@@ -343,36 +491,41 @@ async function createThenBindOrRebind(
343491
// can pick from the list; if the pre-check missed it, this is the
344492
// authoritative signal — surface it and hint the picker.
345493
if (err instanceof ConflictError) {
494+
const existingName = conflictExistingName(err.detail)
346495
prompts.log.error(
347-
`This project is already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Re-run \`altimate-code link\` to switch to a different workspace.`,
496+
`This project is already linked to "${existingName}". Re-run \`altimate-code link\` to switch to a different workspace.`,
348497
)
349498
} else {
350499
prompts.log.error(err instanceof Error ? err.message : String(err))
351500
}
352501
process.exitCode = 1
353502
return
354503
}
355-
spin.stop(`Workspace "${created.datamate.name}" created.`)
504+
// Sanitized once — echoed back from the create-workspace API response
505+
// (not the locally-typed `name` param), so it's technically server data
506+
// even though it usually just round-trips the caller's own auto-name.
507+
const safeCreatedName = stripControlChars(created.datamate.name)
508+
spin.stop(`Workspace "${safeCreatedName}" created.`)
356509

357510
// If the project was already linked, the new workspace exists but the
358511
// binding still points at the OLD workspace — rebind so the project is
359512
// now bound to the freshly-created one. Otherwise createAndBind already
360513
// wrote the binding as part of the atomic create; we're done.
361514
if (existing) {
362515
const rebindSpin = prompts.spinner()
363-
rebindSpin.start(`Repointing project at "${created.datamate.name}"...`)
516+
rebindSpin.start(`Repointing project at "${safeCreatedName}"...`)
364517
try {
365518
await rebindByMatchedIdentifier({
366519
identifier,
367520
targetDatamateId: created.datamate.id,
368521
expectedCurrentDatamateId: existing.datamate.id,
369522
matchedBy: existing.matchedBy,
370523
})
371-
rebindSpin.stop(`Project is now linked to "${created.datamate.name}".`)
524+
rebindSpin.stop(`Project is now linked to "${safeCreatedName}".`)
372525
} catch (err) {
373526
rebindSpin.stop("Could not repoint the project.", 1)
374527
prompts.log.error(
375-
`Workspace "${created.datamate.name}" was CREATED but could not be linked to this project. ${err instanceof Error ? err.message : String(err)} — re-run \`altimate-code link\` to retry (or delete the workspace in the SaaS).`,
528+
`Workspace "${safeCreatedName}" was CREATED but could not be linked to this project. ${err instanceof Error ? err.message : String(err)} — re-run \`altimate-code link\` to retry (or delete the workspace in the SaaS).`,
376529
)
377530
process.exitCode = 1
378531
return
@@ -490,7 +643,7 @@ async function bindOrRebind(
490643
targetDatamateId,
491644
})
492645
}
493-
rebindSpin.stop(`Re-linked to "${res.binding.datamate_name}".`)
646+
rebindSpin.stop(`Re-linked to "${stripControlChars(res.binding.datamate_name)}".`)
494647
} catch (retryErr) {
495648
rebindSpin.stop("Re-link failed.", 1)
496649
throw retryErr
@@ -508,21 +661,17 @@ async function bindOrRebind(
508661
projectPath: res.binding.project_path,
509662
linkedAt: Date.now(),
510663
}, { awaitBackfill: true })
511-
spin.stop(
512-
isRebind
513-
? `Re-linked to "${res.binding.datamate_name}".`
514-
: `Linked to "${res.binding.datamate_name}".`,
515-
)
664+
const safeResName = stripControlChars(res.binding.datamate_name)
665+
spin.stop(isRebind ? `Re-linked to "${safeResName}".` : `Linked to "${safeResName}".`)
516666
prompts.log.info("Saved memory blocks will sync to this workspace if memory is enabled for it.")
517667
const manageUrl = await manageUrlFor(res.binding.datamate_id)
518668
if (manageUrl) prompts.log.info(`Manage it at: ${manageUrl}`)
519669
prompts.outro("Done.")
520670
} catch (err) {
521671
spin.stop(isRebind ? `Re-link failed.` : `Link failed.`, 1)
522672
if (err instanceof ConflictError) {
523-
prompts.log.error(
524-
`Already linked to "${err.detail.existing_datamate_name ?? "another workspace"}". Re-run \`altimate-code link\` to switch.`,
525-
)
673+
const existingName = conflictExistingName(err.detail)
674+
prompts.log.error(`Already linked to "${existingName}". Re-run \`altimate-code link\` to switch.`)
526675
} else if (err instanceof PreconditionFailedError) {
527676
prompts.log.error("Someone else re-linked this project — re-run and try again.")
528677
} else if (err instanceof NotFoundError) {

0 commit comments

Comments
 (0)