Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): open terminal links and workspace paths

rubenluetke10-beep4b578bbfe765
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.py
index e4a29ee294..40ba349753 100644
--- a/jarvis/ui/web/agentic_ide_routes.py
+++ b/jarvis/ui/web/agentic_ide_routes.py
@@ -11,6 +11,7 @@ Endpoints (prefix ``/api/agentic-ide``):
* ``GET /folders`` → browse folders (no path = start points)
* ``GET /folders/native`` → can this machine show the OS folder window?
* ``POST /folders/native`` → open it and return what was picked
+* ``POST /terminal-target/open`` → open a path printed by one terminal
* ``GET /workspaces`` → every open workspace, in tab order
* ``PUT /workspaces/active`` → bring one to the front (null = wizard)
* ``PATCH /workspaces/{workspace_id}`` → rename one workspace tab
@@ -51,6 +52,7 @@ from __future__ import annotations
import asyncio
import logging
+import re
from dataclasses import asdict
from pathlib import Path
@@ -607,6 +609,23 @@ class NativePickResponse(BaseModel):
error: str | None = Field(default=None, description="Why no folder came back.")
+class OpenTerminalTargetRequest(BaseModel):
+ """A path explicitly activated in one Agentic-IDE terminal."""
+
+ workspace_id: str = Field(
+ min_length=1,
+ max_length=160,
+ description="Workspace whose root relative paths are resolved against.",
+ )
+ target: str = Field(
+ min_length=1,
+ max_length=4096,
+ description=(
+ "Printed file/folder path or file URI, optionally followed by a line and column suffix."
+ ),
+ )
+
+
class ResolveRequest(BaseModel):
path: str | None = Field(
default=None,
@@ -1210,6 +1229,105 @@ async def open_native_picker(request: Request, req: NativePickRequest) -> Native
return NativePickResponse(path=result.path, cancelled=result.cancelled, error=result.error)
+_TERMINAL_LOCATION_SUFFIX = re.compile(
+ r"(?:#L[1-9]\d*(?::[1-9]\d*)?|:[1-9]\d*(?::[1-9]\d*)?|"
+ r"\([1-9]\d*(?:,[1-9]\d*)?\))$",
+ re.IGNORECASE,
+)
+
+
+def _resolve_terminal_target(workspace_folder: str, printed: str) -> Path:
+ """Resolve a printed path without letting terminal output escape its workspace.
+
+ Coding-CLI output is untrusted. A modifier-click is deliberate, but it must
+ still not turn an OSC-8 payload into an arbitrary local file launcher.
+ Relative and absolute paths must therefore resolve inside the pane's own
+ workspace, including after symlinks are followed. Common line/column
+ locators are accepted because compilers and agents routinely print them.
+ """
+ value = printed.strip()
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in {'"', "'", "`"}:
+ value = value[1:-1].strip()
+ value = _TERMINAL_LOCATION_SUFFIX.sub("", value)
+ if not value or any(ord(char) < 32 for char in value):
+ raise ValueError("invalid terminal target")
+
+ if value.lower().startswith("file:"):
+ from urllib.parse import unquote, urlparse
+
+ parsed = urlparse(value)
+ if parsed.scheme.lower() != "file" or parsed.query or parsed.fragment:
+ raise ValueError("invalid file URI")
+ if parsed.netloc and parsed.netloc.casefold() != "localhost":
+ raise ValueError("remote file URI")
+ value = unquote(parsed.path)
+ # Local Windows file URIs are written as file:///C:/path.
+ if len(value) > 2 and value[0] == "/" and value[2] == ":":
+ value = value[1:]
+ if not value or any(ord(char) < 32 for char in value):
+ raise ValueError("invalid file URI")
+ elif "://" in value:
+ raise ValueError("unsupported URI scheme")
+
+ root = Path(workspace_folder).expanduser().resolve(strict=True)
+ candidate = Path(value).expanduser()
+ if not candidate.is_absolute():
+ candidate = root / candidate
+ target = candidate.resolve(strict=True)
+ try:
+ target.relative_to(root)
+ except ValueError as exc:
+ raise ValueError("terminal target escapes workspace") from exc
+ if not (target.is_file() or target.is_dir()):
+ raise ValueError("terminal target is not openable")
+ return target
+
+
+ "/terminal-target/open",
+ summary="Open a file or folder linked in an Agentic-IDE terminal",
+)
+async def open_terminal_target(
+ request: Request, req: OpenTerminalTargetRequest
+) -> dict[str, object]:
+ """Open a modifier-clicked workspace path with the operating-system default.
+
+ This is local-desktop-only: a remote browser would otherwise act on the
+ server's screen. Resolution is confined to the addressed open workspace
+ before the shared cross-platform opener sees the path.
+ """
+ if not is_loopback_request(request.scope):
+ raise HTTPException(
+ status_code=403,
+ detail="Terminal paths can only be opened on the computer running Jarvis.",
+ )
+ if not getattr(request.app.state, "native_file_actions", False):
+ raise HTTPException(status_code=404, detail="native file actions unavailable")
+
+ session = get_registry().get(req.workspace_id)
+ if session is None:
+ raise HTTPException(status_code=404, detail="That workspace is not open.")
+ try:
+ target = await asyncio.to_thread(_resolve_terminal_target, session.folder, req.target)
+ except (OSError, RuntimeError, ValueError) as exc:
+ # One answer for missing, malformed and outside-workspace paths: never
+ # disclose through a crafted terminal payload which local file exists.
+ raise HTTPException(status_code=404, detail="That workspace path is unavailable.") from exc
+
+ from jarvis.platform import open_path
+
+ opened = await asyncio.to_thread(open_path.open_file, target)
+ kind = "directory" if target.is_dir() else "file"
+ log.info(
+ "Agentic IDE terminal target: workspace=%s kind=%s opened=%s path=%s",
+ req.workspace_id,
+ kind,
+ opened,
+ target,
+ )
+ return {"opened": bool(opened), "kind": kind, "path": str(target)}
+
+
@router.get("/recents", response_model=RecentsResponse, summary="Recently opened workspaces")
async def get_recents() -> RecentsResponse:
"""Workspaces opened before, newest first, with their previous layout."""
diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
index 067c2fa52f..ae590d95cf 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx
@@ -98,8 +98,9 @@ import {
syncTerminalFont,
} from "@/lib/terminalFont";
import {
- activateTerminalLink,
- TERMINAL_OSC_LINK_HANDLER,
+ createTerminalLinkActivator,
+ createTerminalOscLinkHandler,
+ TerminalPathLinksAddon,
} from "@/lib/terminalLinks";
import { installPasteBridge } from "./terminalPaste";
import { installCopyBridge } from "./terminalCopy";
@@ -467,6 +468,11 @@ export function AgenticTerminal({
// the user the same "it is coming up" answer it owed on its first mount.
setPainted(false);
+ const linkOptions = {
+ workspaceId,
+ onError: (message: string) => onAttachErrorRef.current?.(message),
+ };
+ const activateLink = createTerminalLinkActivator(linkOptions);
const term = new Terminal({
convertEol: false,
// Shared with the measurement in ./../../lib/terminalFont: a pane that
@@ -494,7 +500,7 @@ export function AgenticTerminal({
// Plain clicks belong to text selection. xterm otherwise treats an
// ordinary click on an OSC-8 link as navigation and shows a native
// warning dialog inside the desktop WebView.
- linkHandler: TERMINAL_OSC_LINK_HANDLER,
+ linkHandler: createTerminalOscLinkHandler(linkOptions),
// Windows only. ConPTY re-emits and re-wraps lines in a way a POSIX pty
// never does; without telling xterm which backend it is talking to, those
// re-emitted lines pile up as duplicated, half-overwritten rows. Harmless
@@ -513,7 +519,10 @@ export function AgenticTerminal({
const disposeQuerySuppression = installQuerySuppression(term.parser);
const fit = new FitAddon();
term.loadAddon(fit);
- term.loadAddon(new WebLinksAddon(activateTerminalLink));
+ term.loadAddon(new WebLinksAddon(activateLink));
+ if (workspaceId) {
+ term.loadAddon(new TerminalPathLinksAddon(activateLink));
+ }
// Character WIDTH, not appearance: without this xterm measures emoji and
// many box/symbol glyphs as one cell while the agent on the other side
// counted two, and every such glyph shifts the rest of the line one column
@@ -1141,7 +1150,7 @@ export function AgenticTerminal({
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- see file header:
// appearance/fontSize must NOT rebuild the pane (it would kill the agent).
- }, [name, restartToken, geometryReady]);
+ }, [name, workspaceId, restartToken, geometryReady]);
/*
* A chat-stage switch changes a pane from `display:none` to the full canvas
diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
index abac622c94..e2c72d2883 100644
--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts
@@ -720,6 +720,30 @@ export async function openNativePicker(
return (await res.json()) as NativePickResult;
}
+export interface OpenTerminalTargetResult {
+ opened: boolean;
+ kind: "file" | "directory";
+ path: string;
+}
+
+/** Open a modifier-clicked path from one terminal's own workspace. */
+export async function openTerminalTarget(
+ workspaceId: string,
+ target: string,
+): Promise<OpenTerminalTargetResult> {
+ const res = await fetch("/api/agentic-ide/terminal-target/open", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ workspace_id: workspaceId, target }),
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ const result = (await res.json()) as OpenTerminalTargetResult;
+ if (!result.opened) {
+ throw new Error("Could not open that file or folder on this computer.");
+ }
+ return result;
+}
+
/**
* Turn a drag-and-drop payload into a folder path.
*
diff --git a/jarvis/ui/web/frontend/src/lib/terminalLinks.test.ts b/jarvis/ui/web/frontend/src/lib/terminalLinks.test.ts
index 9daad1bbf4..ef67da3519 100644
--- a/jarvis/ui/web/frontend/src/lib/terminalLinks.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/terminalLinks.test.ts
@@ -1,16 +1,30 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ILink, ILinkProvider, Terminal } from "@xterm/xterm";
vi.mock("@/lib/openExternal", () => ({
openExternalUrl: vi.fn(async () => undefined),
}));
+vi.mock("@/lib/agenticIdeApi", () => ({
+ openTerminalTarget: vi.fn(async () => ({
+ opened: true,
+ kind: "file",
+ path: "src/main.ts",
+ })),
+}));
+import { openTerminalTarget } from "@/lib/agenticIdeApi";
import { openExternalUrl } from "@/lib/openExternal";
import {
activateTerminalLink,
+ createTerminalLinkActivator,
+ createTerminalOscLinkHandler,
+ findTerminalPathMatches,
TERMINAL_OSC_LINK_HANDLER,
+ TerminalPathLinksAddon,
} from "./terminalLinks";
const openExternal = vi.mocked(openExternalUrl);
+const openTarget = vi.mocked(openTerminalTarget);
function click(options: MouseEventInit = {}): MouseEvent {
return new MouseEvent("mouseup", { button: 0, ...options });
@@ -19,6 +33,12 @@ function click(options: MouseEventInit = {}): MouseEvent {
describe("terminal links", () => {
beforeEach(() => {
openExternal.mockClear();
+ openTarget.mockClear();
+ openTarget.mockResolvedValue({
+ opened: true,
+ kind: "file",
+ path: "src/main.ts",
+ });
});
it("leaves ordinary clicks available for selecting linked terminal text", () => {
@@ -42,16 +62,68 @@ describe("terminal links", () => {
TERMINAL_OSC_LINK_HANDLER.activate(
click({ metaKey: true }),
"https://example.com/docs",
+ {
+ start: { x: 1, y: 1 },
+ end: { x: 4, y: 1 },
+ },
);
expect(openExternal).toHaveBeenCalledWith("https://example.com/docs");
});
- it("refuses non-web protocols even with a modifier", () => {
+ it("refuses non-web protocols and paths without workspace context", () => {
activateTerminalLink(click({ ctrlKey: true }), "javascript:alert(1)");
activateTerminalLink(click({ ctrlKey: true }), "file:///private/data");
expect(openExternal).not.toHaveBeenCalled();
+ expect(openTarget).not.toHaveBeenCalled();
+ });
+
+ it("opens a detected workspace path on Ctrl-click", () => {
+ activateTerminalLink(click({ ctrlKey: true }), "src/main.ts:42:7", {
+ workspaceId: "workspace-1",
+ });
+
+ expect(openTarget).toHaveBeenCalledWith(
+ "workspace-1",
+ "src/main.ts:42:7",
+ );
+ });
+
+ it("allows file OSC-8 links only when a workspace boundary is available", () => {
+ const handler = createTerminalOscLinkHandler({
+ workspaceId: "workspace-1",
+ });
+ handler.activate(
+ click({ metaKey: true }),
+ "file:///workspace/docs",
+ {
+ start: { x: 1, y: 1 },
+ end: { x: 4, y: 1 },
+ },
+ );
+
+ expect(handler.allowNonHttpProtocols).toBe(true);
+ expect(TERMINAL_OSC_LINK_HANDLER.allowNonHttpProtocols).toBe(false);
+ expect(openTarget).toHaveBeenCalledWith(
+ "workspace-1",
+ "file:///workspace/docs",
+ );
+ });
+
+ it("reports a native path-open failure instead of doing nothing", async () => {
+ const onError = vi.fn();
+ openTarget.mockRejectedValueOnce(new Error("That workspace path is unavailable."));
+
+ activateTerminalLink(click({ ctrlKey: true }), "docs/missing.md", {
+ workspaceId: "workspace-1",
+ onError,
+ });
+ await vi.waitFor(() => expect(onError).toHaveBeenCalledTimes(1));
+
+ expect(onError).toHaveBeenCalledWith(
+ "That workspace path is unavailable.",
+ );
});
it("does not open from a modified non-primary click", () => {
@@ -62,4 +134,81 @@ describe("terminal links", () => {
expect(openExternal).not.toHaveBeenCalled();
});
+
+ it("detects common file and folder forms without treating URLs as paths", () => {
+ const line =
+ 'Changed src/components/App.tsx:42:7, "C:\\Program Files\\Project\\notes.md" and /work/project/docs; see https://example.com/docs';
+
+ expect(findTerminalPathMatches(line).map((match) => match.text)).toEqual([
+ "src/components/App.tsx:42:7",
+ "C:\\Program Files\\Project\\notes.md",
+ "/work/project/docs",
+ ]);
+ });
+
+ it("recognises bare developer filenames and relative folders", () => {
+ expect(
+ findTerminalPathMatches("README.md ./scripts ../shared assets/icons/").map(
+ (match) => match.text,
+ ),
+ ).toEqual(["README.md", "./scripts", "../shared", "assets/icons/"]);
+ });
+
+ it("registers detected paths as xterm links with clickable cell ranges", () => {
+ const text = "Open src/main.ts:42";
+ const cell = {
+ value: "",
+ getChars() {
+ return this.value;
+ },
+ getWidth() {
+ return 1;
+ },
+ };
+ const line = {
+ isWrapped: false,
+ length: 80,
+ translateToString: () => text,
+ getCell(index: number, target: typeof cell) {
+ target.value = index < text.length ? text[index] : "";
+ return target;
+ },
+ };
+ let provider: ILinkProvider | undefined;
+ const terminal = {
+ buffer: {
+ active: {
+ getLine: (row: number) => (row === 0 ? line : undefined),
+ getNullCell: () => cell,
+ },
+ },
+ registerLinkProvider(value: ILinkProvider) {
+ provider = value;
+ return { dispose: vi.fn() };
+ },
+ } as unknown as Terminal;
+ const addon = new TerminalPathLinksAddon(
+ createTerminalLinkActivator({ workspaceId: "workspace-1" }),
+ );
+ addon.activate(terminal);
+
+ let links: ILink[] | undefined;
+ provider?.provideLinks(1, (value) => {
+ links = value;
+ });
+
+ expect(links).toHaveLength(1);
+ expect(links?.[0]).toMatchObject({
+ text: "src/main.ts:42",
+ range: {
+ start: { x: 6, y: 1 },
+ end: { x: 19, y: 1 },
+ },
+ });
+ links?.[0].activate(click({ ctrlKey: true }), links[0].text);
+ expect(openTarget).toHaveBeenCalledWith(
+ "workspace-1",
+ "src/main.ts:42",
+ );
+ });
});
diff --git a/jarvis/ui/web/frontend/src/lib/terminalLinks.ts b/jarvis/ui/web/frontend/src/lib/terminalLinks.ts
index f253b62b7d..d818cfeddc 100644
--- a/jarvis/ui/web/frontend/src/lib/terminalLinks.ts
+++ b/jarvis/ui/web/frontend/src/lib/terminalLinks.ts
@@ -1,14 +1,36 @@
-/**
- * Safe link activation shared by every embedded xterm terminal.
- *
- * Terminal output is untrusted and xterm's default OSC-8 handler opens a
- * native confirmation dialog on an ordinary click. That makes selecting text
- * which happens to carry a hyperlink look like a navigation attempt. Keep
- * ordinary clicks available for selection and require the conventional
- * Ctrl/Cmd modifier before opening an explicit HTTP(S) link.
- */
+/** Safe URL and workspace-path links shared by the embedded xterm terminals. */
+import type {
+ IDisposable,
+ ILink,
+ ILinkHandler,
+ ILinkProvider,
+ ITerminalAddon,
+ Terminal,
+} from "@xterm/xterm";
+
+import { openTerminalTarget } from "@/lib/agenticIdeApi";
import { openExternalUrl } from "@/lib/openExternal";
+const MAX_LOGICAL_LINE_CHARS = 4096;
+
+const BARE_FILE = /^(?:(?:readme|license|makefile|dockerfile|containerfile)|[^/\\]+\.(?:c|cc|cpp|h|hpp|cs|go|rs|java|kt|kts|swift|php|rb|py|pyi|js|mjs|cjs|jsx|ts|mts|cts|tsx|vue|svelte|html?|css|scss|sass|less|json|jsonl|ya?ml|toml|xml|md|mdx|txt|log|csv|tsv|sql|sh|bash|zsh|fish|ps1|bat|cmd|ini|cfg|conf|env|lock|diff|patch|pdf|png|jpe?g|gif|svg|webp))(?::[1-9]\d*(?::[1-9]\d*)?|#L[1-9]\d*(?::[1-9]\d*)?|\([1-9]\d*(?:,[1-9]\d*)?\))?$/i;
+
+const LOCATION_SUFFIX = /(?:#[lL][1-9]\d*(?::[1-9]\d*)?|:[1-9]\d*(?::[1-9]\d*)?|\([1-9]\d*(?:,[1-9]\d*)?\))$/;
+
+export interface TerminalLinkOptions {
+ /** Required for local paths; URLs do not need workspace context. */
+ workspaceId?: string;
+ onError?: (message: string) => void;
+}
+
+export interface TerminalPathMatch {
+ /** Exact text painted by xterm, including a useful line/column suffix. */
+ text: string;
+ /** UTF-16 string offsets in the logical (possibly wrapped) terminal line. */
+ start: number;
+ end: number;
+}
+
function isHttpUrl(value: string): boolean {
try {
const protocol = new URL(value).protocol;
@@ -18,13 +40,282 @@ function isHttpUrl(value: string): boolean {
}
}
-export function activateTerminalLink(event: MouseEvent, uri: string): void {
+/** Is this text plausibly a local path, without touching the filesystem? */
+export function isTerminalPath(value: string): boolean {
+ const target = value.trim().replace(LOCATION_SUFFIX, "");
+ if (!target) return false;
+ if (/^file:\/\//i.test(target)) return true;
+ // Other URI schemes are handled nowhere in this module. In particular, an
+ // OSC-8 javascript:/custom-app URI may never become a native launch.
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(target)) return false;
+ if (/^[a-z]:[\\/]/i.test(target)) return true;
+ if (/^\\\\[^\\]+\\[^\\]+/.test(target)) return true;
+ if (/^\/(?!\/).+/.test(target)) return true;
+ if (/^(?:\.{1,2}|~)[\\/]/.test(target)) return true;
+ if (/^[a-z0-9_@.+-][^:\s]*[\\/].*/i.test(target)) return true;
+ return BARE_FILE.test(value);
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error
+ ? error.message
+ : "Could not open that terminal path.";
+}
+
+/**
+ * Activate a terminal URL/path only on the conventional Ctrl/Cmd primary click.
+ *
+ * Ordinary clicks stay available for terminal selection. Paths additionally
+ * require a workspace id; the backend resolves and confines them there before
+ * it invokes the OS opener.
+ */
+export function activateTerminalLink(
+ event: MouseEvent,
+ uri: string,
+ options: TerminalLinkOptions = {},
+): void {
if (event.button !== 0 || (!event.ctrlKey && !event.metaKey)) return;
- if (!isHttpUrl(uri)) return;
- void openExternalUrl(uri);
+ if (isHttpUrl(uri)) {
+ void openExternalUrl(uri);
+ return;
+ }
+ if (!options.workspaceId || !isTerminalPath(uri)) return;
+ void openTerminalTarget(options.workspaceId, uri).catch((error: unknown) => {
+ const message = errorMessage(error);
+ if (options.onError) options.onError(message);
+ else console.warn("Could not open terminal path:", message);
+ });
+}
+
+export function createTerminalLinkActivator(
+ options: TerminalLinkOptions,
+): (event: MouseEvent, uri: string) => void {
+ return (event, uri) => activateTerminalLink(event, uri, options);
+}
+
+export function createTerminalOscLinkHandler(
+ options: TerminalLinkOptions = {},
+): ILinkHandler {
+ return {
+ activate: createTerminalLinkActivator(options),
+ // xterm drops file: links before activate unless this is explicit. The
+ // activator above still rejects every non-http/non-path value.
+ allowNonHttpProtocols: Boolean(options.workspaceId),
+ };
}
/** Handler for hyperlinks emitted through the terminal's OSC-8 protocol. */
-export const TERMINAL_OSC_LINK_HANDLER = {
- activate: activateTerminalLink,
-};
+export const TERMINAL_OSC_LINK_HANDLER = createTerminalOscLinkHandler();
+
+function closingDelimiterIsExtra(value: string, closer: string): boolean {
+ const opener = closer === ")" ? "(" : closer === "]" ? "[" : "{";
+ return value.split(closer).length > value.split(opener).length;
+}
+
+function trimToken(
+ token: string,
+ offset: number,
+): TerminalPathMatch | undefined {
+ let start = 0;
+ let end = token.length;
+ while (start < end && "([{<\"'`".includes(token[start])) start += 1;
+ while (end > start) {
+ const last = token[end - 1];
+ const candidate = token.slice(start, end);
+ if (".,;!?\"'`>".includes(last)) {
+ end -= 1;
+ continue;
+ }
+ if (")]}".includes(last) && closingDelimiterIsExtra(candidate, last)) {
+ end -= 1;
+ continue;
+ }
+ break;
+ }
+ const text = token.slice(start, end);
+ if (!text || text.includes("](") || !isTerminalPath(text)) return undefined;
+ return { text, start: offset + start, end: offset + end };
+}
+
+/** Find file/folder candidates in one ANSI-free logical terminal line. */
+export function findTerminalPathMatches(line: string): TerminalPathMatch[] {
+ const matches: TerminalPathMatch[] = [];
+ const quotedRanges: Array<[number, number]> = [];
+ const add = (token: string, offset: number) => {
+ const found = trimToken(token, offset);
+ if (!found || found.text.length > MAX_LOGICAL_LINE_CHARS) return;
+ if (
+ matches.some(
+ (item) => item.start === found.start && item.end === found.end,
+ )
+ ) {
+ return;
+ }
+ matches.push(found);
+ };
+
+ // Quoting is how shells make paths with spaces unambiguous. Keep the quote
+ // itself out of the clickable range and send only the path to the backend.
+ for (const match of line.matchAll(/(["'`])([^"'`\r\n]+)\1/g)) {
+ if (match.index === undefined) continue;
+ const start = match.index + 1;
+ quotedRanges.push([match.index, match.index + match[0].length]);
+ add(match[2], start);
+ }
+
+ for (const match of line.matchAll(/\S+/g)) {
+ if (match.index === undefined) continue;
+ const end = match.index + match[0].length;
+ if (quotedRanges.some(([from, to]) => match.index! < to && end > from)) {
+ continue;
+ }
+ add(match[0], match.index);
+ }
+ return matches.sort((left, right) => left.start - right.start);
+}
+
+interface LogicalLine {
+ text: string;
+ /** Zero-based row in xterm's active buffer. */
+ startRow: number;
+}
+
+function logicalLineAt(
+ terminal: Terminal,
+ bufferLineNumber: number,
+): LogicalLine | undefined {
+ const buffer = terminal.buffer.active;
+ let startRow = bufferLineNumber - 1;
+ let line = buffer.getLine(startRow);
+ if (!line) return undefined;
+
+ let scannedBackward = 0;
+ while (
+ line.isWrapped &&
+ startRow > 0 &&
+ scannedBackward < MAX_LOGICAL_LINE_CHARS
+ ) {
+ const previous = buffer.getLine(startRow - 1);
+ if (!previous) break;
+ startRow -= 1;
+ line = previous;
+ scannedBackward += line.translateToString(true).length;
+ }
+
+ const chunks: string[] = [];
+ let row = startRow;
+ let measured = 0;
+ while (measured < MAX_LOGICAL_LINE_CHARS) {
+ const current = buffer.getLine(row);
+ if (!current) break;
+ const text = current.translateToString(true);
+ chunks.push(text);
+ measured += text.length;
+ const next = buffer.getLine(row + 1);
+ if (!next?.isWrapped) break;
+ row += 1;
+ }
+ return { text: chunks.join(""), startRow };
+}
+
+/** Map a UTF-16 string offset back to xterm's row/cell coordinates. */
+function mapStringIndex(
+ terminal: Terminal,
+ initialRow: number,
+ initialColumn: number,
+ chars: number,
+): [number, number] | undefined {
+ const buffer = terminal.buffer.active;
+ const cell = buffer.getNullCell();
+ let row = initialRow;
+ let column = initialColumn;
+ let remaining = chars;
+ while (remaining > 0) {
+ const line = buffer.getLine(row);
+ if (!line) return undefined;
+ for (let index = column; index < line.length; index += 1) {
+ const current = line.getCell(index, cell);
+ if (!current) continue;
+ const value = current.getChars();
+ if (current.getWidth() > 0) {
+ remaining -= value.length || 1;
+ if (index === line.length - 1 && value === "") {
+ const next = buffer.getLine(row + 1);
+ if (next?.isWrapped && next.getCell(0, cell)?.getWidth() === 2) {
+ remaining += 1;
+ }
+ }
+ }
+ if (remaining < 0) return [row, index];
+ }
+ row += 1;
+ column = 0;
+ }
+ return [row, column];
+}
+
+class TerminalPathLinkProvider implements ILinkProvider {
+ constructor(
+ private readonly terminal: Terminal,
+ private readonly handler: (event: MouseEvent, uri: string) => void,
+ ) {}
+
+ provideLinks(
+ bufferLineNumber: number,
+ callback: (links: ILink[] | undefined) => void,
+ ): void {
+ const logical = logicalLineAt(this.terminal, bufferLineNumber);
+ if (!logical) {
+ callback(undefined);
+ return;
+ }
+ const links = findTerminalPathMatches(logical.text).flatMap((match) => {
+ const start = mapStringIndex(
+ this.terminal,
+ logical.startRow,
+ 0,
+ match.start,
+ );
+ if (!start) return [];
+ const end = mapStringIndex(
+ this.terminal,
+ start[0],
+ start[1],
+ match.text.length,
+ );
+ if (!end) return [];
+ return [
+ {
+ text: match.text,
+ range: {
+ start: { x: start[1] + 1, y: start[0] + 1 },
+ end: { x: end[1], y: end[0] + 1 },
+ },
+ activate: this.handler,
+ },
+ ];
+ });
+ callback(links.length ? links : undefined);
+ }
+}
+
+/** xterm addon that makes printed workspace paths hoverable and activatable. */
+export class TerminalPathLinksAddon implements ITerminalAddon {
+ private registration?: IDisposable;
+
+ constructor(
+ private readonly handler: (event: MouseEvent, uri: string) => void,
+ ) {}
+
+ activate(terminal: Terminal): void {
+ this.registration?.dispose();
+ this.registration = terminal.registerLinkProvider(
+ new TerminalPathLinkProvider(terminal, this.handler),
+ );
+ }
+
+ dispose(): void {
+ this.registration?.dispose();
+ this.registration = undefined;
+ }
+}
diff --git a/tests/unit/agentic_ide/test_terminal_target_route.py b/tests/unit/agentic_ide/test_terminal_target_route.py
new file mode 100644
index 0000000000..049fad38a9
--- /dev/null
+++ b/tests/unit/agentic_ide/test_terminal_target_route.py
@@ -0,0 +1,150 @@
+"""Opening file and folder paths printed inside Agentic-IDE terminals.
+
+The modifier-click is explicit, but the text came from an untrusted terminal.
+These tests keep the useful path forms together with their boundary: only an
+open workspace on the local desktop, and never anything outside that workspace.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+
+from jarvis.platform import open_path
+from jarvis.ui.web import agentic_ide_routes as routes
+
+
+def _request(*, native: bool = True) -> SimpleNamespace:
+ return SimpleNamespace(
+ scope={},
+ app=SimpleNamespace(state=SimpleNamespace(native_file_actions=native)),
+ )
+
+
+def workspace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ root = tmp_path / "project"
+ root.mkdir()
+ session = SimpleNamespace(folder=str(root))
+ registry = SimpleNamespace(
+ get=lambda workspace_id: session if workspace_id == "workspace-1" else None
+ )
+ monkeypatch.setattr(routes, "get_registry", lambda: registry)
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: True)
+ return root
+
+
+def _record_opens(monkeypatch: pytest.MonkeyPatch) -> list[Path]:
+ opened: list[Path] = []
+ monkeypatch.setattr(
+ open_path,
+ "open_file",
+ lambda target: opened.append(target) or True,
+ )
+ return opened
+
+
+async def test_ctrl_click_opens_a_relative_file_with_a_line_locator(
+ workspace: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = workspace / "src" / "main.py"
+ target.parent.mkdir()
+ target.write_text("print('ready')\n", encoding="utf-8")
+ opened = _record_opens(monkeypatch)
+
+ result = await routes.open_terminal_target(
+ _request(),
+ routes.OpenTerminalTargetRequest(workspace_id="workspace-1", target="src/main.py:42:7"),
+ )
+
+ assert result["opened"] is True
+ assert result["kind"] == "file"
+ assert opened == [target.resolve()]
+
+
+async def test_ctrl_click_opens_a_quoted_folder(
+ workspace: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = workspace / "folder with spaces"
+ target.mkdir()
+ opened = _record_opens(monkeypatch)
+
+ result = await routes.open_terminal_target(
+ _request(),
+ routes.OpenTerminalTargetRequest(workspace_id="workspace-1", target=f'"{target}"'),
+ )
+
+ assert result["kind"] == "directory"
+ assert opened == [target.resolve()]
+
+
+async def test_a_local_file_uri_is_unwrapped_before_opening(
+ workspace: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ target = workspace / "notes.md"
+ target.write_text("notes\n", encoding="utf-8")
+ opened = _record_opens(monkeypatch)
+
+ await routes.open_terminal_target(
+ _request(),
+ routes.OpenTerminalTargetRequest(
+ workspace_id="workspace-1", target=target.resolve().as_uri()
+ ),
+ )
+
+ assert opened == [target.resolve()]
+
+
[email protected]("printed", ["../outside.txt", "https://example.com/file"])
+async def test_terminal_output_cannot_open_outside_the_workspace(
+ workspace: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ printed: str,
+) -> None:
+ (workspace.parent / "outside.txt").write_text("private\n", encoding="utf-8")
+ opened = _record_opens(monkeypatch)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await routes.open_terminal_target(
+ _request(),
+ routes.OpenTerminalTargetRequest(workspace_id="workspace-1", target=printed),
+ )
+
+ assert excinfo.value.status_code == 404
+ assert opened == []
+
+
+async def test_an_unknown_workspace_is_not_resolved_against_the_front_one(
+ workspace: Path,
+) -> None:
+ with pytest.raises(HTTPException) as excinfo:
+ await routes.open_terminal_target(
+ _request(),
+ routes.OpenTerminalTargetRequest(workspace_id="gone", target=str(workspace)),
+ )
+
+ assert excinfo.value.status_code == 404
+
+
+async def test_remote_and_headless_callers_cannot_launch_native_paths(
+ workspace: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: False)
+
+ with pytest.raises(HTTPException) as remote:
+ await routes.open_terminal_target(
+ _request(),
+ routes.OpenTerminalTargetRequest(workspace_id="workspace-1", target=str(workspace)),
+ )
+ assert remote.value.status_code == 403
+
+ monkeypatch.setattr(routes, "is_loopback_request", lambda _scope: True)
+ with pytest.raises(HTTPException) as headless:
+ await routes.open_terminal_target(
+ _request(native=False),
+ routes.OpenTerminalTargetRequest(workspace_id="workspace-1", target=str(workspace)),
+ )
+ assert headless.value.status_code == 404