mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat: add assistant mode, SSE streaming, and OpenCode server integration (#214)
This commit is contained in:
1 parent
3cc24288a6
commit
c3d6549f01
133 files changed
+7284
-6293
No files matched your search
@@ -2,7 +2,6 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import { OpenCodeClient } from "../api/opencode";
|
||||
import { FetchError } from "../api/fetchWrapper";
|
||||
import { cancelLoop } from "../api/memory";
|
||||
import type {
|
||||
Message,
|
||||
Part,
|
||||
@@ -13,7 +12,6 @@ import type { paths, components } from "../api/opencode-types";
|
||||
import { parseNetworkError } from "../lib/opencode-errors";
|
||||
import { showToast } from "../lib/toast";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
import { ensureSSEConnected, reconnectSSE } from "../lib/sseManager";
|
||||
|
||||
type AssistantMessage = components["schemas"]["AssistantMessage"];
|
||||
|
||||
@@ -21,6 +19,8 @@ type SendPromptRequest = NonNullable<
|
||||
paths["/session/{sessionID}/message"]["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("/");
|
||||
@@ -61,7 +61,7 @@ export const useSession = (opcodeUrl: string | null | undefined, sessionID: stri
|
||||
});
|
||||
};
|
||||
|
||||
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string) => {
|
||||
export const useMessages = (opcodeUrl: string | null | undefined, sessionID: string | undefined, directory?: string, opts?: { fallbackPoll?: boolean }) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
|
||||
return useQuery({
|
||||
@@ -76,7 +76,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str
|
||||
refetchOnReconnect: true,
|
||||
staleTime: 30000,
|
||||
gcTime: 10 * 60 * 1000,
|
||||
|
||||
refetchInterval: opts?.fallbackPoll ? 5000 : undefined,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -239,6 +239,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
model,
|
||||
agent,
|
||||
variant,
|
||||
queued,
|
||||
}: {
|
||||
sessionID: string;
|
||||
prompt?: string;
|
||||
@@ -246,15 +247,10 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
model?: string;
|
||||
agent?: string;
|
||||
variant?: string;
|
||||
queued?: boolean;
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
const connected = await ensureSSEConnected();
|
||||
if (!connected) {
|
||||
showToast.error("Unable to connect. Please try again.");
|
||||
throw new Error("SSE connection failed");
|
||||
}
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
@@ -319,9 +315,14 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
requestData.variant = variant;
|
||||
}
|
||||
|
||||
if (queued) {
|
||||
await client.sendPromptAsync(sessionID, requestData);
|
||||
return { optimisticUserID, queued: true };
|
||||
}
|
||||
|
||||
const response = await client.sendPrompt(sessionID, requestData);
|
||||
|
||||
return { optimisticUserID, response };
|
||||
return { optimisticUserID, response, queued: false };
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
const { sessionID } = variables;
|
||||
@@ -334,19 +335,12 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
);
|
||||
|
||||
const isNetworkError = error instanceof TypeError ||
|
||||
(error instanceof FetchError && error.code === 'TIMEOUT');
|
||||
(error instanceof FetchError && (error.code === 'TIMEOUT' || error.statusCode === 524));
|
||||
|
||||
if (isNetworkError) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchError = error as { statusCode?: number };
|
||||
const isCloudflareTimeout = fetchError.statusCode === 524;
|
||||
if (isCloudflareTimeout) {
|
||||
reconnectSSE();
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = parseNetworkError(error);
|
||||
showToast.error(parsed.title, {
|
||||
description: parsed.message,
|
||||
@@ -358,6 +352,11 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
const { response } = data;
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
|
||||
if (data.queued || !response) {
|
||||
queryClient.invalidateQueries({ queryKey: messagesQueryKey });
|
||||
return;
|
||||
}
|
||||
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(old) => {
|
||||
@@ -386,7 +385,6 @@ export const useAbortSession = (
|
||||
opcodeUrl: string | null | undefined,
|
||||
directory?: string,
|
||||
sessionID?: string,
|
||||
repoId?: number
|
||||
) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
@@ -506,10 +504,6 @@ export const useAbortSession = (
|
||||
|
||||
attemptAbort();
|
||||
|
||||
if (repoId) {
|
||||
cancelLoop(repoId, targetSessionID).catch(() => {})
|
||||
}
|
||||
|
||||
retryIntervalRef.current = setInterval(() => {
|
||||
retryCountRef.current++;
|
||||
|
||||
@@ -590,6 +584,8 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
|
||||
return old.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_"));
|
||||
},
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
},
|
||||
onSuccess: (data, variables) => {
|
||||
const { sessionID } = variables;
|
||||
@@ -631,3 +627,82 @@ export const useAgents = (opcodeUrl: string | null | undefined, directory?: stri
|
||||
enabled: !!client,
|
||||
});
|
||||
};
|
||||
|
||||
export const useLoadSkill = (
|
||||
opcodeUrl: string | null | undefined,
|
||||
sessionID: string | undefined,
|
||||
directory?: string,
|
||||
) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
return useMutation<
|
||||
{ optimisticUserID: string; response: SendCommandResponse },
|
||||
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");
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
const messagesQueryKey = ["opencode", "messages", 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: messagesQueryKey });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(old) => [...(old || []), optimisticMessageWithParts],
|
||||
);
|
||||
|
||||
const response = await client.sendCommand(sessionID, { command: skillName, arguments: "" });
|
||||
return { optimisticUserID, response };
|
||||
},
|
||||
onError: (error) => {
|
||||
if (sessionID) {
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(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 messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey,
|
||||
(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 }];
|
||||
},
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
},
|
||||
});
|
||||
};
|
||||
Reference in new issue
Block a user