Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
929c6f2
fix: expand tilde in OpenCode worker directory paths
jamiepine Mar 4, 2026
e8aa3b1
merge: resolve conflict with main, keep both expand_tilde and tests
jamiepine Mar 4, 2026
4746d4f
feat: embed OpenCode web UI in worker detail view
jamiepine Mar 4, 2026
1d54c4f
fix: resolve clippy warning in opencode proxy error mapping
jamiepine Mar 4, 2026
ecf9d61
fix: export base64UrlEncode to resolve unused declaration TS error
jamiepine Mar 4, 2026
75e0cc9
Merge branch 'main' into feat/opencode-web-embed
jamiepine Mar 5, 2026
23f6305
fix: inject base href and SDK URL override into proxied OpenCode HTML
jamiepine Mar 5, 2026
a6dcd95
fix: deliver interactive OpenCode worker results without waiting for …
jamiepine Mar 5, 2026
1da3d2c
fix: enrich OpenCode worker status messages with tool context
jamiepine Mar 5, 2026
ece2ae4
fix: accumulate full OpenCode output and persist transcript
jamiepine Mar 5, 2026
4313f6f
feat: real-time OpenCode transcript mirroring via SSE
jamiepine Mar 5, 2026
b8c1fc9
feat: add worker idle state for interactive workers
jamiepine Mar 5, 2026
74a6f1f
fix: persist OpenCode transcript via SSE fallback when get_messages()…
jamiepine Mar 5, 2026
6d5a3a6
Merge branch 'main' into feat/opencode-web-embed
jamiepine Mar 5, 2026
b48a20f
fix: handle new ProcessEvent variants in exhaustive matches after mai…
jamiepine Mar 5, 2026
e6bf1a1
Merge branch 'main' into feat/opencode-web-embed
jamiepine Mar 5, 2026
1ba07e3
Merge branch 'main' into feat/opencode-web-embed
jamiepine Mar 5, 2026
4c73e55
fix: cortex supervisor exempts idle workers from timeout
jamiepine Mar 5, 2026
bb82385
feat: thread interactive flag through full stack and differentiate op…
jamiepine Mar 5, 2026
34f92b2
Merge branch 'main' into feat/opencode-web-embed
jamiepine Mar 6, 2026
5435ed7
fix: emit WorkerInitialResult on interactive follow-up completions
jamiepine Mar 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions interface/src/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ export interface WorkerRunInfo {
has_transcript: boolean;
live_status: string | null;
tool_calls: number;
opencode_port: number | null;
}

