feat(opencode): migrate OpenCode Manager to OpenCode 2 (#359)

* feat(opencode): migrate OpenCode Manager to OpenCode 2

Port the backend lifecycle, generated plugins, event aggregation,
schedules, worktrees, provider credentials, MCP, config handling, the
frontend chat model, and the ocm CLI to OpenCode 2.

Adopt @opencode/client 2.0.15 as the single typed V2 API contract,
require OpenCode 2.0.0 or newer (pinned 2.0.15), and delete every
V1-only code path.

* refactor(opencode): reload config in place and drop v1 compatibility shims

Route config/skill/AGENTS.md changes through the OpenCode location reload
API instead of a full server restart, stop auto-resuming interrupted
sessions, remove the restart coordinator and v1 MCP/version shims, and pin
support to OpenCode >=2.0.15 <3.0.0. Adds integration-ready retries,
service-mode launch, ocm-cli repo proxy, and new frontend form/MCP helpers.

* refactor(opencode): consolidate v2 migration helpers and harden install, proxy, and session flows

- extract shared semver and model-ref utilities, reuse across version checks
- share the OpenCode release download script across Docker, entrypoint, dev setup
- unify install/upgrade failure recovery and guard externally managed OPENCODE_BIN
- scope the repo proxy location rewrite and surface ocm proxy errors
- rework frontend session projection, permission lookup, and cache invalidation

* fix(schedules): reject unavailable agents before creating a session

* feat(opencode): add ocm install, schedule agent fallback, and session move guards
This commit is contained in:
Chris Scott authored and GitHub committed 2026-09-26 13:16:45 -04:00
1 parent 6c2ebd764b
commit dacde879d6
383 files changed
+29905 -46566

No files matched your search

+141 -515
View File
@@ -1,46 +1,40 @@
import { useQuery, useMutation, useQueryClient, useInfiniteQuery } from "@tanstack/react-query";
import { useMemo, useRef, useEffect, useCallback } from "react";
import { OpenCodeClient } from "../api/opencode";
import {
createSession,
deleteSession,
getSession,
listSessionPage,
renameSession,
activateSkill,
interruptSession,
listAgents,
runShell,
sendPrompt,
switchSessionAgent,
switchSessionModel,
type PromptAgentInput,
type PromptFileInput,
type PromptSkillInput,
} from "../api/opencode";
import { FetchError } from "../api/fetchWrapper";
import type {
Message,
Part,
ContentPart,
MessageWithParts,
} from "../api/types";
import type { paths, components } from "../api/opencode-types";
import type { ModelRef, SessionInfo } from "@opencode-manager/shared/opencode";
import { parseNetworkError, isGatewayTimeout } from "../lib/opencode-errors";
import { showToast } from "../lib/toast";
import { useSendErrorStore } from "../stores/sendErrorStore";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { invalidateSessionListCaches, messagesQueryKey } from "../lib/queryInvalidation";
import { reconcileConfirmedPrompt } from "../lib/sendErrorReconcile";
import { invalidateSessionListCaches, sessionTranscriptQueryKey } from "../lib/queryInvalidation";
import { buildSessionKey } from "../lib/sessionKey";
import { toggleSessionPin } from "../api/sessionPins";
import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
import { admitInboxItem, type TranscriptCache } from "../lib/session-projection";
import type { SessionPin } from "@opencode-manager/shared/schemas";
type AssistantMessage = components["schemas"]["AssistantMessage"];
type SendPromptRequest = NonNullable<
paths["/session/{sessionID}/prompt_async"]["post"]["requestBody"]
>["content"]["application/json"];
type SendCommandResponse = paths["/session/{sessionID}/command"]["post"]["responses"]["200"]["content"]["application/json"];
const parseModelString = (model: string) => {
const [providerID, ...rest] = model.split("/");
const modelID = rest.join("/");
if (!providerID || !modelID) return undefined;
return { providerID, modelID };
};
export const useOpenCodeClient = (opcodeUrl: string | null | undefined, directory?: string) => {
return useMemo(
() => (opcodeUrl ? new OpenCodeClient(opcodeUrl, directory) : null),
[opcodeUrl, directory],
);
};
const isSameModelRef = (left: ModelRef, right: ModelRef | undefined) =>
right !== undefined &&
left.providerID === right.providerID &&
left.id === right.id &&
left.variant === right.variant;
const SESSION_LIST_PAGE_SIZE = 25
@@ -52,7 +46,6 @@ interface UseSessionsAcrossDirectoriesOptions {
type SessionPageParam = Record<string, string>
export const useSessionsAcrossDirectories = (
opcodeUrl: string | null | undefined,
directories: string[],
options?: UseSessionsAcrossDirectoriesOptions,
) => {
@@ -65,12 +58,13 @@ export const useSessionsAcrossDirectories = (
const directoryKey = uniqueDirectories.join('|');
const query = useInfiniteQuery({
queryKey: ['opencode', 'sessions', opcodeUrl, directoryKey, { search: normalizedSearch, limit }],
queryKey: ['opencode', 'sessions', directoryKey, { search: normalizedSearch, limit }],
queryFn: async ({ pageParam }) => {
if (!pageParam) {
const pages = await Promise.all(
uniqueDirectories.map((directory) =>
new OpenCodeClient(opcodeUrl!, directory).listSessionsPage({
listSessionPage({
directory,
limit,
order: 'desc',
search: normalizedSearch,
@@ -78,7 +72,7 @@ export const useSessionsAcrossDirectories = (
),
);
const cursors: SessionPageParam = {};
const items: Array<components['schemas']['Session']> = [];
const items: SessionInfo[] = [];
for (let i = 0; i < pages.length; i++) {
items.push(...pages[i].items);
if (pages[i].nextCursor) {
@@ -90,12 +84,10 @@ export const useSessionsAcrossDirectories = (
const entries = Object.entries(pageParam);
const pages = await Promise.all(
entries.map(([directory, cursor]) =>
new OpenCodeClient(opcodeUrl!, directory).listSessionsPage({ cursor }),
),
entries.map(([directory, cursor]) => listSessionPage({ directory, cursor })),
);
const cursors: SessionPageParam = {};
const items: Array<components['schemas']['Session']> = [];
const items: SessionInfo[] = [];
for (let i = 0; i < pages.length; i++) {
items.push(...pages[i].items);
if (pages[i].nextCursor) {
@@ -111,7 +103,7 @@ export const useSessionsAcrossDirectories = (
}
return undefined;
},
enabled: !!opcodeUrl && uniqueDirectories.length > 0,
enabled: uniqueDirectories.length > 0,
staleTime: 10000,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
@@ -129,13 +121,11 @@ export const useSessionsAcrossDirectories = (
};
};
export const useSession = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory);
export const useSession = (sessionID: string | undefined, directory?: string) => {
return useQuery({
queryKey: ["opencode", "session", opcodeUrl, sessionID, directory],
queryFn: () => client!.getSession(sessionID!),
enabled: !!client && !!sessionID,
queryKey: ["opencode", "session", sessionID, directory],
queryFn: () => getSession(sessionID!),
enabled: !!sessionID,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
staleTime: 15000,
@@ -143,33 +133,10 @@ export const useSession = (opcodeUrl: string | null | undefined, sessionID: stri
});
};
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string, opts?: { fallbackPoll?: boolean }) => {
const client = useOpenCodeClient(opcodeUrl, directory);
return useQuery({
queryKey: messagesQueryKey(opcodeUrl, sessionID, directory),
queryFn: async () => {
const response = await client!.listMessages(sessionID!)
reconcileConfirmedPrompt(sessionID!, response as MessageWithParts[])
return response as MessageWithParts[]
},
enabled: !!client && !!sessionID,
refetchOnMount: 'always',
refetchOnWindowFocus: true,
refetchOnReconnect: true,
staleTime: 30000,
gcTime: 10 * 60 * 1000,
refetchInterval: opts?.fallbackPoll ? 5000 : undefined,
retry: (failureCount, error) => !(error instanceof FetchError && error.statusCode === 404) && failureCount < 3,
});
};
export const useCreateSession = (
opcodeUrl: string | null | undefined,
directory?: string,
onSuccess?: (session: { id: string }) => void,
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
return useMutation({
@@ -178,11 +145,13 @@ export const useCreateSession = (
agent?: string;
model?: string;
}) => {
if (!client) throw new Error("No client available");
return client.createSession(data);
if (!directory) {
throw new Error('A directory is required to create a session');
}
return createSession({ directory, ...data });
},
onSuccess: (session) => {
invalidateSessionListCaches(queryClient, opcodeUrl);
invalidateSessionListCaches(queryClient);
onSuccess?.(session);
},
onError: (error) => {
@@ -195,7 +164,7 @@ export const useCreateSession = (
});
};
export type DeleteSessionTarget = string | { id: string; directory?: string; workspaceID?: string };
export type DeleteSessionTarget = string | { id: string; directory?: string };
const getDeleteSessionTargetId = (target: DeleteSessionTarget) =>
typeof target === 'string' ? target : target.id;
@@ -203,22 +172,10 @@ const getDeleteSessionTargetId = (target: DeleteSessionTarget) =>
const getDeleteSessionTargetDirectory = (target: DeleteSessionTarget, fallbackDirectory?: string) =>
typeof target === 'string' ? fallbackDirectory : target.directory ?? fallbackDirectory;
const getDeleteSessionTargetWorkspaceID = (target: DeleteSessionTarget) =>
typeof target === 'string' ? undefined : target.workspaceID;
const getDeleteSessionTargetKey = (target: DeleteSessionTarget, fallbackDirectory?: string) =>
buildSessionKey(getDeleteSessionTargetDirectory(target, fallbackDirectory), getDeleteSessionTargetId(target));
const isMissingWorkspaceError = (error: unknown) =>
error instanceof Error && error.message.includes('Workspace not found:');
const shouldDeleteWorkspaceForSessionDeleteError = (error: unknown) =>
isMissingWorkspaceError(error) ||
(error instanceof FetchError &&
error.statusCode === 500 &&
(error.message.includes('Unexpected server error') || error.message === 'Request failed'));
export const useDeleteSession = (opcodeUrl: string | null | undefined, directory?: string | string[]) => {
export const useDeleteSession = (directory?: string | string[]) => {
const queryClient = useQueryClient();
const directories = useMemo(
() => (Array.isArray(directory) ? directory : directory ? [directory] : []),
@@ -228,10 +185,6 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory
return useMutation({
mutationFn: async (sessionIDs: DeleteSessionTarget | DeleteSessionTarget[]) => {
if (!opcodeUrl) {
throw new Error('OpenCode client not available');
}
const targets = Array.from(
new Map(
(Array.isArray(sessionIDs) ? sessionIDs : [sessionIDs]).map((target) => [
@@ -240,44 +193,22 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory
]),
).values(),
)
const results: PromiseSettledResult<void>[] = []
const removedWorkspaces = new Set<string>()
for (const target of targets) {
const workspaceID = getDeleteSessionTargetWorkspaceID(target)
if (workspaceID && removedWorkspaces.has(workspaceID)) {
results.push({ status: 'fulfilled', value: undefined })
continue
}
const client = new OpenCodeClient(
opcodeUrl,
getDeleteSessionTargetDirectory(target, primaryDirectory),
)
const results: PromiseSettledResult<void>[] = []
for (const target of targets) {
try {
await client.deleteSession(getDeleteSessionTargetId(target))
await deleteSession(getDeleteSessionTargetId(target))
results.push({ status: 'fulfilled', value: undefined })
} catch (reason) {
if (workspaceID && shouldDeleteWorkspaceForSessionDeleteError(reason)) {
try {
await client.deleteWorkspace(workspaceID)
removedWorkspaces.add(workspaceID)
results.push({ status: 'fulfilled', value: undefined })
continue
} catch (workspaceReason) {
results.push({ status: 'rejected', reason: workspaceReason })
continue
}
}
results.push({ status: 'rejected', reason })
}
}
const failures = results.filter(result => result.status === 'rejected')
if (failures.length > 0) {
throw new Error(`Failed to delete ${failures.length} session(s)`)
}
return { deleted: targets.length, results }
},
onSuccess: ({ deleted }) => {
@@ -287,7 +218,7 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory
showToast.error('Failed to delete sessions');
},
onSettled: (_data, _error, variables) => {
invalidateSessionListCaches(queryClient, opcodeUrl);
invalidateSessionListCaches(queryClient);
cleanupSessionPins(queryClient, variables, primaryDirectory);
},
});
@@ -315,196 +246,112 @@ const cleanupSessionPins = (
});
};
export const useUpdateSession = (opcodeUrl: string | null | undefined, directory?: string) => {
export const useUpdateSession = (directory?: string) => {
const queryClient = useQueryClient();
const client = useOpenCodeClient(opcodeUrl, directory);
return useMutation({
mutationFn: async ({ sessionID, title }: { sessionID: string; title: string }) => {
if (!client) throw new Error("No client available");
return client.updateSession(sessionID, { title });
return renameSession(sessionID, title);
},
onSuccess: (_, variables) => {
const { sessionID } = variables;
queryClient.invalidateQueries({ queryKey: ["opencode", "session", opcodeUrl, sessionID, directory] });
invalidateSessionListCaches(queryClient, opcodeUrl);
queryClient.invalidateQueries({ queryKey: ["opencode", "session", sessionID, directory] });
invalidateSessionListCaches(queryClient);
},
});
};
const createOptimisticUserMessageParts = (
const sessionQueryKey = (sessionID: string, directory?: string) =>
["opencode", "session", sessionID, directory] as const;
const patchCachedSessionSelection = (
queryClient: ReturnType<typeof useQueryClient>,
sessionID: string,
parts: ContentPart[],
optimisticID: string,
directory: string | undefined,
patch: Partial<Pick<SessionInfo, 'model' | 'agent'>>,
) => {
return parts.map((part, index): Part => {
if (part.type === "text") {
return {
id: `${optimisticID}_part_${index}`,
type: "text" as const,
text: part.content,
messageID: optimisticID,
sessionID,
} as Part;
} else if (part.type === "image") {
return {
id: `${optimisticID}_part_${index}`,
type: "file" as const,
filename: part.filename,
url: part.dataUrl,
mime: part.mime || "image/*",
messageID: optimisticID,
sessionID,
} as Part;
} else {
return {
id: `${optimisticID}_part_${index}`,
type: "file" as const,
filename: part.name,
url: part.path.startsWith("file:") ? part.path : `file://${part.path}`,
mime: "text/plain",
messageID: optimisticID,
sessionID,
} as Part;
}
});
queryClient.setQueryData<SessionInfo>(sessionQueryKey(sessionID, directory), (current) =>
current ? { ...current, ...patch } : current,
);
};
const createOptimisticUserMessageInfo = (
sessionID: string,
optimisticID: string,
model?: string,
agent?: string,
variant?: string,
): Message => {
const message = {
id: optimisticID,
role: "user",
sessionID,
time: { created: Date.now() },
} as Message;
if (model) {
const parsedModel = parseModelString(model);
if (parsedModel) {
return {
...message,
model: parsedModel,
agent,
variant,
} as Message;
}
}
return { ...message, agent, variant } as Message;
};
const getPromptText = (prompt: string | undefined, parts: ContentPart[] | undefined): string => {
if (prompt !== undefined) return prompt;
if (!parts) return "";
return parts
.filter((part): part is ContentPart & { type: "text" } => part.type === "text")
.map((part) => part.content)
.join("")
.trim();
};
export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory);
export const useSyncSessionSelection = (directory?: string) => {
const queryClient = useQueryClient();
return useCallback(
async ({
sessionID,
model,
agent,
}: {
sessionID: string;
model?: ModelRef;
agent?: string;
}) => {
const session = queryClient.getQueryData<SessionInfo>(
sessionQueryKey(sessionID, directory),
);
if (model && !isSameModelRef(model, session?.model)) {
await switchSessionModel(sessionID, model);
patchCachedSessionSelection(queryClient, sessionID, directory, { model });
}
if (agent && agent !== session?.agent) {
await switchSessionAgent(sessionID, agent);
patchCachedSessionSelection(queryClient, sessionID, directory, { agent });
}
},
[queryClient, directory],
);
};
export const useSendPrompt = (directory?: string) => {
const queryClient = useQueryClient();
const syncSelection = useSyncSessionSelection(directory);
return useMutation({
mutationFn: async ({
sessionID,
prompt,
parts,
text,
files,
agents,
skills,
model,
agent,
variant,
delivery,
}: {
sessionID: string;
prompt?: string;
parts?: ContentPart[];
model?: string;
text: string;
files?: PromptFileInput[];
agents?: PromptAgentInput[];
skills?: PromptSkillInput[];
model?: ModelRef;
agent?: string;
variant?: string;
delivery?: 'steer' | 'queue';
}) => {
if (!client) throw new Error("No client available");
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
await queryClient.cancelQueries({ queryKey });
useSessionStatus.getState().setOptimisticActive(sessionID);
const requestData: SendPromptRequest = {
parts: parts?.map((part) =>
part.type === "text"
? { type: "text", text: (part as ContentPart & { type: "text" }).content }
: part.type === "image"
? {
type: "file",
mime: part.mime,
filename: part.filename,
url: part.dataUrl,
}
: {
type: "file",
mime: "text/plain",
filename: part.name,
url: part.path.startsWith("file:")
? part.path
: `file://${part.path}`,
},
) || [{ type: "text", text: prompt || "" }],
};
await syncSelection({ sessionID, model, agent });
if (model) {
const parsedModel = parseModelString(model);
if (parsedModel) {
const cachedProviders = queryClient.getQueryData<{
providers: Array<{ id: string; models: Record<string, unknown> }>;
}>(['opencode', 'providers', opcodeUrl, directory]);
if (cachedProviders?.providers) {
const provider = cachedProviders.providers.find(
(p) => p.id === parsedModel.providerID,
);
if (!provider || !(parsedModel.modelID in provider.models)) {
throw new FetchError(
'Selected model is no longer available. Pick a different model.',
409,
'MODEL_UNAVAILABLE',
);
}
const inbox = await sendPrompt({ sessionID, text, files, agents, skills, delivery });
queryClient.setQueryData<TranscriptCache>(
sessionTranscriptQueryKey(sessionID),
(current) => {
if (!current) return current;
if (current.transcript.messages.some((message) => message.id === inbox.id)) {
return current;
}
const transcript = admitInboxItem(current.transcript, inbox);
return transcript === current.transcript ? current : { ...current, transcript };
},
);
requestData.model = {
providerID: parsedModel.providerID,
modelID: parsedModel.modelID,
};
}
}
if (agent) {
requestData.agent = agent;
}
if (variant) {
requestData.variant = variant;
}
useSendErrorStore.getState().setQueuedPrompt(sessionID, getPromptText(prompt, parts));
await client.sendPromptAsync(sessionID, requestData);
return inbox;
},
onError: (error, variables) => {
const { sessionID, prompt, parts } = variables;
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
useSendErrorStore.getState().clearQueuedPrompt(sessionID);
queryClient.setQueryData<MessageWithParts[]>(
queryKey,
(old) => old?.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_")),
);
const { sessionID, text } = variables;
if (isGatewayTimeout(error)) {
return;
@@ -513,22 +360,17 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
useSessionStatus.getState().clearStatus(sessionID);
const parsed = parseNetworkError(error);
const failedPrompt = getPromptText(prompt, parts);
useSendErrorStore.getState().setError({
sessionID,
title: parsed.title,
message: parsed.message,
detail: error instanceof FetchError ? error.detail : undefined,
failedPrompt: failedPrompt || undefined,
failedPrompt: text || undefined,
kind: 'network',
});
},
onSuccess: async (_data, variables) => {
const { sessionID } = variables;
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
useSendErrorStore.getState().clearError(sessionID);
await queryClient.invalidateQueries({ queryKey });
onSuccess: (_inbox, variables) => {
useSendErrorStore.getState().clearError(variables.sessionID);
},
});
};
@@ -536,71 +378,10 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
const ABORT_RETRY_INTERVAL_MS = 3000;
const MAX_ABORT_RETRIES = 10;
export const useAbortSession = (
opcodeUrl: string | null | undefined,
directory?: string,
sessionID?: string,
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
export const useInterruptSession = () => {
const retryIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const retryCountRef = useRef(0);
const forceCompleteMessages = useCallback((targetSessionID: string) => {
const queryKey = messagesQueryKey(opcodeUrl, targetSessionID, directory);
const now = Date.now();
queryClient.setQueryData<MessageWithParts[]>(queryKey, (old) => {
if (!old) return old;
return old.map(msgWithParts => {
const msg = msgWithParts.info;
let updatedParts = msgWithParts.parts;
if (msg.role === "assistant") {
const assistantInfo = msg as AssistantMessage;
if (!assistantInfo.time.completed) {
updatedParts = updatedParts.map(part => {
if (part.type !== "tool") return part;
if (part.state.status !== "running" && part.state.status !== "pending") return part;
return {
...part,
state: {
...part.state,
status: "completed" as const,
output: part.state.status === "running" ? "[Session aborted]" : "[Tool was pending when session aborted]",
title: part.state.status === "running" ? (part.state as { title?: string }).title || "" : "",
metadata: (part.state as { metadata?: Record<string, unknown> }).metadata || {},
time: {
start: (part.state as { time?: { start: number } }).time?.start || now,
end: now
}
}
};
});
return {
...msgWithParts,
info: {
...assistantInfo,
time: {
...assistantInfo.time,
completed: now
},
error: {
name: "MessageAbortedError" as const,
data: { message: "Session aborted" }
}
},
parts: updatedParts
};
}
}
return msgWithParts;
});
});
}, [queryClient, opcodeUrl, directory]);
const stopRetrying = useCallback(() => {
if (retryIntervalRef.current) {
clearInterval(retryIntervalRef.current);
@@ -609,48 +390,17 @@ export const useAbortSession = (
retryCountRef.current = 0;
}, []);
const isSessionComplete = useCallback((targetSessionID: string) => {
const queryKey = messagesQueryKey(opcodeUrl, targetSessionID, directory);
const messages = queryClient.getQueryData<MessageWithParts[]>(queryKey);
const hasIncompleteMessages = messages?.some(msgWithParts => {
if (msgWithParts.info.role !== "assistant") return false;
const assistantInfo = msgWithParts.info as AssistantMessage;
return !assistantInfo.time.completed;
});
return !hasIncompleteMessages;
}, [queryClient, opcodeUrl, directory]);
useEffect(() => {
if (!sessionID) return;
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
if (event.query.queryKey.join(",") === queryKey.join(",")) {
if (isSessionComplete(sessionID) && retryIntervalRef.current) {
stopRetrying();
}
}
});
return () => unsubscribe();
}, [sessionID, queryClient, opcodeUrl, directory, isSessionComplete, stopRetrying]);
useEffect(() => {
return () => stopRetrying();
}, [stopRetrying]);
const mutation = useMutation({
mutationFn: async (targetSessionID: string) => {
if (!client) throw new Error("No client available");
stopRetrying();
forceCompleteMessages(targetSessionID);
const attemptAbort = async () => {
try {
await client.abortSession(targetSessionID);
await interruptSession(targetSessionID);
stopRetrying();
} catch {
// Will retry on next interval
@@ -661,20 +411,20 @@ export const useAbortSession = (
retryIntervalRef.current = setInterval(() => {
retryCountRef.current++;
if (retryCountRef.current >= MAX_ABORT_RETRIES) {
stopRetrying();
return;
}
if (isSessionComplete(targetSessionID)) {
if (useSessionStatus.getState().getStatus(targetSessionID).type === 'idle') {
stopRetrying();
return;
}
attemptAbort();
}, ABORT_RETRY_INTERVAL_MS);
return targetSessionID;
},
});
@@ -682,170 +432,46 @@ export const useAbortSession = (
return mutation;
};
export const useSendShell = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory);
export const useSendShell = (directory?: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
sessionID,
command,
agent,
}: {
sessionID: string;
command: string;
agent?: string;
}) => {
if (!client) throw new Error("No client available");
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
const userMessageParts = createOptimisticUserMessageParts(
sessionID,
[{ type: "text" as const, content: command }],
optimisticUserID,
);
const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID);
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
await queryClient.cancelQueries({ queryKey });
const optimisticMessageWithParts: MessageWithParts = {
info: userMessageInfo,
parts: userMessageParts,
}
queryClient.setQueryData<MessageWithParts[]>(
queryKey,
(old) => [...(old || []), optimisticMessageWithParts],
);
const response = await client.sendShell(sessionID, {
command,
agent: agent || "general",
});
return { optimisticUserID, response };
return runShell(sessionID, command);
},
onError: (_, variables) => {
onSuccess: (_data, variables) => {
const { sessionID } = variables;
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey(opcodeUrl, sessionID, directory),
(old) => {
if (!old) return old;
return old.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_"));
},
);
},
onSuccess: (data, variables) => {
const { sessionID } = variables;
const { optimisticUserID } = data;
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey(opcodeUrl, sessionID, directory),
(old) => {
if (!old) return old;
return old.filter((msgWithParts) => msgWithParts.info.id !== optimisticUserID);
},
);
queryClient.invalidateQueries({
queryKey: ["opencode", "session", opcodeUrl, sessionID, directory],
queryKey: ["opencode", "session", sessionID, directory],
});
},
});
};
export const useConfig = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory);
export const useAgents = (directory?: string, options?: { enabled?: boolean }) => {
return useQuery({
queryKey: ["opencode", "config", opcodeUrl, directory],
queryFn: () => client!.getConfig(),
enabled: !!client,
staleTime: 0,
refetchOnWindowFocus: true,
queryKey: ["opencode", "agents", directory],
queryFn: () => listAgents(directory),
enabled: options?.enabled ?? true,
});
};
export const useAgents = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory);
return useQuery({
queryKey: ["opencode", "agents", opcodeUrl, directory],
queryFn: () => client!.listAgents(),
enabled: !!client,
});
};
export const useLoadSkill = (
opcodeUrl: string | null | undefined,
sessionID: string | undefined,
directory?: string,
) => {
const client = useOpenCodeClient(opcodeUrl, directory);
const queryClient = useQueryClient();
return useMutation<
{ optimisticUserID: string; response: SendCommandResponse },
Error,
{ skillName: string }
>({
export const useLoadSkill = (sessionID: string | undefined) => {
return useMutation<void, Error, { skillName: string }>({
mutationFn: async ({ skillName }: { skillName: string }) => {
if (!client) throw new Error("No OpenCode client available");
if (!sessionID) throw new Error("No active session");
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
const userMessageParts = createOptimisticUserMessageParts(
sessionID,
[{ type: "text" as const, content: `Loading skill: ${skillName}` }],
optimisticUserID,
);
const userMessageInfo = createOptimisticUserMessageInfo(sessionID, optimisticUserID);
const optimisticMessageWithParts: MessageWithParts = {
info: userMessageInfo,
parts: userMessageParts,
};
await queryClient.cancelQueries({ queryKey });
queryClient.setQueryData<MessageWithParts[]>(
queryKey,
(old) => [...(old || []), optimisticMessageWithParts],
);
const response = await client.sendCommand(sessionID, { command: skillName, arguments: "" });
return { optimisticUserID, response };
return activateSkill(sessionID, skillName);
},
onError: (error) => {
if (sessionID) {
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
queryClient.setQueryData<MessageWithParts[]>(
queryKey,
(old) => old?.filter((m) => !m.info.id.startsWith("optimistic_")),
);
}
showToast.error(error instanceof Error ? error.message : "Failed to load skill");
},
onSuccess: (data) => {
const { response } = data;
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
queryClient.setQueryData<MessageWithParts[]>(
queryKey,
(old) => {
if (!old) return old;
const existingIdx = old.findIndex(m => m.info.id === response.info.id);
if (existingIdx >= 0) {
const updated = [...old];
updated[existingIdx] = { info: response.info, parts: response.parts };
return updated;
}
return [...old, { info: response.info, parts: response.parts }];
},
);
},
});
};