Decouple bundled UI from runtime API and add remote instance tooling (#1228)
Add a packaged-client runtime boundary so the shared UI can talk to local, desktop, remote, and VS Code runtimes through the right transport instead of assuming one same-origin web server. Centralize OpenChamber-owned API access behind RuntimeAPIs, runtimeFetch, and runtime URL helpers, while keeping official OpenCode traffic on the SDK path. Support runtime switching, remote host selection, desktop client credentials, and headless connection links for pairing packaged clients with remote OpenChamber servers. Harden the new auth model by moving long-lived client tokens out of browser URLs, introducing short-lived scoped URL tokens for browser-owned transports, restricting URL-token access to explicit readable/realtime routes, and making client-token management session-scoped or self-scoped as appropriate. Update browser-owned assets and preview proxy flows to work with the split runtime model, including authenticated project icons, preview token propagation, CSP-safe preview bridge injection, and preview proxy auth that survives short-lived URL-token expiry. Tighten Electron security boundaries for packaged clients by gating privileged preload state to trusted origins and requiring explicit confirmation before connect deep-links import or switch remote runtimes. Also refresh agent guidance and project skills so future runtime/API, auth, preview, UI, CLI, settings, locale, and drag-to-reorder work follows the new architecture.
This commit is contained in:
committed by
GitHub
parent
a4314c189b
commit
2031e3b4a8
@@ -17,6 +17,7 @@ import type { Session, Part, Message, TextPart } from "@opencode-ai/sdk/v2/clien
|
||||
import type { AttachedFile, SessionContextUsage, SessionWorktreeAttachment } from "@/stores/types/sessionTypes"
|
||||
import type { WorktreeMetadata } from "@/types/worktree"
|
||||
import { opencodeClient } from "@/lib/opencode/client"
|
||||
import { runtimeFetch } from "@/lib/runtime-fetch"
|
||||
import { useConfigStore } from "@/stores/useConfigStore"
|
||||
import { useProjectsStore } from "@/stores/useProjectsStore"
|
||||
import { useGlobalSessionsStore, resolveGlobalSessionDirectory } from "@/stores/useGlobalSessionsStore"
|
||||
@@ -48,12 +49,18 @@ import {
|
||||
unshareSession as unshareSessionAction,
|
||||
optimisticSend,
|
||||
refetchSessionMessages,
|
||||
revertToMessage as revertToMessageAction,
|
||||
unrevertSession as unrevertSessionAction,
|
||||
forkFromMessage as forkFromMessageAction,
|
||||
} from "./session-actions"
|
||||
import { useInputStore, type SyntheticContextPart } from "./input-store"
|
||||
import { useSelectionStore } from "./selection-store"
|
||||
import { useViewportStore } from "./viewport-store"
|
||||
import { getViewportSessionMemory, useViewportStore, viewportSessionKey } from "./viewport-store"
|
||||
import { useSessionWorktreeStore } from "./session-worktree-store"
|
||||
import { getAttachedSessionDirectory } from "./session-worktree-contract"
|
||||
import { setSessionOpener } from "./session-navigation"
|
||||
import { getRuntimeKey } from "@/lib/runtime-switch"
|
||||
import { rememberRuntimeLiveStatus } from "./runtime-live-memory"
|
||||
|
||||
export type { AttachedFile }
|
||||
|
||||
@@ -74,82 +81,75 @@ export function routeMessage(params: {
|
||||
files?: Array<{ type: "file"; mime: string; url: string; filename: string }>
|
||||
additionalParts?: Array<{ text: string; synthetic?: boolean; files?: Array<{ type: "file"; mime: string; url: string; filename: string }> }>
|
||||
}): Promise<void> {
|
||||
const run = (): Promise<void> => {
|
||||
if (params.inputMode === "shell") {
|
||||
const sdk = opencodeClient.getSdkClient()
|
||||
const dir = opencodeClient.getDirectory() || undefined
|
||||
return sdk.session.shell({
|
||||
sessionID: params.sessionId,
|
||||
directory: dir,
|
||||
agent: params.agent,
|
||||
model: { providerID: params.providerID, modelID: params.modelID },
|
||||
command: params.content,
|
||||
}).then(() => {})
|
||||
}
|
||||
|
||||
// Slash commands — fire and forget, SSE delivers messages and status
|
||||
if (params.content.startsWith("/")) {
|
||||
const [head, ...tail] = params.content.split(" ")
|
||||
const cmdName = head.slice(1)
|
||||
|
||||
const dirState = getDirectoryState(params.directory ?? undefined)
|
||||
const syncCommands = dirState?.command ?? []
|
||||
const storeCommands = useCommandsStore.getState().commands
|
||||
|
||||
const isCommand = syncCommands.find((c) => c.name === cmdName)
|
||||
|| storeCommands.find((c) => c.name === cmdName)
|
||||
|
||||
if (isCommand) {
|
||||
return optimisticSend({
|
||||
sessionId: params.sessionId,
|
||||
content: params.content,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
agent: params.agent,
|
||||
files: params.files,
|
||||
send: (messageID) => opencodeClient.sendCommand({
|
||||
id: params.sessionId,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
command: cmdName,
|
||||
arguments: tail.join(" "),
|
||||
agent: params.agent,
|
||||
variant: params.variant,
|
||||
files: params.files,
|
||||
messageId: messageID,
|
||||
}).then(() => {}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Normal prompt — optimistic insert so message appears instantly
|
||||
return optimisticSend({
|
||||
const requestDirectory = params.directory ?? undefined
|
||||
if (params.inputMode === "shell") {
|
||||
return opencodeClient.shellSession({
|
||||
sessionId: params.sessionId,
|
||||
content: params.content,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
agent: params.agent,
|
||||
files: params.files,
|
||||
send: (messageID) => opencodeClient.sendMessage({
|
||||
id: params.sessionId,
|
||||
directory: requestDirectory,
|
||||
agent: params.agent ?? "",
|
||||
model: { providerID: params.providerID, modelID: params.modelID },
|
||||
command: params.content,
|
||||
}).then(() => undefined)
|
||||
}
|
||||
|
||||
// Slash commands — fire and forget, SSE delivers messages and status
|
||||
if (params.content.startsWith("/")) {
|
||||
const [head, ...tail] = params.content.split(" ")
|
||||
const cmdName = head.slice(1)
|
||||
|
||||
const dirState = getDirectoryState(requestDirectory)
|
||||
const syncCommands = dirState?.command ?? []
|
||||
const storeCommands = useCommandsStore.getState().commands
|
||||
|
||||
const isCommand = syncCommands.find((c) => c.name === cmdName)
|
||||
|| storeCommands.find((c) => c.name === cmdName)
|
||||
|
||||
if (isCommand) {
|
||||
return optimisticSend({
|
||||
sessionId: params.sessionId,
|
||||
content: params.content,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
text: params.content,
|
||||
agent: params.agent,
|
||||
agentMentions: params.agentMentionName ? [{ name: params.agentMentionName }] : undefined,
|
||||
variant: params.variant,
|
||||
files: params.files,
|
||||
additionalParts: params.additionalParts,
|
||||
messageId: messageID,
|
||||
}).then(() => {}),
|
||||
})
|
||||
send: (messageID) => opencodeClient.sendCommand({
|
||||
id: params.sessionId,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
command: cmdName,
|
||||
arguments: tail.join(" "),
|
||||
agent: params.agent,
|
||||
variant: params.variant,
|
||||
files: params.files,
|
||||
messageId: messageID,
|
||||
directory: requestDirectory,
|
||||
}).then(() => {}),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (params.directory !== undefined) {
|
||||
return opencodeClient.withDirectory(params.directory, run)
|
||||
}
|
||||
|
||||
return run()
|
||||
// Normal prompt — optimistic insert so message appears instantly
|
||||
return optimisticSend({
|
||||
sessionId: params.sessionId,
|
||||
content: params.content,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
agent: params.agent,
|
||||
files: params.files,
|
||||
send: (messageID) => opencodeClient.sendMessage({
|
||||
id: params.sessionId,
|
||||
providerID: params.providerID,
|
||||
modelID: params.modelID,
|
||||
text: params.content,
|
||||
agent: params.agent,
|
||||
agentMentions: params.agentMentionName ? [{ name: params.agentMentionName }] : undefined,
|
||||
variant: params.variant,
|
||||
files: params.files,
|
||||
additionalParts: params.additionalParts,
|
||||
messageId: messageID,
|
||||
directory: requestDirectory,
|
||||
}).then(() => {}),
|
||||
})
|
||||
}
|
||||
|
||||
type SendMessageOptions = {
|
||||
@@ -157,7 +157,7 @@ type SendMessageOptions = {
|
||||
}
|
||||
|
||||
function notifyMessageSent(sessionId: string): void {
|
||||
fetch(`/api/sessions/${sessionId}/message-sent`, { method: "POST" })
|
||||
runtimeFetch(`/api/sessions/${sessionId}/message-sent`, { method: "POST" })
|
||||
.catch(() => { /* ignore */ })
|
||||
}
|
||||
|
||||
@@ -222,6 +222,8 @@ export type SessionUIState = {
|
||||
|
||||
// Actions — UI state management
|
||||
setCurrentSession: (id: string | null, directoryHint?: string | null) => void
|
||||
prepareForRuntimeSwitch: (apiBaseUrl?: string | null) => void
|
||||
restoreForRuntimeSwitch: (apiBaseUrl?: string | null) => void
|
||||
openNewSessionDraft: (options?: Partial<NewSessionDraftState>) => void
|
||||
closeNewSessionDraft: () => void
|
||||
setNewSessionDraftTarget: (target: { projectId?: string | null; selectedProjectId?: string | null; directoryOverride?: string | null }, options?: { force?: boolean }) => void
|
||||
@@ -358,6 +360,31 @@ const DEFAULT_DRAFT: NewSessionDraftState = {
|
||||
parentID: null,
|
||||
}
|
||||
|
||||
const activeSessionByRuntime = new Map<string, string | null>()
|
||||
type RuntimeSessionMemory = {
|
||||
sessionId: string | null
|
||||
directory: string | null
|
||||
draft: NewSessionDraftState
|
||||
}
|
||||
const runtimeSessionMemory = new Map<string, RuntimeSessionMemory>()
|
||||
|
||||
const runtimeMemoryKey = (value?: string | null): string => {
|
||||
const key = (value ?? getRuntimeKey()).trim()
|
||||
return key || "default"
|
||||
}
|
||||
|
||||
const cloneDraft = (draft: NewSessionDraftState): NewSessionDraftState => ({ ...draft })
|
||||
|
||||
const writeRuntimeSessionMemory = (key: string, patch: Partial<RuntimeSessionMemory>): void => {
|
||||
const current = runtimeSessionMemory.get(key)
|
||||
runtimeSessionMemory.set(key, {
|
||||
sessionId: current?.sessionId ?? null,
|
||||
directory: current?.directory ?? null,
|
||||
draft: current?.draft ? cloneDraft(current.draft) : { ...DEFAULT_DRAFT },
|
||||
...patch,
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Store
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -387,6 +414,9 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
get().closeNewSessionDraft()
|
||||
}
|
||||
|
||||
const key = runtimeMemoryKey()
|
||||
activeSessionByRuntime.set(key, id)
|
||||
|
||||
const previousSessionId = get().currentSessionId
|
||||
|
||||
// Set currentSessionId immediately so the skeleton renders without delay.
|
||||
@@ -400,6 +430,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
)
|
||||
const fallbackDir = opencodeClient.getDirectory() ?? directoryState.currentDirectory ?? null
|
||||
const resolvedDir = (directoryHint ? normalizePath(directoryHint) : null) ?? sessionDir ?? fallbackDir
|
||||
writeRuntimeSessionMemory(key, { sessionId: id, directory: resolvedDir ?? null })
|
||||
|
||||
try {
|
||||
if (resolvedDir && directoryState.currentDirectory !== resolvedDir) {
|
||||
@@ -415,7 +446,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
if (previousSessionId && previousSessionId !== id) {
|
||||
const prevId = previousSessionId
|
||||
setTimeout(() => {
|
||||
const memState = useViewportStore.getState().sessionMemoryState.get(prevId)
|
||||
const memState = getViewportSessionMemory(prevId)
|
||||
if (!memState?.isStreaming) {
|
||||
const prevMessages = getSyncMessages(prevId)
|
||||
if (prevMessages.length > 0) {
|
||||
@@ -432,6 +463,50 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
}
|
||||
},
|
||||
|
||||
prepareForRuntimeSwitch: (apiBaseUrl?: string | null) => {
|
||||
const key = runtimeMemoryKey(apiBaseUrl)
|
||||
const directory = useDirectoryStore.getState().currentDirectory || null
|
||||
const currentSessionId = get().currentSessionId
|
||||
const directorySnapshot = directory ? getDirectoryState(directory) : null
|
||||
rememberRuntimeLiveStatus({
|
||||
runtimeKey: key,
|
||||
directory,
|
||||
sessionId: currentSessionId,
|
||||
status: currentSessionId ? directorySnapshot?.session_status?.[currentSessionId] : null,
|
||||
})
|
||||
activeSessionByRuntime.set(key, get().currentSessionId)
|
||||
writeRuntimeSessionMemory(key, {
|
||||
sessionId: currentSessionId,
|
||||
directory,
|
||||
draft: cloneDraft(get().newSessionDraft),
|
||||
})
|
||||
},
|
||||
|
||||
restoreForRuntimeSwitch: (apiBaseUrl?: string | null) => {
|
||||
const key = runtimeMemoryKey(apiBaseUrl)
|
||||
const memory = runtimeSessionMemory.get(key)
|
||||
const restoredSessionId = memory?.sessionId ?? activeSessionByRuntime.get(key) ?? null
|
||||
const restoredDraft = memory?.draft ? cloneDraft(memory.draft) : { ...DEFAULT_DRAFT }
|
||||
const restoredDirectory = memory?.directory ?? null
|
||||
if (restoredDirectory) {
|
||||
useDirectoryStore.getState().setDirectory(restoredDirectory, { showOverlay: false })
|
||||
}
|
||||
set({
|
||||
currentSessionId: restoredSessionId,
|
||||
newSessionDraft: restoredSessionId ? { ...DEFAULT_DRAFT } : restoredDraft,
|
||||
abortPromptSessionId: null,
|
||||
abortPromptExpiresAt: null,
|
||||
error: null,
|
||||
sessionAbortFlags: new Map(),
|
||||
pendingChangesBarDismissed: new Map(),
|
||||
})
|
||||
if (restoredSessionId) {
|
||||
setActiveSession(opencodeClient.getDirectory() ?? "", restoredSessionId)
|
||||
} else {
|
||||
setActiveSession("", "")
|
||||
}
|
||||
},
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// openNewSessionDraft
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -481,24 +556,29 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
|
||||
persistDraftTarget({ projectId: selectedProject?.id ?? null, directory })
|
||||
|
||||
const nextDraft: NewSessionDraftState = {
|
||||
open: true,
|
||||
selectedProjectId: selectedProject?.id ?? null,
|
||||
directoryOverride: directory,
|
||||
pendingWorktreeRequestId: options?.pendingWorktreeRequestId ?? null,
|
||||
bootstrapPendingDirectory: normalizePath(options?.bootstrapPendingDirectory ?? null),
|
||||
preserveDirectoryOverride: options?.preserveDirectoryOverride === true,
|
||||
parentID: options?.parentID ?? null,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
syntheticParts: options?.syntheticParts,
|
||||
targetFolderId: options?.targetFolderId,
|
||||
}
|
||||
|
||||
set({
|
||||
newSessionDraft: {
|
||||
open: true,
|
||||
selectedProjectId: selectedProject?.id ?? null,
|
||||
directoryOverride: directory,
|
||||
pendingWorktreeRequestId: options?.pendingWorktreeRequestId ?? null,
|
||||
bootstrapPendingDirectory: normalizePath(options?.bootstrapPendingDirectory ?? null),
|
||||
preserveDirectoryOverride: options?.preserveDirectoryOverride === true,
|
||||
parentID: options?.parentID ?? null,
|
||||
title: options?.title,
|
||||
initialPrompt: options?.initialPrompt,
|
||||
syntheticParts: options?.syntheticParts,
|
||||
targetFolderId: options?.targetFolderId,
|
||||
...nextDraft,
|
||||
},
|
||||
currentSessionId: null,
|
||||
error: null,
|
||||
})
|
||||
|
||||
writeRuntimeSessionMemory(runtimeMemoryKey(), { sessionId: null, directory, draft: nextDraft })
|
||||
// Clear composer attachments when opening a new session draft.
|
||||
// Attachments from the previous session (e.g. restored by revert) must
|
||||
// not bleed into the new session's input.
|
||||
@@ -515,8 +595,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
// closeNewSessionDraft
|
||||
// ---------------------------------------------------------------------------
|
||||
closeNewSessionDraft: () => {
|
||||
set({
|
||||
newSessionDraft: {
|
||||
const nextDraft: NewSessionDraftState = {
|
||||
open: false,
|
||||
selectedProjectId: null,
|
||||
directoryOverride: null,
|
||||
@@ -528,8 +607,11 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
initialPrompt: undefined,
|
||||
syntheticParts: undefined,
|
||||
targetFolderId: undefined,
|
||||
},
|
||||
}
|
||||
set({
|
||||
newSessionDraft: nextDraft,
|
||||
})
|
||||
writeRuntimeSessionMemory(runtimeMemoryKey(), { draft: nextDraft })
|
||||
},
|
||||
|
||||
setNewSessionDraftTarget: (target) => {
|
||||
@@ -841,10 +923,10 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
|
||||
if (targetSessionId) {
|
||||
const viewportState = useViewportStore.getState()
|
||||
const memState = viewportState.sessionMemoryState.get(targetSessionId)
|
||||
const memState = getViewportSessionMemory(targetSessionId)
|
||||
if (!memState || !memState.lastUserMessageAt) {
|
||||
const newMemState = new Map(viewportState.sessionMemoryState)
|
||||
newMemState.set(targetSessionId, {
|
||||
newMemState.set(viewportSessionKey(targetSessionId), {
|
||||
viewportAnchor: 0,
|
||||
isStreaming: false,
|
||||
lastAccessedAt: Date.now(),
|
||||
@@ -980,8 +1062,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
// Ensure the complete message range is present before applying the revert
|
||||
// marker. Reverted UI is derived from session.revert + stored messages.
|
||||
await refetchSessionMessages(sessionId)
|
||||
const { revertToMessage: revert } = await import("./session-actions")
|
||||
await revert(sessionId, messageId)
|
||||
await revertToMessageAction(sessionId, messageId)
|
||||
},
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1056,8 +1137,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
return
|
||||
}
|
||||
|
||||
const { unrevertSession } = await import("./session-actions")
|
||||
await unrevertSession(sessionId)
|
||||
await unrevertSessionAction(sessionId)
|
||||
const { toast } = await import("sonner")
|
||||
const { useI18nStore, formatMessage } = await import("@/lib/i18n/store")
|
||||
const { dictionary } = useI18nStore.getState()
|
||||
@@ -1073,8 +1153,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
if (!existingSession) return
|
||||
|
||||
try {
|
||||
const { forkFromMessage: fork } = await import("./session-actions")
|
||||
await fork(sessionId, messageId)
|
||||
await forkFromMessageAction(sessionId, messageId)
|
||||
|
||||
const { toast } = await import("sonner")
|
||||
toast.success(`Forked from ${existingSession.title}`)
|
||||
@@ -1127,6 +1206,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
|
||||
if (!pID || !mID) return
|
||||
|
||||
const sessionDirectory = normalizePath(directory ?? session.directory ?? null)
|
||||
await opencodeClient.sendMessage({
|
||||
id: session.id,
|
||||
providerID: pID,
|
||||
@@ -1134,6 +1214,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
text: assistantPlanText,
|
||||
prefaceText: EXECUTION_FORK_META_TEXT,
|
||||
agent: currentAgentName ?? undefined,
|
||||
directory: sessionDirectory,
|
||||
})
|
||||
},
|
||||
|
||||
@@ -1238,3 +1319,7 @@ export const useSessionUIStore = create<SessionUIState>()((set, get) => ({
|
||||
return get().sessionPlanAvailable.get(sessionId) ?? false
|
||||
},
|
||||
}))
|
||||
|
||||
setSessionOpener((sessionID, directory) => {
|
||||
useSessionUIStore.getState().setCurrentSession(sessionID, directory)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user