export interface WorkerDetailResponse {
Expand All @@ -242,6 +243,8 @@ export interface WorkerDetailResponse {
completed_at: string | null;
transcript: TranscriptStep[] | null;
tool_calls: number;
opencode_session_id: string | null;
opencode_port: number | null;
}

export interface WorkerListResponse {
Expand Down
214 changes: 166 additions & 48 deletions interface/src/routes/AgentWorkers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ import {LiveDuration} from "@/components/LiveDuration";
import {useLiveContext} from "@/hooks/useLiveContext";
import {cx} from "@/ui/utils";

/** RFC 4648 base64url encoding (no padding), matching OpenCode's directory encoding. */
export function base64UrlEncode(value: string): string {
const bytes = new TextEncoder().encode(value);
const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join("");
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
Comment on lines +20 to +25

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify call sites for base64UrlEncode in TS/TSX files
rg -nP --type=ts --type=tsx '\bbase64UrlEncode\s*\('

Repository: spacedriveapp/spacebot

Length of output: 93


🏁 Script executed:

#!/bin/bash
# Search for base64UrlEncode usage more broadly
rg 'base64UrlEncode' --type=js interface/

# Also check the actual file
echo "=== File content ==="
cat -n interface/src/routes/AgentWorkers.tsx | head -50

Repository: spacedriveapp/spacebot

Length of output: 2213


🏁 Script executed:

#!/bin/bash
# Search entire repo for base64UrlEncode
rg 'base64UrlEncode' .

# Also check if there are TypeScript errors being reported
echo "=== Checking for tsconfig and eslint config ==="
find . -maxdepth 2 -name "tsconfig.json" -o -name ".eslintrc*" -o -name "eslint.config.*" | head -10

Repository: spacedriveapp/spacebot

Length of output: 250


🏁 Script executed:

#!/bin/bash
# Check tsconfig for unused variable checking
cat ./interface/tsconfig.json

Repository: spacedriveapp/spacebot

Length of output: 633


Remove base64UrlEncode to unblock CI.

The function is declared but never called, triggering TS6133 in the interface/tsconfig.json where noUnusedLocals is enabled. CI will fail until this is removed.

Fix
-/** RFC 4648 base64url encoding (no padding), matching OpenCode's directory encoding. */
-function base64UrlEncode(value: string): string {
-	const bytes = new TextEncoder().encode(value);
-	const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join("");
-	return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
-}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/** RFC 4648 base64url encoding (no padding), matching OpenCode's directory encoding. */
function base64UrlEncode(value: string): string {
const bytes = new TextEncoder().encode(value);
const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join("");
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
🧰 Tools
🪛 GitHub Actions: Interface CI

[error] 20-20: TS6133: 'base64UrlEncode' is declared but its value is never read. Command 'bunx tsc --noEmit' exited with code 2.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@interface/src/routes/AgentWorkers.tsx` around lines 19 - 24, Remove the
unused function base64UrlEncode from AgentWorkers.tsx to satisfy the
noUnusedLocals rule: locate the declaration of function base64UrlEncode (the RFC
4648 base64url encoder) and delete the entire function definition and its
comment since it is never referenced; if you believe encoding is needed later,
alternatively export it from a util module and import where used, but do not
leave an unused local function in this file.


const STATUS_FILTERS = ["all", "running", "done", "failed"] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];

Expand Down Expand Up @@ -139,6 +146,7 @@ export function AgentWorkers({agentId}: {agentId: string}) {
has_transcript: false,
live_status: live.status,
tool_calls: live.toolCalls,
opencode_port: null,
}));

return [...synthetic, ...merged];
Expand Down Expand Up @@ -177,6 +185,8 @@ export function AgentWorkers({agentId}: {agentId: string}) {
completed_at: null,
transcript: null,
tool_calls: live.toolCalls,
opencode_session_id: null,
opencode_port: null,
};
}, [detailData, scopedActiveWorkers, selectedWorkerId]);

Expand Down Expand Up @@ -339,6 +349,8 @@ function WorkerCard({
);
}

type DetailTab = "opencode" | "transcript";

function WorkerDetail({
detail,
liveWorker,
Expand All @@ -353,6 +365,21 @@ function WorkerDetail({
const displayStatus = liveWorker?.status;
const currentTool = liveWorker?.currentTool;
const toolCalls = liveWorker?.toolCalls ?? detail.tool_calls ?? 0;

const hasOpenCodeEmbed =
detail.worker_type === "opencode" &&
detail.opencode_port != null &&
detail.opencode_session_id != null;

const [activeTab, setActiveTab] = useState<DetailTab>(
hasOpenCodeEmbed ? "opencode" : "transcript",
);

// Reset tab when switching workers
useEffect(() => {
setActiveTab(hasOpenCodeEmbed ? "opencode" : "transcript");
}, [detail.id, hasOpenCodeEmbed]);

// Use persisted transcript if available, otherwise fall back to live SSE transcript.
// Strip the final action step if it duplicates the result text shown above.
const rawTranscript = detail.transcript ?? (isRunning ? liveTranscript : null);
Expand All @@ -373,10 +400,10 @@ function WorkerDetail({

// Auto-scroll to latest transcript step for running workers
useEffect(() => {
if (isRunning && transcriptRef.current) {
if (isRunning && activeTab === "transcript" && transcriptRef.current) {
transcriptRef.current.scrollTop = transcriptRef.current.scrollHeight;
}
}, [isRunning, transcript?.length]);
}, [isRunning, activeTab, transcript?.length]);

return (
<div className="flex h-full flex-col">
Expand Down Expand Up @@ -444,60 +471,151 @@ function WorkerDetail({
)}
</div>

{/* Tab bar (only for OpenCode workers with embed data) */}
{hasOpenCodeEmbed && (
<div className="flex border-b border-app-line/50">
<button
onClick={() => setActiveTab("opencode")}
className={cx(
"px-4 py-2 text-xs font-medium transition-colors",
activeTab === "opencode"
? "border-b-2 border-accent text-accent"
: "text-ink-faint hover:text-ink-dull",
)}
>
OpenCode
</button>
<button
onClick={() => setActiveTab("transcript")}
className={cx(
"px-4 py-2 text-xs font-medium transition-colors",
activeTab === "transcript"
? "border-b-2 border-accent text-accent"
: "text-ink-faint hover:text-ink-dull",
)}
>
Transcript
</button>
</div>
)}

{/* Content */}
<div ref={transcriptRef} className="flex-1 overflow-y-auto">
{/* Result section */}
{detail.result && (
<div className="border-b border-app-line/30 px-6 py-4">
<h3 className="mb-2 text-tiny font-medium uppercase tracking-wider text-ink-faint">
Result
</h3>
<div className="text-xs text-ink">
<Markdown>{detail.result}</Markdown>
{activeTab === "opencode" && hasOpenCodeEmbed ? (
<OpenCodeEmbed
port={detail.opencode_port!}
sessionId={detail.opencode_session_id!}
/>
) : (
<div ref={transcriptRef} className="flex-1 overflow-y-auto">
{/* Result section */}
{detail.result && (
<div className="border-b border-app-line/30 px-6 py-4">
<h3 className="mb-2 text-tiny font-medium uppercase tracking-wider text-ink-faint">
Result
</h3>
<div className="text-xs text-ink">
<Markdown>{detail.result}</Markdown>
</div>
</div>
</div>
)}
)}

{/* Transcript section */}
{transcript && transcript.length > 0 ? (
<div className="px-6 py-4">
<h3 className="mb-3 text-tiny font-medium uppercase tracking-wider text-ink-faint">
{isRunning ? "Live Transcript" : "Transcript"}
</h3>
<div className="flex flex-col gap-3">
{transcript.map((step, index) => (
<motion.div
key={`${step.type}-${index}`}
initial={{opacity: 0, y: 6}}
animate={{opacity: 1, y: 0}}
transition={{duration: 0.2, ease: "easeOut"}}
>
<TranscriptStepView step={step} />
</motion.div>
))}
{isRunning && currentTool && (
<div className="flex items-center gap-2 py-2 text-tiny text-accent">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-accent" />
Running {currentTool}...
</div>
)}
{/* Transcript section */}
{transcript && transcript.length > 0 ? (
<div className="px-6 py-4">
<h3 className="mb-3 text-tiny font-medium uppercase tracking-wider text-ink-faint">
{isRunning ? "Live Transcript" : "Transcript"}
</h3>
<div className="flex flex-col gap-3">
{transcript.map((step, index) => (
<motion.div
key={`${step.type}-${index}`}
initial={{opacity: 0, y: 6}}
animate={{opacity: 1, y: 0}}
transition={{duration: 0.2, ease: "easeOut"}}
>
<TranscriptStepView step={step} />
</motion.div>
))}
{isRunning && currentTool && (
<div className="flex items-center gap-2 py-2 text-tiny text-accent">
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-accent" />
Running {currentTool}...
</div>
)}
</div>
</div>
</div>
) : isRunning ? (
<div className="flex flex-col items-center justify-center gap-2 py-12 text-ink-faint">
<div className="h-2 w-2 animate-pulse rounded-full bg-amber-500" />
<p className="text-xs">Waiting for first tool call...</p>
</div>
) : (
<div className="px-6 py-8 text-center text-xs text-ink-faint">
Full transcript not available for this worker
</div>
)}
</div>
) : isRunning ? (
<div className="flex flex-col items-center justify-center gap-2 py-12 text-ink-faint">
<div className="h-2 w-2 animate-pulse rounded-full bg-amber-500" />
<p className="text-xs">Waiting for first tool call...</p>
</div>
) : (
<div className="px-6 py-8 text-center text-xs text-ink-faint">
Full transcript not available for this worker
</div>
)}
</div>
)}
</div>
);
}

function OpenCodeEmbed({port, sessionId}: {port: number; sessionId: string}) {
const [state, setState] = useState<"loading" | "ready" | "error">("loading");

useEffect(() => {
setState("loading");
const controller = new AbortController();

fetch(`/api/opencode/${port}/global/health`, {signal: controller.signal})
.then((response) => {
setState(response.ok ? "ready" : "error");
})
.catch(() => {
setState("error");
});
Comment on lines +641 to +647

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

OpenCode embed requests will fail under Bearer-token API auth.

src/api/server.rs Line 276-281 enforces Authorization: Bearer ... for /api/*. Here, Line 570 uses plain fetch without auth headers, and the iframe request (Line 611) cannot send Bearer headers, so secured deployments will return 401.

Also applies to: 607-615

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@interface/src/routes/AgentWorkers.tsx` around lines 570 - 576, The
health-check fetch and the iframe embed in AgentWorkers.tsx are failing under
Bearer-token API auth because they call /api/opencode/... directly (the fetch at
the block that sets setState and the iframe src around lines ~607-615) without
an Authorization header and iframes cannot set Bearer headers; fix by routing
these requests through a backend proxy endpoint that attaches the server-side
Bearer token (or returns a tokenized/self-authenticating URL): implement a new
server route (e.g., GET /internal/proxy/opencode/:port/global/health and GET
/internal/proxy/opencode/:port/embed) which performs server-side fetch to
/api/opencode/:port/... with the required Authorization header and returns the
response (or the embed HTML/URL), then update the fetch in AgentWorkers.tsx to
call the new proxy health endpoint and change the iframe src to the proxy embed
URL so auth is applied server-side.

Comment on lines +637 to +647

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Ignore aborted health-check requests to avoid transient false error state.

When switching workers quickly, an aborted request can still land in catch and set "error", causing a flicker before the next request resolves.

Suggested fix
 useEffect(() => {
   setState("loading");
   const controller = new AbortController();

   fetch(`/api/opencode/${port}/global/health`, {signal: controller.signal})
     .then((response) => {
-      setState(response.ok ? "ready" : "error");
+      if (!controller.signal.aborted) {
+        setState(response.ok ? "ready" : "error");
+      }
     })
-    .catch(() => {
-      setState("error");
+    .catch((error) => {
+      if (error?.name === "AbortError" || controller.signal.aborted) return;
+      setState("error");
     });

   return () => controller.abort();
 }, [port, sessionId]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@interface/src/routes/AgentWorkers.tsx` around lines 566 - 576, The
health-check useEffect should ignore aborted fetches to avoid transient "error"
state: in the catch handler for the fetch to
`/api/opencode/${port}/global/health` (inside the useEffect in AgentWorkers.tsx)
check whether the thrown error is an abort (e.g., error.name === 'AbortError' or
controller.signal.aborted) and if so do nothing, otherwise call
setState("error"); also ensure the effect returns a cleanup that calls
controller.abort() so stale requests are cancelled when port/worker changes. Use
the existing AbortController, setState, and fetch call sites to implement this
change.


return () => controller.abort();
}, [port, sessionId]);

if (state === "loading") {
return (
<div className="flex flex-1 items-center justify-center">
<div className="flex items-center gap-2 text-xs text-ink-faint">
<span className="h-2 w-2 animate-pulse rounded-full bg-accent" />
Connecting to OpenCode...
</div>
</div>
);
}

if (state === "error") {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-2 text-ink-faint">
<p className="text-xs">OpenCode server is not reachable</p>
<p className="text-tiny">
The server may have been stopped. Try the Transcript tab for available data.
</p>
</div>
);
}

// Build the iframe URL. OpenCode uses base64url-encoded directory paths
// in its SPA routing. We load the root and let the app navigate — the
// server knows its directory, and the session list will show this session.
// Direct deep-linking: /api/opencode/{port}/{base64dir}/session/{sessionId}
const iframeSrc = `/api/opencode/${port}/`;

return (
<iframe
src={iframeSrc}
className="h-full w-full flex-1 border-0"
title="OpenCode"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
);
}

function TaskText({text}: {text: string}) {
const [expanded, setExpanded] = useState(false);

Expand Down
5 changes: 5 additions & 0 deletions migrations/20260303000001_opencode_worker_metadata.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- OpenCode worker metadata for embedded web UI.
-- Stores the session ID and server port so the frontend can construct
-- an iframe URL to the OpenCode web UI for a given worker run.
ALTER TABLE worker_runs ADD COLUMN opencode_session_id TEXT;
ALTER TABLE worker_runs ADD COLUMN opencode_port INTEGER;
8 changes: 8 additions & 0 deletions src/agent/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1574,6 +1574,14 @@ impl Channel {

tracing::info!(worker_id = %worker_id, "worker completed, result queued for retrigger");
}
ProcessEvent::OpenCodeSessionCreated {
worker_id,
session_id,
port,
..
} => {
run_logger.log_opencode_metadata(*worker_id, session_id, *port);
}
Comment on lines +2302 to +2309

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Find and examine the logger implementation for both functions
rg -n "fn log_worker_started|fn log_opencode_metadata" src/conversation/history.rs -A 15

Repository: spacedriveapp/spacebot

Length of output: 1360


🏁 Script executed:

# Examine the ProcessEvent handler context to understand sequencing
rg -n "ProcessEvent::OpenCodeSessionCreated|ProcessEvent::WorkerStarted" src/agent/channel.rs -B 5 -A 10

Repository: spacedriveapp/spacebot

Length of output: 1188


🏁 Script executed:

# Check how these logger methods are called in the worker lifecycle
rg -n "log_worker_started|log_opencode_metadata" src/agent/channel.rs -B 3 -A 2

Repository: spacedriveapp/spacebot

Length of output: 490


🏁 Script executed:

# Look for worker_runs table schema and insert/update patterns
rg -n "INSERT INTO worker_runs|UPDATE worker_runs" src/ -C 3

Repository: spacedriveapp/spacebot

Length of output: 2507


🏁 Script executed:

# Get the complete implementation of log_worker_started
sed -n '305,340p' src/conversation/history.rs

Repository: spacedriveapp/spacebot

Length of output: 1308


🏁 Script executed:

# Check if there's explicit synchronization or ordering between WorkerStarted and OpenCodeSessionCreated
rg -n "ProcessEvent::WorkerStarted|ProcessEvent::OpenCodeSessionCreated" src/ -B 2 -A 2

Repository: spacedriveapp/spacebot

Length of output: 2351


🏁 Script executed:

# Verify if sqlx returns error or rows_affected for 0-row UPDATE
rg -n "execute.*worker_runs" src/conversation/history.rs -A 2

Repository: spacedriveapp/spacebot

Length of output: 48


Handle zero-row UPDATE race in OpenCode metadata persistence.

Both log_worker_started (INSERT) and log_opencode_metadata (UPDATE) are fire-and-forget spawned tasks with no ordering guarantee. If ProcessEvent::OpenCodeSessionCreated handler executes before the worker row is inserted, the UPDATE worker_runs ... WHERE id = ? will succeed but affect 0 rows—and the current code only logs on query errors, not on 0-rows-affected, so metadata is silently lost.

Suggested fix: check rows_affected() in log_opencode_metadata and either retry, or coalesce with an upsert pattern (e.g., INSERT OR REPLACE ... ON CONFLICT UPDATE ...).

Per coding guidelines, async/stateful paths like worker lifecycle must include explicit race/terminal-state reasoning in the PR summary and run targeted tests beyond just gate-pr.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/agent/channel.rs` around lines 1577 - 1584, The OpenCode metadata UPDATE
can silently affect 0 rows if the INSERT from log_worker_started hasn't
completed; in log_opencode_metadata check the query result's rows_affected() and
handle 0-rows cases by either retrying a small number of times with backoff or
switching to an upsert (INSERT ... ON CONFLICT DO UPDATE / INSERT OR REPLACE) so
metadata isn't lost; update the ProcessEvent::OpenCodeSessionCreated handling
notes and add test(s) for the race between log_worker_started and
log_opencode_metadata to document the terminal-state reasoning per guidelines.

_ => {}
}

Expand Down
20 changes: 19 additions & 1 deletion src/agent/channel_dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ pub async fn spawn_opencode_worker_from_state(
check_worker_limit(state).await?;
ensure_dispatch_readiness(state, "opencode_worker");
let task = task.into();
let directory = std::path::PathBuf::from(directory);
let directory = expand_tilde(directory);

let rc = &state.deps.runtime_config;
let prompt_engine = rc.prompts.load();
Expand Down Expand Up @@ -679,6 +679,24 @@ where
})
}

/// Expand a leading `~` or `~/` in a path to the user's home directory.
///
/// LLMs consistently produce tilde-prefixed paths because that's what appears
/// in conversation context. `std::path::Path::canonicalize()` doesn't expand
/// tildes (that's a shell feature), so paths like `~/Projects/foo` fail with
/// "directory does not exist". This handles the common cases.
fn expand_tilde(path: &str) -> std::path::PathBuf {
if path == "~" {
dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("/"))
} else if let Some(rest) = path.strip_prefix("~/") {
dirs::home_dir()
.unwrap_or_else(|| std::path::PathBuf::from("/"))
.join(rest)
} else {
std::path::PathBuf::from(path)
}
}
Comment on lines +707 to +723

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Do not fall back to filesystem root when home dir is unavailable.

Returning / for ~/~/... can run OpenCode against an unintended directory. Preserve the original path when home directory cannot be resolved.

🔧 Proposed fix
 fn expand_tilde(path: &str) -> std::path::PathBuf {
     if path == "~" {
-        dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("/"))
+        dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(path))
     } else if let Some(rest) = path.strip_prefix("~/") {
         dirs::home_dir()
-            .unwrap_or_else(|| std::path::PathBuf::from("/"))
-            .join(rest)
+            .map(|home| home.join(rest))
+            .unwrap_or_else(|| std::path::PathBuf::from(path))
     } else {
         std::path::PathBuf::from(path)
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/// Expand a leading `~` or `~/` in a path to the user's home directory.
///
/// LLMs consistently produce tilde-prefixed paths because that's what appears
/// in conversation context. `std::path::Path::canonicalize()` doesn't expand
/// tildes (that's a shell feature), so paths like `~/Projects/foo` fail with
/// "directory does not exist". This handles the common cases.
fn expand_tilde(path: &str) -> std::path::PathBuf {
if path == "~" {
dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("/"))
} else if let Some(rest) = path.strip_prefix("~/") {
dirs::home_dir()
.unwrap_or_else(|| std::path::PathBuf::from("/"))
.join(rest)
} else {
std::path::PathBuf::from(path)
}
}
/// Expand a leading `~` or `~/` in a path to the user's home directory.
///
/// LLMs consistently produce tilde-prefixed paths because that's what appears
/// in conversation context. `std::path::Path::canonicalize()` doesn't expand
/// tildes (that's a shell feature), so paths like `~/Projects/foo` fail with
/// "directory does not exist". This handles the common cases.
fn expand_tilde(path: &str) -> std::path::PathBuf {
if path == "~" {
dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from(path))
} else if let Some(rest) = path.strip_prefix("~/") {
dirs::home_dir()
.map(|home| home.join(rest))
.unwrap_or_else(|| std::path::PathBuf::from(path))
} else {
std::path::PathBuf::from(path)
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/agent/channel_dispatch.rs` around lines 666 - 682, The expand_tilde
function currently falls back to filesystem root when dirs::home_dir() returns
None; change it so that if the home directory cannot be resolved you preserve
and return the original path instead of "/" — i.e., in the "~" case and the
"~/..." case, only join with the resolved home_dir when dirs::home_dir() returns
Some(dir), otherwise return std::path::PathBuf::from(path). Update the logic in
expand_tilde to check dirs::home_dir() and fall back to PathBuf::from(path)
rather than PathBuf::from("/") to avoid operating on the filesystem root.


#[cfg(test)]
mod tests {
use super::{WorkerCompletionError, map_worker_completion_result, spawn_worker_task};
Expand Down
1 change: 1 addition & 0 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod mcp;
mod memories;
mod messaging;
mod models;
mod opencode_proxy;
mod providers;
mod secrets;
mod server;
Expand Down
Loading
Loading