Repository navigation
feat: embed OpenCode web UI in worker detail view #314
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
929c6f2
e8aa3b1
4746d4f
1d54c4f
ecf9d61
75e0cc9
23f6305
a6dcd95
1da3d2c
ece2ae4
4313f6f
b8c1fc9
74a6f1f
6d5a3a6
b48a20f
e6bf1a1
1ba07e3
4c73e55
bb82385
34f92b2
5435ed7
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, ""); | ||
| } | ||
|
|
||
| const STATUS_FILTERS = ["all", "running", "done", "failed"] as const; | ||
| type StatusFilter = (typeof STATUS_FILTERS)[number]; | ||
|
|
||
|
|
@@ -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]; | ||
|
|
@@ -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]); | ||
|
|
||
|
|
@@ -339,6 +349,8 @@ function WorkerCard({ | |
| ); | ||
| } | ||
|
|
||
| type DetailTab = "opencode" | "transcript"; | ||
|
|
||
| function WorkerDetail({ | ||
| detail, | ||
| liveWorker, | ||
|
|
@@ -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); | ||
|
|
@@ -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"> | ||
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. OpenCode embed requests will fail under Bearer-token API auth.
Also applies to: 607-615 🤖 Prompt for AI Agents
Comment on lines
+637
to
+647
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Ignore aborted health-check requests to avoid transient false error state. When switching workers quickly, an aborted request can still land in 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 |
||
|
|
||
| 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); | ||
|
|
||
|
|
||
| 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; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 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 15Repository: 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 10Repository: 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 2Repository: 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 3Repository: spacedriveapp/spacebot Length of output: 2507 🏁 Script executed: # Get the complete implementation of log_worker_started
sed -n '305,340p' src/conversation/history.rsRepository: 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 2Repository: 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 2Repository: spacedriveapp/spacebot Length of output: 48 Handle zero-row UPDATE race in OpenCode metadata persistence. Both Suggested fix: check 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 🤖 Prompt for AI Agents |
||
| _ => {} | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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(); | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not fall back to filesystem root when home dir is unavailable. Returning 🔧 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
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| #[cfg(test)] | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| mod tests { | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| use super::{WorkerCompletionError, map_worker_completion_result, spawn_worker_task}; | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: spacedriveapp/spacebot
Length of output: 93
🏁 Script executed:
Repository: spacedriveapp/spacebot
Length of output: 2213
🏁 Script executed:
Repository: spacedriveapp/spacebot
Length of output: 250
🏁 Script executed:
Repository: spacedriveapp/spacebot
Length of output: 633
Remove
base64UrlEncodeto unblock CI.The function is declared but never called, triggering TS6133 in the
interface/tsconfig.jsonwherenoUnusedLocalsis enabled. CI will fail until this is removed.Fix
📝 Committable suggestion
🧰 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