mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
refactor: derive session active state from messages instead of status store (#264)
* refactor: derive session active state from messages instead of status store * refactor: remove duplicate session.updated handler from EventContext
This commit is contained in:
1 parent
30c34e867e
commit
468e2f5dfb
5 files changed
+13
-60
No files matched your search
@@ -8,7 +8,6 @@ import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent,
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { openCodeEventStream, type EventStreamHealthState } from '@/lib/opencode-event-stream'
|
||||
import { OPENCODE_API_ENDPOINT } from '@/config'
|
||||
import { invalidateSessionListCachesDebounced } from '@/lib/queryInvalidation'
|
||||
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
|
||||
|
||||
type PermissionsBySession = Record<string, PermissionRequest[]>
|
||||
@@ -499,24 +498,6 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
})
|
||||
}
|
||||
break
|
||||
case 'session.updated':
|
||||
if ('info' in event.properties) {
|
||||
const sessionInfo = event.properties.info as { id: string }
|
||||
// Update single-session cache entries
|
||||
const cache = queryClient.getQueryCache()
|
||||
for (const query of cache.getAll()) {
|
||||
const key = query.queryKey
|
||||
if (key[0] === 'opencode' && key[1] === 'session' && key.length >= 5) {
|
||||
const sessionData = query.state.data as { id: string } | undefined
|
||||
if (sessionData?.id === sessionInfo.id) {
|
||||
queryClient.setQueryData(key, sessionInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Invalidate session list caches instead of mutating infinite-query data
|
||||
invalidateSessionListCachesDebounced(queryClient)
|
||||
}
|
||||
break
|
||||
case 'lsp.updated':
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'lsp']
|
||||
|
||||
@@ -8,7 +8,6 @@ import { showToast } from '../../lib/toast'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
sendCommand: vi.fn(),
|
||||
setStatus: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../api/opencode', () => ({
|
||||
@@ -25,10 +24,6 @@ vi.mock('../../lib/toast', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../../stores/sessionStatusStore', () => ({
|
||||
useSessionStatus: vi.fn((selector) => selector({ setStatus: mocks.setStatus })),
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
@@ -187,8 +182,6 @@ describe('useLoadSkill', () => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'busy' })
|
||||
expect(mocks.setStatus).toHaveBeenCalledWith('test-session-id', { type: 'idle' })
|
||||
})
|
||||
|
||||
it('removes optimistic message from cache on error', async () => {
|
||||
|
||||
@@ -11,7 +11,6 @@ import type {
|
||||
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 { useSendErrorStore } from "../stores/sendErrorStore";
|
||||
import { invalidateSessionListCaches, messagesQueryKey } from "../lib/queryInvalidation";
|
||||
|
||||
@@ -370,7 +369,6 @@ const createOptimisticUserMessageInfo = (
|
||||
export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
@@ -392,8 +390,6 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
|
||||
const contentParts = parts || [{ type: "text" as const, content: prompt || "", name: "" }];
|
||||
@@ -485,7 +481,6 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
const { sessionID } = variables;
|
||||
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
|
||||
|
||||
setSessionStatus(sessionID, { type: "idle" });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
queryKey,
|
||||
(old) => old?.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_")),
|
||||
@@ -534,7 +529,6 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
},
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID, { type: "idle" });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -691,7 +685,6 @@ export const useAbortSession = (
|
||||
export const useSendShell = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
@@ -705,8 +698,6 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
|
||||
}) => {
|
||||
if (!client) throw new Error("No client available");
|
||||
|
||||
setSessionStatus(sessionID, { type: "busy" });
|
||||
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
|
||||
const userMessageParts = createOptimisticUserMessageParts(
|
||||
@@ -737,7 +728,6 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
|
||||
},
|
||||
onError: (_, variables) => {
|
||||
const { sessionID } = variables;
|
||||
setSessionStatus(sessionID, { type: "idle" });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey(opcodeUrl, sessionID, directory),
|
||||
(old) => {
|
||||
@@ -745,8 +735,6 @@ 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;
|
||||
@@ -796,7 +784,6 @@ export const useLoadSkill = (
|
||||
) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
return useMutation<
|
||||
{ optimisticUserID: string; response: SendCommandResponse },
|
||||
@@ -807,8 +794,6 @@ export const useLoadSkill = (
|
||||
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 queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
|
||||
|
||||
@@ -835,7 +820,6 @@ export const useLoadSkill = (
|
||||
onError: (error) => {
|
||||
if (sessionID) {
|
||||
const queryKey = messagesQueryKey(opcodeUrl, sessionID, directory);
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
queryKey,
|
||||
(old) => old?.filter((m) => !m.info.id.startsWith("optimistic_")),
|
||||
@@ -862,8 +846,6 @@ export const useLoadSkill = (
|
||||
return [...old, { info: response.info, parts: response.parts }];
|
||||
},
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID!, { type: "idle" });
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -3,7 +3,6 @@ import { createOpenCodeClient } from '@/api/opencode'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { messagesQueryKey } from '@/lib/queryInvalidation'
|
||||
import type { Message, Part, MessageWithParts } from '@/api/types'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
|
||||
interface UseRemoveMessageOptions {
|
||||
opcodeUrl: string | null
|
||||
@@ -72,7 +71,6 @@ interface UseRefreshMessageOptions {
|
||||
export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefreshMessageOptions) {
|
||||
const queryClient = useQueryClient()
|
||||
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus)
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
@@ -88,8 +86,6 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
|
||||
}) => {
|
||||
if (!opcodeUrl) throw new Error('OpenCode URL not available')
|
||||
|
||||
setSessionStatus(sessionId, { type: 'busy' })
|
||||
|
||||
await removeMessage.mutateAsync({ messageID: assistantMessageID })
|
||||
|
||||
const client = createOpenCodeClient(opcodeUrl, directory)
|
||||
@@ -155,7 +151,6 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
|
||||
},
|
||||
onError: (_, variables) => {
|
||||
void variables
|
||||
setSessionStatus(sessionId, { type: 'idle' })
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
messagesQueryKey(opcodeUrl, sessionId, directory),
|
||||
(old) => {
|
||||
|
||||
@@ -40,8 +40,7 @@ import { ResetPermissionsDialog } from "@/components/repo/ResetPermissionsDialog
|
||||
import { RepoLspDialog } from "@/components/repo/RepoLspDialog";
|
||||
import { RepoSkillsDialog } from "@/components/repo/RepoSkillsDialog";
|
||||
import { createOpenCodeClient } from "@/api/opencode";
|
||||
import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore";
|
||||
import { usePermissions, useQuestions, useSSEHealth } from "@/contexts/EventContext";
|
||||
import { usePermissions, useQuestions } from "@/contexts/EventContext";
|
||||
import type { QuestionRequest } from "@/api/types";
|
||||
import { QuestionPrompt } from "@/components/session/QuestionPrompt";
|
||||
import { MinimizedQuestionIndicator } from "@/components/session/MinimizedQuestionIndicator";
|
||||
@@ -128,11 +127,8 @@ export function SessionDetail() {
|
||||
const sessionRouteSuffix = isAssistantSession ? '?assistant=1' : '';
|
||||
|
||||
const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory, sessionId);
|
||||
const sseHealth = useSSEHealth();
|
||||
const sessionStatus = useSessionStatusForSession(sessionId);
|
||||
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'compact' || sessionStatus.type === 'retry';
|
||||
|
||||
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory, { fallbackPoll: !sseHealth.isHealthy && isSessionActive });
|
||||
const { data: rawMessages, isLoading: messagesLoading } = useMessages(opcodeUrl, sessionId, repoDirectory);
|
||||
const { data: session, isLoading: sessionLoading } = useSession(
|
||||
opcodeUrl,
|
||||
sessionId,
|
||||
@@ -166,13 +162,21 @@ export function SessionDetail() {
|
||||
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
||||
const setActivePromptFileBasePath = useUIState((state) => state.setActivePromptFileBasePath);
|
||||
const { isEnabled: ttsEnabled } = useTTS();
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
const { syncForSession: syncPermissionsForSession } = usePermissions();
|
||||
const { current: currentQuestion, reply: replyToQuestion, reject: rejectQuestion, syncForSession: syncQuestionsForSession } = useQuestions();
|
||||
|
||||
const lastAssistantMessage = messages?.filter(m => m.info.role === 'assistant').at(-1);
|
||||
const lastAssistantText = getAssistantText(lastAssistantMessage);
|
||||
const latestPlayableAssistant = useMemo(() => getLatestPlayableAssistantMessage(messages), [messages]);
|
||||
|
||||
const isSessionActive = useMemo(() => {
|
||||
if (session?.time?.compacting) return true
|
||||
if (!messages || messages.length === 0) return false
|
||||
const last = messages[messages.length - 1]
|
||||
if (last.info.role === 'user') return true
|
||||
if (last.info.role === 'assistant' && !('completed' in last.info.time)) return true
|
||||
return false
|
||||
}, [messages, session?.time?.compacting])
|
||||
const hasIncompleteMessages = lastAssistantMessage ? !('completed' in lastAssistantMessage.info.time && lastAssistantMessage.info.time.completed) : false;
|
||||
const isStreamingResponse = hasIncompleteMessages && isSessionActive;
|
||||
const assistantFileBasePath = assistantMode?.directory.split('/').filter(Boolean).at(-1);
|
||||
@@ -228,7 +232,7 @@ export function SessionDetail() {
|
||||
refetchOnMount: 'always',
|
||||
refetchOnReconnect: true,
|
||||
refetchOnWindowFocus: true,
|
||||
refetchInterval: !sseHealth.isHealthy && (isSessionActive || hasIncompleteMessages) ? PENDING_ACTION_SYNC_INTERVAL_MS : false,
|
||||
refetchInterval: !isConnected && (isSessionActive || hasIncompleteMessages) ? PENDING_ACTION_SYNC_INTERVAL_MS : false,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
@@ -255,16 +259,14 @@ export function SessionDetail() {
|
||||
}
|
||||
|
||||
showToast.loading('Compacting session...', { id: `compact-${sessionId}` });
|
||||
setSessionStatus(sessionId, { type: 'compact' });
|
||||
|
||||
try {
|
||||
const client = createOpenCodeClient(opcodeUrl, repoDirectory);
|
||||
await client.summarizeSession(sessionId, model.providerID, model.modelID);
|
||||
} catch (error) {
|
||||
showToast.error(`Compact failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
setSessionStatus(sessionId, { type: 'idle' });
|
||||
}
|
||||
}, [opcodeUrl, sessionId, model, repoDirectory, setSessionStatus]);
|
||||
}, [opcodeUrl, sessionId, model, repoDirectory]);
|
||||
|
||||
const handleUndo = useCallback(async () => {
|
||||
if (!opcodeUrl || !sessionId) return;
|
||||
|
||||
Reference in new issue
Block a user