refactor: inline message parts with batched SSE updates (#137)

This commit is contained in:
Chris Scott authored and GitHub committed 2026-02-16 10:47:37 -05:00
1 parent 63561640fd
commit 725122b588
12 files changed
+408 -337

No files matched your search

@@ -4,10 +4,9 @@ import { MessagePart } from './MessagePart'
import { UserMessageActionButtons } from './UserMessageActionButtons'
import { EditableUserMessage, ClickableUserMessage } from './EditableUserMessage'
import { MessageError } from './MessageError'
import type { Message, Part } from '@/api/types'
import type { Message, Part, MessageWithParts } from '@/api/types'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import { useMessageParts, usePartsForMessage, usePartsVersion } from '@/stores/messagePartsStore'
import type { components } from '@/api/opencode-types'
import type { Todo } from '@/components/message/SessionTodoDisplay'
import type { OpenCodeError } from '@/lib/opencode-errors'
@@ -24,7 +23,7 @@ interface MessageThreadProps {
opcodeUrl: string
sessionID: string
directory?: string
messages?: Message[]
messages?: MessageWithParts[]
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
onUndoMessage?: (restoredPrompt: string) => void
@@ -48,12 +47,12 @@ const compareMessageIds = (id1: string, id2: string): number => {
}
const findLastMessageByRole = (
messages: Message[],
messages: MessageWithParts[],
role: 'user' | 'assistant',
predicate?: (msg: Message) => boolean
): string | undefined => {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
const msg = messages[i].info
if (msg.role === role && (!predicate || predicate(msg))) {
return msg.id
}
@@ -62,9 +61,9 @@ const findLastMessageByRole = (
}
interface MessageRowProps {
msg: Message
msgWithParts: MessageWithParts
index: number
messages: Message[]
messages: MessageWithParts[]
pendingAssistantId: string | undefined
lastUserMessageId: string | undefined
isSessionBusy: boolean
@@ -82,7 +81,7 @@ interface MessageRowProps {
}
const MessageRow = memo(function MessageRow({
msg,
msgWithParts,
index,
messages,
pendingAssistantId,
@@ -100,13 +99,15 @@ const MessageRow = memo(function MessageRow({
handleCancelEdit,
model,
}: MessageRowProps) {
const parts = usePartsForMessage(msg.id)
const msg = msgWithParts.info
const parts = msgWithParts.parts
const streaming = isMessageStreaming(msg)
const isQueued = msg.role === 'user' && pendingAssistantId && compareMessageIds(msg.id, pendingAssistantId) > 0
const isLastUserMessage = msg.role === 'user' && msg.id === lastUserMessageId
const messageTextContent = getMessageTextContent(parts)
const nextAssistantMessage = messages.slice(index + 1).find(m => m.role === 'assistant')
const nextAssistantMessage = messages.slice(index + 1).find(m => m.info.role === 'assistant')
const nextAssistantMsg = nextAssistantMessage?.info
const isUserBeforeAssistant = msg.role === 'user' && nextAssistantMessage
const canEditUserMessage = isLastUserMessage && isUserBeforeAssistant && !isSessionBusy
const canUndoUserMessage = isLastUserMessage && nextAssistantMessage && !isSessionBusy && onUndoMessage
@@ -139,9 +140,9 @@ const MessageRow = memo(function MessageRow({
{new Date(msg.time.created).toLocaleTimeString()}
</span>
)}
{canEditUserMessage && nextAssistantMessage && (
{canEditUserMessage && nextAssistantMsg && (
<button
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMessage.id)}
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMsg.id)}
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
title="Edit message"
>
@@ -178,10 +179,10 @@ const MessageRow = memo(function MessageRow({
onCancel={handleCancelEdit}
model={model}
/>
) : msg.role === 'user' && canEditUserMessage && nextAssistantMessage ? (
) : msg.role === 'user' && canEditUserMessage && nextAssistantMsg ? (
<ClickableUserMessage
content={messageTextContent}
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMessage.id)}
onClick={() => handleStartEditUserMessage(msg.id, nextAssistantMsg.id)}
isEditable={false}
/>
) : parts.length > 0 ? (
@@ -234,19 +235,11 @@ export const MessageThread = memo(function MessageThread({
const isSessionBusy = !!pendingAssistantId || isSessionInRetry(sessionStatus)
const setSessionTodos = useSessionTodos((state) => state.setTodos)
const partsVersion = usePartsVersion()
useEffect(() => {
if (!messages || messages.length === 0) return
const partsMap = useMessageParts.getState().parts
const allParts: Part[] = []
for (const msg of messages) {
const msgParts = partsMap.get(msg.id)
if (msgParts) {
allParts.push(...msgParts)
}
}
const allParts = messages.flatMap(m => m.parts)
const latestTodoPart = allParts
.filter((part): part is components['schemas']['ToolPart'] => part.type === 'tool' && (part.tool === 'todowrite' || part.tool === 'todoread'))
@@ -281,7 +274,7 @@ export const MessageThread = memo(function MessageThread({
setSessionTodos(sessionID, todos)
}
}
}, [messages, sessionID, setSessionTodos, partsVersion])
}, [messages, sessionID, setSessionTodos])
const handleStartEditUserMessage = useCallback((userMessageId: string, assistantMessageId: string) => {
setEditingUserMessageId(userMessageId)
@@ -303,10 +296,10 @@ export const MessageThread = memo(function MessageThread({
return (
<div className="flex flex-col space-y-2 p-2 overflow-x-hidden">
{messages.map((msg, index) => (
{messages.map((msgWithParts, index) => (
<MessageRow
key={msg.id}
msg={msg}
key={msgWithParts.info.id}
msgWithParts={msgWithParts}
index={index}
messages={messages}
pendingAssistantId={pendingAssistantId}
+10 -20
View File
@@ -1,5 +1,5 @@
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell, useAgents } from '@/hooks/useOpenCode'
import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
@@ -10,7 +10,7 @@ import { useSTT } from '@/hooks/useSTT'
import { useUserBash } from '@/stores/userBashStore'
import { useMobile } from '@/hooks/useMobile'
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
import { usePermissions } from '@/contexts/EventContext'
import { ChevronDown, Upload, X, Mic, MicOff } from 'lucide-react'
@@ -25,7 +25,7 @@ import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQu
import type { components } from '@/api/opencode-types'
import type { Message, FileAttachmentInfo, ImageAttachment } from '@/api/types'
import type { FileAttachmentInfo, ImageAttachment } from '@/api/types'
const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"]
@@ -55,6 +55,7 @@ interface PromptInputProps {
sessionID: string
disabled?: boolean
showScrollButton?: boolean
hasActiveStream?: boolean
onScrollToBottom?: () => void
onShowSessionsDialog?: () => void
onShowModelsDialog?: () => void
@@ -64,12 +65,13 @@ interface PromptInputProps {
onPromptChange?: (hasContent: boolean) => void
}
export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
export const PromptInput = memo(forwardRef<PromptInputHandle, PromptInputProps>(function PromptInput({
opcodeUrl,
directory,
sessionID,
disabled,
showScrollButton,
hasActiveStream = false,
onScrollToBottom,
onShowSessionsDialog,
onShowModelsDialog,
@@ -137,7 +139,6 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory, sessionID)
const { data: messages } = useMessages(opcodeUrl, sessionID, directory)
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
@@ -184,7 +185,7 @@ export const PromptInput = forwardRef<PromptInputHandle, PromptInputProps>(funct
}, [agents, searchResults, mentionQuery])
const { addUserBashCommand } = useUserBash()
const addUserBashCommand = useUserBash((s) => s.addUserBashCommand)
const handleSubmit = () => {
if (disabled) return
@@ -715,14 +716,6 @@ if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read)
}
}
const isMessageIncomplete = (msg: Message): boolean => {
if (msg.role !== 'assistant') return false
return !('completed' in msg.time && msg.time.completed)
}
const lastAssistantMessage = messages?.filter(msg => msg.role === 'assistant').at(-1)
const hasIncompleteMessages = lastAssistantMessage ? isMessageIncomplete(lastAssistantMessage) : false
const sessionAgent = useSessionAgent(opcodeUrl, sessionID, directory)
const currentMode = localMode ?? sessionAgent.agent
@@ -733,10 +726,7 @@ const { model, modelString } = useModelSelection(opcodeUrl, directory)
const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions()
const hasPendingPermissionForSession = hasPermissionsForSession(sessionID)
const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory)
const sessionStatus = useSessionStatusForSession(sessionID)
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'retry'
const hasActiveStream = hasIncompleteMessages && isSessionActive
const showStopButton = isSessionActive && hasIncompleteMessages
const showStopButton = hasActiveStream
const hideSecondaryButtons = isMobile && hasActiveStream
@@ -969,4 +959,4 @@ return (
/>
</div>
)
})
}))
+69 -23
View File
@@ -4,33 +4,79 @@ import { useNavigate, useLocation } from 'react-router-dom'
import { useQueryClient, useQuery } from '@tanstack/react-query'
import { OpenCodeClient } from '@/api/opencode'
import { listRepos } from '@/api/repos'
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest } from '@/api/types'
import type { PermissionRequest, PermissionResponse, QuestionRequest, SSEEvent, SSHHostKeyRequest, MessageWithParts } from '@/api/types'
import { showToast } from '@/lib/toast'
import { subscribeToSSE, addSSEDirectory, ensureSSEConnected } from '@/lib/sseManager'
import { OPENCODE_API_ENDPOINT } from '@/config'
import { addToSessionKeyedState, removeFromSessionKeyedState } from '@/lib/sessionKeyedState'
import { useMessageParts } from '@/stores/messagePartsStore'
type PermissionsBySession = Record<string, PermissionRequest[]>
type QuestionsBySession = Record<string, QuestionRequest[]>
function optimisticallyErrorToolPart(messageID: string, callID: string, errorMessage: string) {
const store = useMessageParts.getState()
const parts = store.parts.get(messageID)
const target = parts?.find(p => p.type === 'tool' && p.callID === callID)
if (target && target.type === 'tool' && target.state.status === 'running') {
store.setPart(messageID, {
...target,
state: {
status: 'error' as const,
input: target.state.input,
error: errorMessage,
time: {
start: target.state.time.start,
end: Date.now(),
},
},
})
function optimisticallyErrorToolPart(
queryClient: ReturnType<typeof useQueryClient>,
sessionID: string,
messageID: string,
callID: string,
errorMessage: string
) {
const cache = queryClient.getQueryCache()
const queries = cache.getAll()
for (const query of queries) {
const key = query.queryKey
if (key[0] === 'opencode' && key[1] === 'messages' && key.length >= 5) {
const querySessionID = key[3] as string
if (querySessionID !== sessionID) continue
const currentData = queryClient.getQueryData<MessageWithParts[]>(key)
if (!currentData) continue
const updatedData = currentData.map(msgWithParts => {
if (msgWithParts.info.id !== messageID) return msgWithParts
const targetPart = msgWithParts.parts.find(p =>
p.type === 'tool' &&
'callID' in p &&
p.callID === callID &&
'state' in p &&
p.state &&
typeof p.state === 'object' &&
'status' in p.state &&
(p.state as { status?: string }).status === 'running'
)
if (!targetPart) {
return msgWithParts
}
const targetPartAny = targetPart as unknown as { state: { status: string; input?: string; time: { start: number } } }
const targetState = targetPartAny.state
const updatedParts = msgWithParts.parts.map(p => {
if (p.id !== targetPart.id) return p
return {
...p,
state: {
status: 'error' as const,
input: targetState.input,
error: errorMessage,
time: {
start: targetState.time.start,
end: Date.now(),
},
},
}
})
return {
...msgWithParts,
parts: updatedParts,
}
})
queryClient.setQueryData(key, updatedData)
break
}
}
}
@@ -206,12 +252,12 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
if (response === 'reject') {
const permission = (permissionsBySession[sessionID] ?? []).find(p => p.id === permissionID)
if (permission?.tool) {
optimisticallyErrorToolPart(permission.tool.messageID, permission.tool.callID, 'Permission denied')
optimisticallyErrorToolPart(queryClient, sessionID, permission.tool.messageID, permission.tool.callID, 'Permission denied')
}
}
await client.respondToPermission(sessionID, permissionID, response)
}, [getClient, permissionsBySession])
}, [getClient, permissionsBySession, queryClient])
const replyToQuestion = useCallback(async (requestID: string, answers: string[][]) => {
const connected = await ensureSSEConnected()
@@ -238,11 +284,11 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
if (!client) throw new Error('No client found for session')
if (question.tool) {
optimisticallyErrorToolPart(question.tool.messageID, question.tool.callID, 'Question rejected')
optimisticallyErrorToolPart(queryClient, question.sessionID, question.tool.messageID, question.tool.callID, 'Question rejected')
}
await client.rejectQuestion(requestID)
}, [getClient, questionsBySession])
}, [getClient, questionsBySession, queryClient])
const getPermissionForCallID = useCallback((callID: string, sessionID: string): PermissionRequest | null => {
const perms = permissionsBySession[sessionID] ?? []
+7 -5
View File
@@ -55,11 +55,12 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
return useMemo(() => {
const currentModel = modelString || null
const assistantMessages = messages?.filter(msg => msg.role === 'assistant') || []
const assistantMessages = messages?.filter(msg => msg.info.role === 'assistant') || []
let latestAssistantMessage = assistantMessages[assistantMessages.length - 1]
if (latestAssistantMessage?.role === 'assistant') {
const tokens = latestAssistantMessage.tokens.input + latestAssistantMessage.tokens.output + latestAssistantMessage.tokens.reasoning + (latestAssistantMessage.tokens.cache?.read || 0)
if (latestAssistantMessage?.info.role === 'assistant') {
const msgInfo = latestAssistantMessage.info as { tokens?: { input: number; output: number; reasoning: number; cache?: { read: number } } }
const tokens = (msgInfo.tokens?.input ?? 0) + (msgInfo.tokens?.output ?? 0) + (msgInfo.tokens?.reasoning ?? 0) + (msgInfo.tokens?.cache?.read ?? 0)
if (tokens === 0 && assistantMessages.length > 1) {
latestAssistantMessage = assistantMessages[assistantMessages.length - 2]
}
@@ -88,8 +89,9 @@ export const useContextUsage = (opcodeUrl: string | null | undefined, sessionID:
}
let totalTokens = 0
if (latestAssistantMessage?.role === 'assistant') {
totalTokens = latestAssistantMessage.tokens.input + latestAssistantMessage.tokens.output + latestAssistantMessage.tokens.reasoning + (latestAssistantMessage.tokens.cache?.read || 0)
if (latestAssistantMessage?.info.role === 'assistant') {
const msgInfo = latestAssistantMessage.info as { tokens?: { input: number; output: number; reasoning: number; cache?: { read: number } } }
totalTokens = (msgInfo.tokens?.input ?? 0) + (msgInfo.tokens?.output ?? 0) + (msgInfo.tokens?.reasoning ?? 0) + (msgInfo.tokens?.cache?.read ?? 0)
}
const usagePercentage = contextLimit ? (totalTokens / contextLimit) * 100 : null
+66 -63
View File
@@ -7,12 +7,12 @@ import type {
Message,
Part,
ContentPart,
MessageWithParts,
} from "../api/types";
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 { useMessageParts } from "@/stores/messagePartsStore";
import { ensureSSEConnected, reconnectSSE } from "../lib/sseManager";
const titleGeneratingSessionsState = new Set<string>();
@@ -86,8 +86,7 @@ export const useMessages = (opcodeUrl: string | null | undefined, sessionID: str
queryKey: ["opencode", "messages", opcodeUrl, sessionID, directory],
queryFn: async () => {
const response = await client!.listMessages(sessionID!)
useMessageParts.getState().initFromMessages(response)
return response.map(m => m.info) as Message[]
return response as MessageWithParts[]
},
enabled: !!client && !!sessionID,
refetchOnMount: 'always',
@@ -298,11 +297,14 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
await queryClient.cancelQueries({ queryKey: messagesQueryKey });
queryClient.setQueryData<Message[]>(
const optimisticMessageWithParts: MessageWithParts = {
info: userMessageInfo,
parts: userMessageParts,
}
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => [...(old || []), userMessageInfo],
(old) => [...(old || []), optimisticMessageWithParts],
);
useMessageParts.getState().setParts(optimisticUserID, userMessageParts);
const requestData: SendPromptRequest = {
parts: parts?.map((part) =>
@@ -369,9 +371,9 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
}
setSessionStatus(sessionID, { type: "idle" });
queryClient.setQueryData<Message[]>(
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => old?.filter((msg) => !msg.id.startsWith("optimistic_")),
(old) => old?.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_")),
);
const parsed = parseNetworkError(error);
@@ -385,25 +387,23 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
const { optimisticUserID, userPromptText, response } = data;
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
queryClient.setQueryData<Message[]>(
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => {
if (!old) return old;
const withoutOptimistic = old.filter((msg) => msg.id !== optimisticUserID);
const withoutOptimistic = old.filter((msgWithParts) => msgWithParts.info.id !== optimisticUserID);
const existingIdx = withoutOptimistic.findIndex(m => m.id === response.info.id);
const existingIdx = withoutOptimistic.findIndex(m => m.info.id === response.info.id);
if (existingIdx >= 0) {
const updated = [...withoutOptimistic];
updated[existingIdx] = response.info;
updated[existingIdx] = { info: response.info, parts: response.parts };
return updated;
}
return [...withoutOptimistic, response.info];
return [...withoutOptimistic, { info: response.info, parts: response.parts }];
},
);
useMessageParts.getState().setParts(response.info.id, response.parts);
setSessionStatus(sessionID, { type: "idle" });
queryClient.invalidateQueries({
@@ -432,55 +432,55 @@ export const useAbortSession = (
const queryKey = ["opencode", "messages", opcodeUrl, targetSessionID, directory];
const now = Date.now();
queryClient.setQueryData<Message[]>(queryKey, (old) => {
queryClient.setQueryData<MessageWithParts[]>(queryKey, (old) => {
if (!old) return old;
return old.map(msg => {
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 {
...assistantInfo,
time: {
...assistantInfo.time,
completed: now
...msgWithParts,
info: {
...assistantInfo,
time: {
...assistantInfo.time,
completed: now
},
error: {
name: "MessageAbortedError" as const,
data: { message: "Session aborted" }
}
},
error: {
name: "MessageAbortedError" as const,
data: { message: "Session aborted" }
}
parts: updatedParts
};
}
}
return msg;
return msgWithParts;
});
});
const partsStore = useMessageParts.getState();
for (const [messageID, parts] of partsStore.parts) {
if (!parts.some(p => p.sessionID === targetSessionID)) continue;
const updatedParts = parts.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
}
}
};
});
useMessageParts.getState().setParts(messageID, updatedParts);
}
}, [queryClient, opcodeUrl, directory]);
const stopRetrying = useCallback(() => {
@@ -493,11 +493,11 @@ export const useAbortSession = (
const isSessionComplete = useCallback((targetSessionID: string) => {
const queryKey = ["opencode", "messages", opcodeUrl, targetSessionID, directory];
const messages = queryClient.getQueryData<Message[]>(queryKey);
const messages = queryClient.getQueryData<MessageWithParts[]>(queryKey);
const hasActiveStream = messages?.some(msg => {
if (msg.role !== "assistant") return false;
const assistantInfo = msg as AssistantMessage;
const hasActiveStream = messages?.some(msgWithParts => {
if (msgWithParts.info.role !== "assistant") return false;
const assistantInfo = msgWithParts.info as AssistantMessage;
return !assistantInfo.time.completed;
});
@@ -595,11 +595,14 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
await queryClient.cancelQueries({ queryKey: messagesQueryKey });
queryClient.setQueryData<Message[]>(
const optimisticMessageWithParts: MessageWithParts = {
info: userMessageInfo,
parts: userMessageParts,
}
queryClient.setQueryData<MessageWithParts[]>(
messagesQueryKey,
(old) => [...(old || []), userMessageInfo],
(old) => [...(old || []), optimisticMessageWithParts],
);
useMessageParts.getState().setParts(optimisticUserID, userMessageParts);
const response = await client.sendShell(sessionID, {
command,
@@ -611,11 +614,11 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
onError: (_, variables) => {
const { sessionID } = variables;
setSessionStatus(sessionID, { type: "idle" });
queryClient.setQueryData<Message[]>(
queryClient.setQueryData<MessageWithParts[]>(
["opencode", "messages", opcodeUrl, sessionID, directory],
(old) => {
if (!old) return old;
return old.filter((msg) => !msg.id.startsWith("optimistic_"));
return old.filter((msgWithParts) => !msgWithParts.info.id.startsWith("optimistic_"));
},
);
},
@@ -623,11 +626,11 @@ export const useSendShell = (opcodeUrl: string | null | undefined, directory?: s
const { sessionID } = variables;
const { optimisticUserID } = data;
queryClient.setQueryData<Message[]>(
queryClient.setQueryData<MessageWithParts[]>(
["opencode", "messages", opcodeUrl, sessionID, directory],
(old) => {
if (!old) return old;
return old.filter((msg) => msg.id !== optimisticUserID);
return old.filter((msgWithParts) => msgWithParts.info.id !== optimisticUserID);
},
);
+13 -14
View File
@@ -1,9 +1,8 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createOpenCodeClient } from '@/api/opencode'
import { showToast } from '@/lib/toast'
import type { Message, Part } from '@/api/types'
import type { Message, Part, MessageWithParts } from '@/api/types'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useMessageParts } from '@/stores/messagePartsStore'
interface UseRemoveMessageOptions {
opcodeUrl: string | null
@@ -12,12 +11,11 @@ interface UseRemoveMessageOptions {
}
interface RemoveMessageContext {
previousMessages?: Message[]
previousMessages?: MessageWithParts[]
}
export function useRemoveMessage({ opcodeUrl, sessionId, directory }: UseRemoveMessageOptions) {
const queryClient = useQueryClient()
const clearMessage = useMessageParts((state) => state.clearMessage)
return useMutation<unknown, Error, { messageID: string; partID?: string }, RemoveMessageContext>({
mutationFn: async ({ messageID, partID }: { messageID: string, partID?: string }) => {
@@ -31,18 +29,16 @@ export function useRemoveMessage({ opcodeUrl, sessionId, directory }: UseRemoveM
await queryClient.cancelQueries({ queryKey })
const previousMessages = queryClient.getQueryData<Message[]>(queryKey)
const previousMessages = queryClient.getQueryData<MessageWithParts[]>(queryKey)
if (previousMessages) {
const messageIndex = previousMessages.findIndex(m => m.id === messageID)
const messageIndex = previousMessages.findIndex(m => m.info.id === messageID)
if (messageIndex !== -1) {
const newMessages = previousMessages.slice(0, messageIndex)
queryClient.setQueryData(queryKey, newMessages)
}
}
clearMessage(messageID)
return { previousMessages }
},
onError: (_error, _variables, _context: RemoveMessageContext | undefined) => {
@@ -76,7 +72,6 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
const queryClient = useQueryClient()
const removeMessage = useRemoveMessage({ opcodeUrl, sessionId, directory })
const setSessionStatus = useSessionStatus((state) => state.setStatus)
const setParts = useMessageParts((state) => state.setParts)
return useMutation({
mutationFn: async ({
@@ -114,11 +109,15 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
sessionID: sessionId
}] as Part[]
queryClient.setQueryData<Message[]>(
const optimisticMessageWithParts: MessageWithParts = {
info: userMessageInfo,
parts: userMessageParts,
}
queryClient.setQueryData<MessageWithParts[]>(
['opencode', 'messages', opcodeUrl, sessionId, directory],
(old) => [...(old || []), userMessageInfo]
(old) => [...(old || []), optimisticMessageWithParts]
)
setParts(optimisticUserID, userMessageParts)
interface SendPromptRequest {
parts: Array<{ type: 'text'; text: string }>
@@ -156,11 +155,11 @@ export function useRefreshMessage({ opcodeUrl, sessionId, directory }: UseRefres
onError: (_, variables) => {
void variables
setSessionStatus(sessionId, { type: 'idle' })
queryClient.setQueryData<Message[]>(
queryClient.setQueryData<MessageWithParts[]>(
['opencode', 'messages', opcodeUrl, sessionId, directory],
(old) => {
const messages = old || []
const optimisticIndex = messages.findIndex((m) => m.id.startsWith('optimistic_user_'))
const optimisticIndex = messages.findIndex((m) => m.info.id.startsWith('optimistic_user_'))
if (optimisticIndex !== -1) {
return messages.slice(0, optimisticIndex)
}
+49 -40
View File
@@ -1,14 +1,14 @@
import { useEffect, useRef, useState, useCallback } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useOpenCodeClient } from './useOpenCode'
import type { SSEEvent, Message } from '@/api/types'
import type { SSEEvent, MessageWithParts } from '@/api/types'
import { showToast } from '@/lib/toast'
import { settingsApi } from '@/api/settings'
import { useSessionStatus } from '@/stores/sessionStatusStore'
import { useSessionTodos } from '@/stores/sessionTodosStore'
import { useMessageParts } from '@/stores/messagePartsStore'
import { sseManager, subscribeToSSE, reconnectSSE, addSSEDirectory } from '@/lib/sseManager'
import { parseOpenCodeError } from '@/lib/opencode-errors'
import { createPartsBatcher } from '@/lib/partsBatcher'
const handleRestartServer = async () => {
showToast.loading('Reloading OpenCode configuration...', {
@@ -51,10 +51,22 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
const [isReconnecting, setIsReconnecting] = useState(false)
const setSessionStatus = useSessionStatus((state) => state.setStatus)
const setSessionTodos = useSessionTodos((state) => state.setTodos)
const setPart = useMessageParts((state) => state.setPart)
const removePart = useMessageParts((state) => state.removePart)
const clearMessage = useMessageParts((state) => state.clearMessage)
const setParts = useMessageParts((state) => state.setParts)
const batcherRef = useRef<ReturnType<typeof createPartsBatcher> | null>(null)
useEffect(() => {
if (!opcodeUrl) {
batcherRef.current?.destroy()
batcherRef.current = null
return
}
batcherRef.current = createPartsBatcher(queryClient, opcodeUrl, directory)
return () => {
batcherRef.current?.destroy()
batcherRef.current = null
}
}, [queryClient, opcodeUrl, directory])
const handleSSEEvent = useCallback((event: SSEEvent) => {
switch (event.type) {
@@ -87,7 +99,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
case 'messagev2.part.updated': {
if (!('part' in event.properties)) break
const { part } = event.properties
setPart(part.messageID, part)
batcherRef.current?.queuePartUpdate(part.sessionID, part)
break
}
@@ -104,25 +116,25 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
}
const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory]
const currentData = queryClient.getQueryData<Message[]>(messagesQueryKey)
const currentData = queryClient.getQueryData<MessageWithParts[]>(messagesQueryKey)
if (!currentData) {
queryClient.invalidateQueries({ queryKey: messagesQueryKey })
return
}
const messageExists = currentData.some(msg => msg.id === info.id)
const messageExists = currentData.some(msgWithParts => msgWithParts.info.id === info.id)
if (!messageExists) {
const filteredData = info.role === 'user'
? currentData.filter(msg => !msg.id.startsWith('optimistic_'))
? currentData.filter(msgWithParts => !msgWithParts.info.id.startsWith('optimistic_'))
: currentData
queryClient.setQueryData(messagesQueryKey, [...filteredData, info])
queryClient.setQueryData(messagesQueryKey, [...filteredData, { info, parts: [] }])
return
}
const updated = currentData.map(msg => {
if (msg.id !== info.id) return msg
return { ...info }
const updated = currentData.map(msgWithParts => {
if (msgWithParts.info.id !== info.id) return msgWithParts
return { ...msgWithParts, info: { ...info } }
})
queryClient.setQueryData(messagesQueryKey, updated)
@@ -135,14 +147,13 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
const { sessionID, messageID } = event.properties
queryClient.setQueryData<Message[]>(
queryClient.setQueryData<MessageWithParts[]>(
['opencode', 'messages', opcodeUrl, sessionID, directory],
(old) => {
if (!old) return old
return old.filter(msg => msg.id !== messageID)
return old.filter(msgWithParts => msgWithParts.info.id !== messageID)
}
)
clearMessage(messageID)
break
}
@@ -150,9 +161,9 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
case 'messagev2.part.removed': {
if (!('sessionID' in event.properties && 'messageID' in event.properties && 'partID' in event.properties)) break
const { messageID, partID } = event.properties
const { sessionID, messageID, partID } = event.properties
removePart(messageID, partID)
batcherRef.current?.queuePartRemoval(sessionID, messageID, partID)
break
}
@@ -176,29 +187,20 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
setSessionStatus(sessionID, { type: 'idle' })
batcherRef.current?.flush()
const messagesQueryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory]
const currentData = queryClient.getQueryData<Message[]>(messagesQueryKey)
const currentData = queryClient.getQueryData<MessageWithParts[]>(messagesQueryKey)
if (!currentData) break
const now = Date.now()
const updated = currentData.map(msg => {
if (msg.role !== 'assistant') return msg
const updated = currentData.map(msgWithParts => {
const msg = msgWithParts.info
if (msg.role !== 'assistant') return msgWithParts
if ('completed' in msg.time && msg.time.completed) return msg
if ('completed' in msg.time && msg.time.completed) return msgWithParts
return {
...msg,
time: { ...msg.time, completed: now }
}
})
queryClient.setQueryData(messagesQueryKey, updated)
const partsStore = useMessageParts.getState()
for (const [messageID, parts] of partsStore.parts) {
if (!parts.some(p => p.sessionID === sessionID)) continue
const updatedParts = parts.map(part => {
const updatedParts = msgWithParts.parts.map(part => {
if (part.type !== 'tool') return part
if (part.state.status !== 'running' && part.state.status !== 'pending') return part
return {
@@ -217,10 +219,17 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
}
})
setParts(messageID, updatedParts)
}
return {
...msgWithParts,
info: {
...msg,
time: { ...msg.time, completed: now }
},
parts: updatedParts
}
})
queryClient.invalidateQueries({ queryKey: messagesQueryKey })
queryClient.setQueryData(messagesQueryKey, updated)
break
}
@@ -286,7 +295,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
default:
break
}
}, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos, setPart, removePart, clearMessage, setParts, currentSessionId])
}, [queryClient, opcodeUrl, directory, setSessionStatus, setSessionTodos, currentSessionId])
const fetchInitialData = useCallback(async () => {
if (!client || !mountedRef.current) return
+32 -20
View File
@@ -1,4 +1,4 @@
import { useMemo } from 'react'
import { useMemo, useRef } from 'react'
import { useMessages } from './useOpenCode'
import type { components } from '@/api/opencode-types'
@@ -6,39 +6,51 @@ type UserMessage = components['schemas']['UserMessage']
const DEFAULT_AGENT = 'plan'
interface SessionAgentResult {
agent: string
model: { providerID: string; modelID: string } | undefined
variant: string | undefined
}
export function useSessionAgent(
opcodeUrl: string | null | undefined,
sessionID: string | undefined,
directory?: string
) {
const { data: messages } = useMessages(opcodeUrl, sessionID, directory)
const prevRef = useRef<SessionAgentResult>({ agent: DEFAULT_AGENT, model: undefined, variant: undefined })
return useMemo(() => {
if (!messages || messages.length === 0) {
return {
agent: DEFAULT_AGENT,
model: undefined as { providerID: string; modelID: string } | undefined,
variant: undefined as string | undefined,
}
}
let agent = DEFAULT_AGENT
let model: { providerID: string; modelID: string } | undefined
let variant: string | undefined
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
if (msg.role === 'user') {
const userInfo = msg as UserMessage
return {
agent: userInfo.agent || DEFAULT_AGENT,
model: userInfo.model,
variant: userInfo.variant,
if (messages && messages.length > 0) {
for (let i = messages.length - 1; i >= 0; i--) {
const msgWithParts = messages[i]
if (msgWithParts.info.role === 'user') {
const userInfo = msgWithParts.info as UserMessage
agent = userInfo.agent || DEFAULT_AGENT
model = userInfo.model
variant = userInfo.variant
break
}
}
}
return {
agent: DEFAULT_AGENT,
model: undefined,
variant: undefined,
const prev = prevRef.current
if (
prev.agent === agent &&
prev.variant === variant &&
prev.model?.providerID === model?.providerID &&
prev.model?.modelID === model?.modelID
) {
return prev
}
const next: SessionAgentResult = { agent, model, variant }
prevRef.current = next
return next
}, [messages])
}
+4 -8
View File
@@ -1,8 +1,7 @@
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createOpenCodeClient } from '@/api/opencode'
import { showToast } from '@/lib/toast'
import type { Message } from '@/api/types'
import { useMessageParts } from '@/stores/messagePartsStore'
import type { MessageWithParts } from '@/api/types'
interface UseUndoMessageOptions {
opcodeUrl: string | null
@@ -12,7 +11,7 @@ interface UseUndoMessageOptions {
}
interface UndoMessageContext {
previousMessages?: Message[]
previousMessages?: MessageWithParts[]
}
export function useUndoMessage({
@@ -22,7 +21,6 @@ export function useUndoMessage({
onSuccess
}: UseUndoMessageOptions) {
const queryClient = useQueryClient()
const clearMessage = useMessageParts((state) => state.clearMessage)
return useMutation<string, Error, { messageID: string; messageContent: string }, UndoMessageContext>({
mutationFn: async ({ messageID, messageContent }: { messageID: string, messageContent: string }) => {
@@ -37,18 +35,16 @@ export function useUndoMessage({
await queryClient.cancelQueries({ queryKey })
const previousMessages = queryClient.getQueryData<Message[]>(queryKey)
const previousMessages = queryClient.getQueryData<MessageWithParts[]>(queryKey)
if (previousMessages) {
const messageIndex = previousMessages.findIndex(m => m.id === messageID)
const messageIndex = previousMessages.findIndex(m => m.info.id === messageID)
if (messageIndex !== -1) {
const newMessages = previousMessages.slice(0, messageIndex)
queryClient.setQueryData(queryKey, newMessages)
}
}
clearMessage(messageID)
return { previousMessages }
},
onError: (_error, _variables, _context: UndoMessageContext | undefined) => {
+119
View File
@@ -0,0 +1,119 @@
import type { QueryClient } from '@tanstack/react-query'
import type { Part, MessageWithParts } from '@/api/types'
interface PartsBatcher {
queuePartUpdate: (sessionID: string, part: Part) => void
queuePartRemoval: (sessionID: string, messageID: string, partID: string) => void
flush: () => void
destroy: () => void
}
export function createPartsBatcher(
queryClient: QueryClient,
opcodeUrl: string,
directory?: string
): PartsBatcher {
const pendingUpserts = new Map<string, Map<string, Part>>()
const pendingRemovals = new Map<string, Map<string, Set<string>>>()
let pendingFrameId: number | null = null
const scheduleFlush = () => {
if (pendingFrameId !== null) return
pendingFrameId = requestAnimationFrame(() => {
pendingFrameId = null
flush()
})
}
const flush = () => {
if (pendingUpserts.size === 0 && pendingRemovals.size === 0) return
const sessionsToUpdate = new Set([
...pendingUpserts.keys(),
...pendingRemovals.keys(),
])
for (const sessionID of sessionsToUpdate) {
const queryKey = ['opencode', 'messages', opcodeUrl, sessionID, directory]
const currentData = queryClient.getQueryData<MessageWithParts[]>(queryKey)
if (!currentData) continue
let updatedData = [...currentData]
const sessionUpserts = pendingUpserts.get(sessionID)
const sessionRemovals = pendingRemovals.get(sessionID)
updatedData = updatedData.map((msgWithParts) => {
let msgParts = [...msgWithParts.parts]
if (sessionRemovals?.has(msgWithParts.info.id)) {
const partIDsToRemove = sessionRemovals.get(msgWithParts.info.id)!
msgParts = msgParts.filter((p) => !partIDsToRemove.has(p.id))
}
if (sessionUpserts) {
const partsForMessage = Array.from(sessionUpserts.values()).filter(
(part) => part.messageID === msgWithParts.info.id
)
for (const part of partsForMessage) {
const existingIdx = msgParts.findIndex((p) => p.id === part.id)
if (existingIdx >= 0) {
msgParts[existingIdx] = part
} else {
msgParts.push(part)
}
}
}
return {
...msgWithParts,
parts: msgParts,
}
})
queryClient.setQueryData(queryKey, updatedData)
}
pendingUpserts.clear()
pendingRemovals.clear()
}
const queuePartUpdate = (sessionID: string, part: Part) => {
if (!pendingUpserts.has(sessionID)) {
pendingUpserts.set(sessionID, new Map())
}
const sessionUpserts = pendingUpserts.get(sessionID)!
sessionUpserts.set(part.id, part)
scheduleFlush()
}
const queuePartRemoval = (sessionID: string, messageID: string, partID: string) => {
if (!pendingRemovals.has(sessionID)) {
pendingRemovals.set(sessionID, new Map())
}
const sessionRemovals = pendingRemovals.get(sessionID)!
if (!sessionRemovals.has(messageID)) {
sessionRemovals.set(messageID, new Set())
}
const messageRemovals = sessionRemovals.get(messageID)!
messageRemovals.add(partID)
scheduleFlush()
}
const destroy = () => {
if (pendingFrameId !== null) {
cancelAnimationFrame(pendingFrameId)
pendingFrameId = null
}
pendingUpserts.clear()
pendingRemovals.clear()
}
return {
queuePartUpdate,
queuePartRemoval,
flush,
destroy,
}
}
+19 -18
View File
@@ -28,13 +28,12 @@ import { useTTS } from "@/hooks/useTTS";
import { useEffect, useRef, useCallback, useMemo } from "react";
import { MessageSkeleton } from "@/components/message/MessageSkeleton";
import { exportSession, downloadMarkdown } from "@/lib/exportSession";
import { useMessageParts, usePartsVersion } from "@/stores/messagePartsStore";
import type { MessageWithParts } from "@/api/types";
import { showToast } from "@/lib/toast";
import { getRepoDisplayName } from "@/lib/utils";
import { RepoMcpDialog } from "@/components/repo/RepoMcpDialog";
import { createOpenCodeClient } from "@/api/opencode";
import { useSessionStatus } from "@/stores/sessionStatusStore";
import { useSessionStatus, useSessionStatusForSession } from "@/stores/sessionStatusStore";
import { useQuestions } from "@/contexts/EventContext";
import { QuestionPrompt } from "@/components/session/QuestionPrompt";
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
@@ -98,25 +97,18 @@ export function SessionDetail() {
if (!rawMessages) return undefined
const revertMessageID = session?.revert?.messageID
if (!revertMessageID) return rawMessages
return rawMessages.filter(msg => compareMessageIds(msg.id, revertMessageID) < 0)
return rawMessages.filter(msgWithParts => compareMessageIds(msgWithParts.info.id, revertMessageID) < 0)
}, [rawMessages, session?.revert?.messageID]);
const getMessagesWithParts = useCallback((): MessageWithParts[] | undefined => {
if (!messages) return undefined
const partsMap = useMessageParts.getState().parts
return messages.map(msg => ({
info: msg,
parts: partsMap.get(msg.id) || []
}))
return messages
}, [messages])
const partsVersion = usePartsVersion()
const { scrollToBottom } = useAutoScroll({
containerRef: messageContainerRef,
messages,
messages: messages?.map(m => m.info),
sessionId,
contentVersion: partsVersion,
contentVersion: messages?.reduce((sum, m) => sum + m.parts.length, 0) ?? 0,
onScrollStateChange: setShowScrollButton
});
@@ -132,6 +124,16 @@ export function SessionDetail() {
const setSessionStatus = useSessionStatus((state) => state.setStatus);
const { current: currentQuestion, reply: replyToQuestion, reject: rejectQuestion } = useQuestions();
const sessionStatus = useSessionStatusForSession(sessionId);
const isSessionActive = sessionStatus.type === 'busy' || sessionStatus.type === 'retry';
const lastAssistantMessage = messages?.filter(m => m.info.role === 'assistant').at(-1);
const hasIncompleteMessages = lastAssistantMessage ? !('completed' in lastAssistantMessage.info.time && lastAssistantMessage.info.time.completed) : false;
const hasActiveStream = hasIncompleteMessages && isSessionActive;
const handleShowModelsDialog = useCallback(() => setModelDialogOpen(true), []);
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
const handleShowHelpDialog = useCallback(() => openSettings(), [openSettings]);
const handleNewSession = useCallback(async () => {
try {
const newSession = await createSession.mutateAsync({ agent: undefined });
@@ -480,12 +482,11 @@ export function SessionDetail() {
sessionID={sessionId}
disabled={!isConnected}
showScrollButton={showScrollButton}
hasActiveStream={hasActiveStream}
onScrollToBottom={scrollToBottom}
onShowModelsDialog={() => setModelDialogOpen(true)}
onShowSessionsDialog={() => setSessionsDialogOpen(true)}
onShowHelpDialog={() => {
openSettings()
}}
onShowModelsDialog={handleShowModelsDialog}
onShowSessionsDialog={handleShowSessionsDialog}
onShowHelpDialog={handleShowHelpDialog}
onToggleDetails={handleToggleDetails}
onExportSession={handleExportSession}
onPromptChange={setHasPromptContent}
-99
View File
@@ -1,99 +0,0 @@
import { create } from 'zustand'
import type { Part } from '@/api/types'
const EMPTY_PARTS: Part[] = []
interface MessagePartsStore {
parts: Map<string, Part[]>
version: number
setPart: (messageID: string, part: Part) => void
setParts: (messageID: string, parts: Part[]) => void
removePart: (messageID: string, partID: string) => void
clearMessage: (messageID: string) => void
clearSession: (sessionID: string) => void
initFromMessages: (messages: Array<{ info: { id: string }, parts: Part[] }>) => void
}
export const useMessageParts = create<MessagePartsStore>((set) => ({
parts: new Map(),
version: 0,
setPart: (messageID, part) => {
set((state) => {
const newMap = new Map(state.parts)
const existing = newMap.get(messageID)
if (!existing) {
newMap.set(messageID, [part])
return { parts: newMap, version: state.version + 1 }
}
const idx = existing.findIndex(p => p.id === part.id)
if (idx >= 0) {
const updated = [...existing]
updated[idx] = part
newMap.set(messageID, updated)
} else {
newMap.set(messageID, [...existing, part])
}
return { parts: newMap, version: state.version + 1 }
})
},
setParts: (messageID, parts) => {
set((state) => {
const newMap = new Map(state.parts)
newMap.set(messageID, parts)
return { parts: newMap, version: state.version + 1 }
})
},
removePart: (messageID, partID) => {
set((state) => {
const existing = state.parts.get(messageID)
if (!existing) return state
const newMap = new Map(state.parts)
newMap.set(messageID, existing.filter(p => p.id !== partID))
return { parts: newMap, version: state.version + 1 }
})
},
clearMessage: (messageID) => {
set((state) => {
const newMap = new Map(state.parts)
newMap.delete(messageID)
return { parts: newMap, version: state.version + 1 }
})
},
clearSession: (sessionID) => {
set((state) => {
const newMap = new Map(state.parts)
for (const [, parts] of newMap) {
if (parts.some(p => p.sessionID === sessionID)) {
newMap.delete(sessionID)
}
}
return { parts: newMap, version: state.version + 1 }
})
},
initFromMessages: (messages) => {
set((state) => {
const newMap = new Map(state.parts)
for (const msg of messages) {
newMap.set(msg.info.id, msg.parts)
}
return { parts: newMap, version: state.version + 1 }
})
},
}))
export const usePartsForMessage = (messageID: string | undefined): Part[] => {
return useMessageParts((state) => {
if (!messageID) return EMPTY_PARTS
return state.parts.get(messageID) ?? EMPTY_PARTS
})
}
export const usePartsVersion = (): number => {
return useMessageParts((state) => state.version)
}