perf: harden sync architecture and modularize runtimes (#803)
* fix: added desktop app background throttling
* perf: add streaming debug metrics panel
- Show streaming performance metrics in the debug panel
- Auto-enable stream profiling while the panel is open
- Add JSON export for sharing UI and VS Code metrics
* perf: batch streaming updates more aggressively
- Buffer message deltas and metadata updates to cut render churn
- Skip no-op part updates before they touch the message store
- Fix the desktop debug panel shortcut binding
* perf: split streaming event handling and coalesce deltas
- Move streaming content events onto a dedicated fast path
- Defer non-critical stream side effects off the hot path
- Merge repeated message delta events before they reach the UI
* perf: isolate streaming rows from chat rerenders
- Memoize chat rows against render-relevant message changes only
- Read live assistant text directly from store to narrow streaming updates
- Split the active streaming entry from the stable message list path
* perf: streamline chat streaming and SSE proxying
- Reduce chat rerenders around the active streaming path
- Simplify server SSE forwarding to avoid duplicate proxy work
* fix: preserve the first streaming text chunk
- Show the initial text chunk immediately before batched deltas arrive
- Bypass batching for the first text or reasoning part update
- Keep later streaming updates buffered for performance
* perf: align streaming/render hot paths with opencode parity
* perf: harden turn/cache stability and stale delta suppression
* fix: stabilize chat rendering and disable timeline interactions
- Disabled timeline dialog access from shortcuts, commands, and chat input
- Reduced chat render churn by simplifying message list and turn staging behavior
- Improved session-switch stability to prevent update-depth crashes
* perf: track static message rerenders during streaming
* perf: reduce sorted-mode activity rerender fanout
* perf: reduce chat rerender fanout and add active-turn metrics
- Reduced sorted-mode rerender coupling by tightening turn context propagation
- Added a metric for static rerenders outside the active turn during streaming
- Exposed new chat render counters in the debug panel for parity tracking
* fix: keep sorted activity mounted while stream grows
* fix: stabilize session and history scroll rendering
* refactor: decouple server routes from index
* refactor: extract fs module from server index
* refactor: move opencode route ownership into module
* refactor: extract notification route registration
* refactor: extract opencode and notification runtimes from index
* refactor: extract settings runtime and complete server modularization pass
* refactor: modularize server config, skills, icons, and tunnel routes
* refactor: extract server modules from monolithic index.js
Split proxy, routes, runtime helpers, and notification emitter
into dedicated modules under packages/web/server/lib/.
* refactor: replace session/message stores with SSE-driven sync layer
Delete ~9200 lines of old architecture (useEventStream, messageStore,
sessionStore, useSessionStore, questionStore, useTodoStore, client SSE).
New sync layer: event pipeline with coalescing + 16ms flush, pure event
reducer, per-directory child stores with LRU eviction, cursor pagination,
optimistic updates, deferred timeline staging, text throttle.
Migrate all UI consumers to sync hooks (useSessionMessages,
useSessionMessageRecords, useSessionStatus, useSessionPermissions, etc).
Strip session-ui-store to UI-only state, delegate SDK ops to
session-actions with abort-if-busy, optimistic store updates, and
response merging for revert/fork/archive/delete.
Add notification-store for SSE-driven session attention tracking,
cross-directory GlobalSessionStatusStore for sidebar indicators,
client-side diff snapshot sanitization to prevent memory bloat,
and revert message filtering via useVisibleSessionMessages.
* feat: notification store, session actions, activity detection
Add notification-store.ts for SSE-driven attention tracking.
Add sanitize.ts to strip diff snapshot memory bloat.
Add session-actions.ts with optimistic revert/fork/archive/delete.
Improve useSessionActivity with incomplete-message fallback.
Delete useServerSessionStatus polling hook.
* fix: add directory param to all SDK calls, fix command/shell/abort routing
All SDK calls in session-actions.ts now pass directory parameter —
required by OpenCode server to scope session operations. Without it,
abort, commands, revert, fork, and other operations returned 500.
Add routeMessage() in session-ui-store for shell mode (session.shell),
slash commands (session.command), and normal prompts. Command lookup
checks both sync child store and useCommandsStore. Handle /compact
locally via session.summarize().
Implement getContextUsage() to restore header context usage display —
reads token counts from last assistant message in sync store.
* refactor: replace custom API proxy with http-proxy-middleware
Remove ~280 lines of custom proxy code: forwardSseRequest,
forwardGenericApiRequest, collectRequestBodyBuffer, header
manipulation, hop-by-hop filtering, SSE block buffering.
Replace with single createProxyMiddleware() call that handles
SSE streaming, large bodies, and timeouts out of the box.
Dynamic router for OpenCode port changes after restarts.
Auth headers injected via proxyReq hook.
Keep: readiness gate, Windows session merge, API prefix detection.
* perf: targeted event draft cloning to fix streaming render cascade
Event handler was eagerly cloning all state slices on every event,
breaking Zustand selector referential equality. During streaming
(~60 events/sec), this caused every subscriber to re-render regardless
of which slice actually changed.
Now only clones fields the specific event type mutates. Also extracts
StatusRowContainer to isolate high-frequency useAssistantStatus
subscription, removes dead messageStreamStatesMap subscription from
ChatContainer, and narrows useAssistantStatus to only track last
assistant message parts.
MessageList renders: 1972 → 296 per streaming session (-85%).
* fix: null safety for sync state slices
Add defensive ?? {} guards on permission, question, session_status,
and message record access. Prevents crashes when child store state
is partially initialized during bootstrap.
* perf: dedup inflight SDK calls, extract concurrency util, delay PR tracking
Extract mapWithConcurrency to shared lib/concurrency.ts. Add in-flight
dedup for loadProviders/loadAgents to prevent concurrent duplicate SDK
calls. Delay initial PR background tracking by 5s to reduce startup
CPU burst.
* fix: header session lookup across all child stores
Session title and context panel click failed when session belonged to
a different directory than the current child store. Fall back to
getAllSyncSessions() to search all initialized stores.
* chore: bump @opencode-ai/sdk to 1.3.5
* docs: add sync event handling guide
* Optimize session prefetch and improve delete/archive UX
- Add settlement delay to session prefetch to avoid race conditions on
rapid session switches
- Reduce git diff prefetch and session cache limits for better performance
- Implement optimistic UI updates for session delete/archive operations
with proper rollback on failure
- Wire session prefetch hook into SessionSidebar with sync integration
* Add file content cache and sync optimizations
- Wrap FilesAPI with in-memory LRU cache for file content with dual
constraints (entry count and byte size)
- Optimize chat timeline scroll restoration using useLayoutEffect
- Preserve React references in message and part arrays to prevent
unnecessary re-renders when prepending history
- Add session prefetch TTL cache to prevent redundant fetches
- Integrate session prefetch cache clearing with eviction flow
* Improve session sidebar error handling and add diff prefetch filtering
Load active and archived sessions independently using Promise.allSettled
to prevent one failure from blocking the other. Add retry logic to session
API calls and skip large files during diff prefetch to improve performance.
* Replace sendMessage with optimisticSend wrapper
Introduces optimistic UI updates for normal chat messages to provide
instant feedback. Messages appear immediately in the UI while the API
call executes in the background, with automatic rollback on errors.
* perf: split stores, proper optimistic send, fix revert/directory bugs
- split session-ui-store into voice/input/selection/viewport stores
to reduce subscriber re-evaluation during streaming
- wire optimisticSend through useSync shadow Map infrastructure
matching OpenCode's pattern (no heuristic part detection)
- port OpenCode Identifier.ascending ID format for correct sorting
- pass messageID to promptAsync to prevent duplicate messages
- fix worktree directory not propagating to session actions
(dynamic dir() via opencodeClient.getDirectory)
- fix setCurrentSession accepting directoryHint for new sessions
- fix revert not hiding messages (session limit was 5, bumped to match loaded count)
- fix revert optimistic message removal from store
- fix load-more flicker (useLayoutEffect scroll compensation)
- add prefetch TTL cache, file content LRU cache
- add session prefetch for adjacent sessions
- add instant archive/delete (optimistic before SDK call)
- migrate legacy window.__zustand_session_store__ to session-ui-store
- add retry + independent error handling for archived sessions
- add AGENTS.md performance rules
* perf: startup optimization — dedup, caching, light git status, diff rendering gates
- defer diff prefetch to git tab open, reduce concurrency 4→2, skip >500 changed lines
- cap project git checks concurrency (2), directory status probe (3)
- dedup provider/agent loading, github auth, worktree list (in-flight + TTL caches)
- delay PR tracking 5s, cache 403 search failures per-repo
- coalesce settings PUT (200ms debounce), cache settings GET (2s TTL)
- cache canonical directory resolution (60s TTL)
- persist missing directory status to localStorage (10min TTL)
- light/heavy git status: polling skips numstat+line counting+rev-list
- large diff rendering gate (>500 lines → "render anyway" button)
- tokenization degradation for >500KB files in Pierre
- parallelize main.tsx pre-render awaits
- batch sidebar file tree expanded paths restoration (3 at a time)
- remove bare useConfigStore() subscription in AgentsPage
- sync worktree sandboxes to OpenCode SQLite DB
- fix RightSidebarTabs ternary → explicit tab matching
- defensive guards on sync state (session_status, permission, question, message)
* fix: add defensive guards on remaining sync state field accesses
guard session_status, permission, message, todo, part, config with ?? {}
in useDirectorySync selectors, session-cache, and bootstrap
* fix: add missing directory dep to useCallback in use-sync.ts
* fix: preserve diffStats when light-mode polling overwrites status
* perf: optimize startup git status polling and diff rendering
Preserves diff stats when lightweight polling updates repository status
Reduces startup overhead with smarter git polling and store updates
Adds detailed optimization and migration docs for next performance steps
* fix: keep chat diff stats stable during git status updates
Prevents lightweight git polling from dropping diff statistics
Keeps MessageList diff indicators consistent while status refreshes
Improves reliability of git-aware chat rendering
* fix: user animation replay, queued message variant, startup provider loading
- consume animation ID after first play to prevent re-animation
on neighbor assistant message completion
- capture send config (model/agent/variant) at queue time matching
OpenCode's FollowupDraft pattern instead of re-resolving at send time
- replace one-shot startup recovery effect with polling interval
that retries every 2s until providers and agents load
- fix optimistic bridge to avoid re-render loop (stable ref wrappers)
* chore: update tauri to 2.10.3 and all plugins to latest
- tauri 2.9.4 → 2.10.3
- tauri-build 2.5.3 → 2.5.6
- tauri-plugin-dialog 2.4.2 → 2.6.0
- tauri-plugin-log 2.7.1 → 2.8.0
- tauri-plugin-shell 2.3.3 → 2.3.5
- tauri-plugin-updater 2 (floating) → 2.10.0 (pinned)
- @tauri-apps/api ^2.9.0 → ^2.10.1
- wry 0.53.5 → 0.54.4 (transitive)
* refactor: decouple web server index orchestration runtimes
* fix: align VS Code runtime behavior with web and reduce draft view CPU load
- Queue VS Code bridge and SSE startup requests until API readiness to avoid false bootstrap failures
- Make agent manager actions directory-aware and remove real worktrees with safer partial-failure handling
- Replace heavy logo animation path with a lightweight pulse to cut draft-session CPU usage
* fix: restore auto-selected file sending in chat input
- Send server-selected files as proper file URLs in the message payload
- Include server-backed attachments in submit flow instead of dropping them
- Restore queued-message attachments through the refactored input store
* fix: restore session model selection consistently on session switch
- Restore agent, model, and variant from the latest loaded user message for each session
- Wait for session messages before applying restored selections to avoid stale or missing state
- Remove legacy session-choice inference paths that caused overlap and instability
* fix: restore permission replies and auto-accept across sessions
- Scope permission and question replies to the target session directory so answers take effect reliably
- Make permission auto-accept immediately handle pending requests and react to new permission prompts
- Keep parent-session handling working for child-session requests through the shared response path
* feat: add reusable fuzzy branch fuzzy-search helper and dialog integration (#798)
* feat: add reusable fuzzy branch search for worktrees
* chore: drop planning docs from feature branch
* feat: make worktree branch refresh manual
* feat: add configurable session retention action
* refactor: centralize global session state in ui store
* fix: cancel debounced permission push after reply
* docs: clarify global and directory session store architecture
* docs: refine agent development rules and session activity guidance
- Clarify agent code of conduct and durable development patterns
- Add explicit shared-store rerender and live-state guidance
- Narrow session activity fallback to avoid stale working state
* chore: updated .gitignore
---------
Co-authored-by: Iuliia Ivashko <yulia.ivashko@gmail.com>
This commit is contained in:
committed by
GitHub
co-authored by
Iuliia Ivashko
parent
8dfe833faf
commit
c9e31a0e6c
@@ -1,10 +1,8 @@
|
||||
import React from 'react';
|
||||
import { RiArrowLeftLine } from '@remixicon/react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import type { Message, Part } from '@opencode-ai/sdk/v2';
|
||||
|
||||
import { ChatInput } from './ChatInput';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import ChatEmptyState from './ChatEmptyState';
|
||||
@@ -14,10 +12,10 @@ import { ScrollShadow } from '@/components/ui/ScrollShadow';
|
||||
import { useChatScrollManager } from '@/hooks/useChatScrollManager';
|
||||
import { useChatTimelineController } from './hooks/useChatTimelineController';
|
||||
import { useChatTurnNavigation } from './hooks/useChatTurnNavigation';
|
||||
import { useTimelineStaging } from '@/hooks/useTimelineStaging';
|
||||
import { useDeviceInfo } from '@/lib/device';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { OverlayScrollbar } from '@/components/ui/OverlayScrollbar';
|
||||
import { TimelineDialog } from './TimelineDialog';
|
||||
import type { PermissionRequest } from '@/types/permission';
|
||||
import type { QuestionRequest } from '@/types/question';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -26,6 +24,19 @@ import {
|
||||
flattenBlockingRequests,
|
||||
} from './lib/blockingRequests';
|
||||
|
||||
// New sync system imports
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useViewportStore } from '@/sync/viewport-store';
|
||||
import { useStreamingStore } from '@/sync/streaming';
|
||||
import {
|
||||
useSessionMessageRecords,
|
||||
useSessions,
|
||||
useDirectorySync,
|
||||
useSessionStatus,
|
||||
} from '@/sync/sync-context';
|
||||
import { useSync } from '@/sync/use-sync';
|
||||
import { getAllSyncSessions } from '@/sync/sync-refs';
|
||||
|
||||
const EMPTY_MESSAGES: Array<{ info: Message; parts: Part[] }> = [];
|
||||
const EMPTY_PERMISSIONS: PermissionRequest[] = [];
|
||||
const EMPTY_QUESTIONS: QuestionRequest[] = [];
|
||||
@@ -71,101 +82,97 @@ const HYDRATING_SKELETON_ITEMS: Array<{
|
||||
];
|
||||
|
||||
export const ChatContainer: React.FC = () => {
|
||||
const {
|
||||
currentSessionId,
|
||||
loadMessages,
|
||||
loadMoreMessages,
|
||||
updateViewportAnchor,
|
||||
openNewSessionDraft,
|
||||
setCurrentSession,
|
||||
newSessionDraft,
|
||||
} = useSessionStore(
|
||||
useShallow((state) => ({
|
||||
currentSessionId: state.currentSessionId,
|
||||
loadMessages: state.loadMessages,
|
||||
loadMoreMessages: state.loadMoreMessages,
|
||||
updateViewportAnchor: state.updateViewportAnchor,
|
||||
openNewSessionDraft: state.openNewSessionDraft,
|
||||
setCurrentSession: state.setCurrentSession,
|
||||
newSessionDraft: state.newSessionDraft,
|
||||
}))
|
||||
// Session UI state
|
||||
const currentSessionId = useSessionUIStore((s) => s.currentSessionId);
|
||||
const openNewSessionDraft = useSessionUIStore((s) => s.openNewSessionDraft);
|
||||
const setCurrentSession = useSessionUIStore((s) => s.setCurrentSession);
|
||||
const newSessionDraft = useSessionUIStore((s) => s.newSessionDraft);
|
||||
const updateViewportAnchor = useViewportStore((s) => s.updateViewportAnchor);
|
||||
const isSyncing = useViewportStore((s) => s.isSyncing);
|
||||
const sessionMemoryStateMap = useViewportStore((s) => s.sessionMemoryState);
|
||||
|
||||
// Sync actions
|
||||
const sync = useSync();
|
||||
const loadMessages = React.useCallback(
|
||||
(sessionId: string) => sync.syncSession(sessionId),
|
||||
[sync],
|
||||
);
|
||||
const loadMoreMessages = React.useCallback(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
(sessionId: string, _direction: 'up' | 'down') => sync.loadMore(sessionId),
|
||||
[sync],
|
||||
);
|
||||
|
||||
const { isSyncing, messageStreamStates, sessionMemoryStateMap } = useSessionStore(
|
||||
useShallow((state) => ({
|
||||
isSyncing: state.isSyncing,
|
||||
messageStreamStates: state.messageStreamStates,
|
||||
sessionMemoryStateMap: state.sessionMemoryState,
|
||||
}))
|
||||
);
|
||||
// UI store
|
||||
const { isExpandedInput, stickyUserHeader, chatRenderMode } = useUIStore();
|
||||
|
||||
const {
|
||||
isTimelineDialogOpen,
|
||||
setTimelineDialogOpen,
|
||||
isExpandedInput,
|
||||
stickyUserHeader,
|
||||
chatRenderMode,
|
||||
} = useUIStore();
|
||||
|
||||
const sessionMessages = useSessionStore(
|
||||
// Streaming state
|
||||
const streamingMessageId = useStreamingStore(
|
||||
React.useCallback(
|
||||
(state) => (currentSessionId ? state.messages.get(currentSessionId) ?? EMPTY_MESSAGES : EMPTY_MESSAGES),
|
||||
[currentSessionId]
|
||||
)
|
||||
(s) => (currentSessionId ? s.streamingMessageIds.get(currentSessionId) ?? null : null),
|
||||
[currentSessionId],
|
||||
),
|
||||
);
|
||||
// Messages from sync system
|
||||
const sessionMessageRecords = useSessionMessageRecords(currentSessionId ?? '');
|
||||
const sessionMessages = currentSessionId ? sessionMessageRecords : EMPTY_MESSAGES;
|
||||
|
||||
// Sessions from sync system
|
||||
const sessions = useSessions();
|
||||
|
||||
// Session status from sync system
|
||||
const sessionStatusForCurrent = useSessionStatus(currentSessionId ?? '') ?? IDLE_SESSION_STATUS;
|
||||
|
||||
// Permissions & questions from sync system
|
||||
const allPermissions = useDirectorySync(
|
||||
React.useCallback((s) => s.permission ?? {}, []),
|
||||
);
|
||||
const allQuestions = useDirectorySync(
|
||||
React.useCallback((s) => s.question ?? {}, []),
|
||||
);
|
||||
|
||||
const sessions = useSessionStore((state) => state.sessions);
|
||||
// Convert Record → Map for blockingRequests helpers
|
||||
const permissionsMap = React.useMemo(() => {
|
||||
const m = new Map<string, PermissionRequest[]>();
|
||||
for (const [k, v] of Object.entries(allPermissions)) m.set(k, v as PermissionRequest[]);
|
||||
return m;
|
||||
}, [allPermissions]);
|
||||
|
||||
const blockingRequestState = useSessionStore(
|
||||
useShallow((state) => ({
|
||||
sessions: state.sessions,
|
||||
permissions: state.permissions,
|
||||
questions: state.questions,
|
||||
}))
|
||||
);
|
||||
const questionsMap = React.useMemo(() => {
|
||||
const m = new Map<string, QuestionRequest[]>();
|
||||
for (const [k, v] of Object.entries(allQuestions)) m.set(k, v as QuestionRequest[]);
|
||||
return m;
|
||||
}, [allQuestions]);
|
||||
|
||||
const scopedSessionIds = React.useMemo(
|
||||
() => collectVisibleSessionIdsForBlockingRequests(
|
||||
blockingRequestState.sessions.map((session) => ({ id: session.id, parentID: session.parentID })),
|
||||
sessions.map((session) => ({ id: session.id, parentID: session.parentID })),
|
||||
currentSessionId,
|
||||
),
|
||||
[blockingRequestState.sessions, currentSessionId]
|
||||
[sessions, currentSessionId],
|
||||
);
|
||||
|
||||
const sessionPermissions = React.useMemo(() => {
|
||||
if (scopedSessionIds.length === 0) return EMPTY_PERMISSIONS;
|
||||
return flattenBlockingRequests(blockingRequestState.permissions, scopedSessionIds);
|
||||
}, [blockingRequestState.permissions, scopedSessionIds]);
|
||||
return flattenBlockingRequests(permissionsMap, scopedSessionIds);
|
||||
}, [permissionsMap, scopedSessionIds]);
|
||||
|
||||
const sessionQuestions = React.useMemo(() => {
|
||||
if (scopedSessionIds.length === 0) return EMPTY_QUESTIONS;
|
||||
return flattenBlockingRequests(blockingRequestState.questions, scopedSessionIds);
|
||||
}, [blockingRequestState.questions, scopedSessionIds]);
|
||||
return flattenBlockingRequests(questionsMap, scopedSessionIds);
|
||||
}, [questionsMap, scopedSessionIds]);
|
||||
|
||||
const historyMeta = useSessionStore(
|
||||
React.useCallback(
|
||||
(state) => (currentSessionId ? state.sessionHistoryMeta.get(currentSessionId) ?? null : null),
|
||||
[currentSessionId]
|
||||
)
|
||||
);
|
||||
// History metadata — use sync's hasMore/isLoading
|
||||
const historyMeta = React.useMemo(() => {
|
||||
if (!currentSessionId) return null;
|
||||
return {
|
||||
limit: sessionMessages.length,
|
||||
complete: !sync.hasMore(currentSessionId),
|
||||
loading: sync.isLoading(currentSessionId),
|
||||
};
|
||||
}, [currentSessionId, sessionMessages.length, sync]);
|
||||
|
||||
const streamingMessageId = useSessionStore(
|
||||
React.useCallback(
|
||||
(state) => (currentSessionId ? state.streamingMessageIds.get(currentSessionId) ?? null : null),
|
||||
[currentSessionId]
|
||||
)
|
||||
);
|
||||
|
||||
const sessionStatusForCurrent = useSessionStore(
|
||||
React.useCallback(
|
||||
(state) => (currentSessionId ? state.sessionStatus?.get(currentSessionId) ?? IDLE_SESSION_STATUS : IDLE_SESSION_STATUS),
|
||||
[currentSessionId]
|
||||
)
|
||||
);
|
||||
|
||||
const hasSessionMessagesEntry = useSessionStore(
|
||||
React.useCallback((state) => (currentSessionId ? state.messages.has(currentSessionId) : false), [currentSessionId])
|
||||
);
|
||||
const hasSessionMessagesEntry = sessionMessages.length > 0 || (currentSessionId ? sync.hasMore(currentSessionId) : false);
|
||||
|
||||
const { isMobile } = useDeviceInfo();
|
||||
const draftOpen = Boolean(newSessionDraft?.open);
|
||||
@@ -173,24 +180,18 @@ export const ChatContainer: React.FC = () => {
|
||||
const messageListRef = React.useRef<MessageListHandle | null>(null);
|
||||
|
||||
const parentSession = React.useMemo(() => {
|
||||
if (!currentSessionId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!currentSessionId) return null;
|
||||
const current = sessions.find((session) => session.id === currentSessionId);
|
||||
const parentID = current?.parentID;
|
||||
if (!parentID) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return sessions.find((session) => session.id === parentID) ?? null;
|
||||
if (!parentID) return null;
|
||||
return sessions.find((session) => session.id === parentID)
|
||||
?? getAllSyncSessions().find((session) => session.id === parentID)
|
||||
?? null;
|
||||
}, [currentSessionId, sessions]);
|
||||
|
||||
const handleReturnToParentSession = React.useCallback(() => {
|
||||
if (!parentSession) {
|
||||
return;
|
||||
}
|
||||
void setCurrentSession(parentSession.id);
|
||||
if (!parentSession) return;
|
||||
setCurrentSession(parentSession.id);
|
||||
}, [parentSession, setCurrentSession]);
|
||||
|
||||
const returnToParentButton = parentSession ? (
|
||||
@@ -219,13 +220,15 @@ export const ChatContainer: React.FC = () => {
|
||||
}, [sessionPermissions, sessionQuestions]);
|
||||
|
||||
const activeTurnChangeRef = React.useRef<(turnId: string | null) => void>(() => {});
|
||||
const handleActiveTurnChange = React.useCallback((turnId: string | null) => {
|
||||
activeTurnChangeRef.current(turnId);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
scrollRef,
|
||||
handleMessageContentChange,
|
||||
getAnimationHandlers,
|
||||
scrollToBottom,
|
||||
releasePinnedScroll,
|
||||
isPinned,
|
||||
isOverflowing,
|
||||
isProgrammaticFollowActive,
|
||||
@@ -238,16 +241,20 @@ export const ChatContainer: React.FC = () => {
|
||||
isSyncing,
|
||||
isMobile,
|
||||
chatRenderMode,
|
||||
messageStreamStates,
|
||||
sessionPermissions: sessionBlockingCards,
|
||||
onActiveTurnChange: (turnId) => {
|
||||
activeTurnChangeRef.current(turnId);
|
||||
},
|
||||
onActiveTurnChange: handleActiveTurnChange,
|
||||
});
|
||||
|
||||
// Deferred timeline staging — renders 1 message on first paint,
|
||||
// adds 3 per rAF frame to avoid blocking.
|
||||
const { stagedMessages } = useTimelineStaging({
|
||||
sessionKey: currentSessionId ?? '',
|
||||
messages: sessionMessages,
|
||||
});
|
||||
|
||||
const timelineController = useChatTimelineController({
|
||||
sessionId: currentSessionId,
|
||||
messages: sessionMessages,
|
||||
messages: stagedMessages,
|
||||
historyMeta,
|
||||
scrollRef,
|
||||
messageListRef,
|
||||
@@ -272,16 +279,11 @@ export const ChatContainer: React.FC = () => {
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
if (typeof window === 'undefined' || !currentSessionId) {
|
||||
return;
|
||||
}
|
||||
if (typeof window === 'undefined' || !currentSessionId) return;
|
||||
|
||||
const handleSessionReselected = (event: Event) => {
|
||||
const customEvent = event as CustomEvent<string>;
|
||||
if (customEvent.detail !== currentSessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (customEvent.detail !== currentSessionId) return;
|
||||
resumeToBottomInstant();
|
||||
};
|
||||
|
||||
@@ -293,9 +295,7 @@ export const ChatContainer: React.FC = () => {
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
const container = scrollRef.current;
|
||||
if (!container) {
|
||||
return;
|
||||
}
|
||||
if (!container) return;
|
||||
|
||||
const updateChatScrollHeight = () => {
|
||||
container.style.setProperty('--chat-scroll-height', `${container.clientHeight}px`);
|
||||
@@ -329,23 +329,15 @@ export const ChatContainer: React.FC = () => {
|
||||
};
|
||||
}, [currentSessionId, isDesktopExpandedInput, scrollRef]);
|
||||
|
||||
const hasHistoryMetadata = React.useMemo(() => {
|
||||
return Boolean(historyMeta);
|
||||
}, [historyMeta]);
|
||||
const hasHistoryMetadata = Boolean(historyMeta);
|
||||
|
||||
const isSessionHydrating =
|
||||
Boolean(currentSessionId)
|
||||
&& (!hasSessionMessagesEntry || !hasHistoryMetadata || historyMeta?.loading === true);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!currentSessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasSessionMessages = hasSessionMessagesEntry;
|
||||
if (hasSessionMessages && hasHistoryMetadata) {
|
||||
return;
|
||||
}
|
||||
if (!currentSessionId) return;
|
||||
if (hasSessionMessagesEntry && hasHistoryMetadata) return;
|
||||
|
||||
const load = async () => {
|
||||
await loadMessages(currentSessionId).finally(() => {
|
||||
@@ -523,6 +515,9 @@ export const ChatContainer: React.FC = () => {
|
||||
<ScrollShadow
|
||||
className="absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target"
|
||||
ref={scrollRef}
|
||||
style={(timelineController.pendingRevealWork || timelineController.isLoadingOlder)
|
||||
? { overflowAnchor: 'none' }
|
||||
: undefined}
|
||||
observeMutations={false}
|
||||
hideTopShadow={isMobile && stickyUserHeader}
|
||||
data-scroll-shadow="true"
|
||||
@@ -569,20 +564,6 @@ export const ChatContainer: React.FC = () => {
|
||||
)}
|
||||
<ChatInput scrollToBottom={scrollToBottom} />
|
||||
</div>
|
||||
|
||||
<TimelineDialog
|
||||
open={isTimelineDialogOpen}
|
||||
onOpenChange={setTimelineDialogOpen}
|
||||
onScrollToMessage={(messageId) => {
|
||||
releasePinnedScroll();
|
||||
return navigation.scrollToMessageId(messageId, { behavior: 'smooth', updateHash: false });
|
||||
}}
|
||||
onScrollByTurnOffset={(offset) => {
|
||||
releasePinnedScroll();
|
||||
void navigation.scrollByTurnOffset(offset);
|
||||
}}
|
||||
onResumeToLatest={navigation.resumeToLatest}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -16,12 +16,16 @@ import {
|
||||
RiSendPlane2Line,
|
||||
} from '@remixicon/react';
|
||||
import { BrowserVoiceButton } from '@/components/voice';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionStore as useSessionManagementStore } from '@/stores/sessionStore';
|
||||
// sessionStore removed — currentSessionId comes from useSessionUIStore
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useMessageQueueStore, type QueuedMessage } from '@/stores/messageQueueStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSelectionStore } from '@/sync/selection-store';
|
||||
import { useInputStore } from '@/sync/input-store';
|
||||
import type { AttachedFile } from '@/stores/types/sessionTypes';
|
||||
import * as sessionActions from '@/sync/session-actions';
|
||||
import { useSessionMessageRecords } from '@/sync/sync-context';
|
||||
import { useInlineCommentDraftStore, type InlineCommentDraft } from '@/stores/useInlineCommentDraftStore';
|
||||
import { appendInlineComments } from '@/lib/messages/inlineComments';
|
||||
import { AttachedFilesList } from './FileAttachment';
|
||||
@@ -40,8 +44,7 @@ import { MobileSessionStatusBar } from './MobileSessionStatusBar';
|
||||
import { useAssistantStatus } from '@/hooks/useAssistantStatus';
|
||||
import { useCurrentSessionActivity } from '@/hooks/useSessionActivity';
|
||||
import { toast } from '@/components/ui';
|
||||
import { useFileStore } from '@/stores/fileStore';
|
||||
import { useMessageStore } from '@/stores/messageStore';
|
||||
// useMessageStore removed — messages now come from sync system
|
||||
import { isTauriShell, isVSCodeRuntime } from '@/lib/desktop';
|
||||
import { isIMECompositionEvent } from '@/lib/ime';
|
||||
import { StopIcon } from '@/components/icons/StopIcon';
|
||||
@@ -81,6 +84,28 @@ const VS_CODE_DROP_DATA_TYPES = [
|
||||
|
||||
const FILE_URI_PREFIX = 'file://';
|
||||
|
||||
const encodeFilePath = (filepath: string): string => {
|
||||
let normalized = filepath.replace(/\\/g, '/');
|
||||
if (/^[A-Za-z]:/.test(normalized)) {
|
||||
normalized = `/${normalized}`;
|
||||
}
|
||||
return normalized
|
||||
.split('/')
|
||||
.map((segment, index) => {
|
||||
if (index === 1 && /^[A-Za-z]:$/.test(segment)) return segment;
|
||||
return encodeURIComponent(segment);
|
||||
})
|
||||
.join('/');
|
||||
};
|
||||
|
||||
const toServerFileUrl = (filepath: string): string => {
|
||||
const normalized = filepath.replace(/\\/g, '/').trim();
|
||||
if (normalized.toLowerCase().startsWith(FILE_URI_PREFIX)) {
|
||||
return normalized;
|
||||
}
|
||||
return `file://${encodeFilePath(normalized)}`;
|
||||
};
|
||||
|
||||
const isLikelyAbsolutePath = (value: string): boolean => (
|
||||
value.startsWith('/')
|
||||
|| value.startsWith('\\\\')
|
||||
@@ -273,7 +298,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
const initialSessionIdRef = React.useRef<string | null>(null);
|
||||
const [message, setMessage] = React.useState(() => {
|
||||
// Read per-session draft at mount time using the current session from the store
|
||||
const sessionId = useSessionStore.getState().currentSessionId;
|
||||
const sessionId = useSessionUIStore.getState().currentSessionId;
|
||||
initialSessionIdRef.current = sessionId;
|
||||
const draft = getStoredDraft(sessionId);
|
||||
if (draft) {
|
||||
@@ -313,25 +338,32 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
const lastPersistedDraftRef = React.useRef<Map<string, string>>(new Map());
|
||||
const currentSessionIdForDraftRef = React.useRef<string | null>(null);
|
||||
|
||||
const sendMessage = useSessionStore((state) => state.sendMessage);
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const newSessionDraft = useSessionStore((state) => state.newSessionDraft);
|
||||
// TODO: port sendMessage to session-actions (complex — creates sessions, handles attachments, etc.)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const sendMessage = React.useRef((...args: any[]) =>
|
||||
Promise.resolve((useSessionUIStore.getState().sendMessage as (...a: unknown[]) => unknown)(...args)),
|
||||
).current;
|
||||
const currentSessionId = useSessionUIStore((s) => s.currentSessionId);
|
||||
const newSessionDraft = useSessionUIStore((s) => s.newSessionDraft);
|
||||
const newSessionDraftOpen = Boolean(newSessionDraft?.open);
|
||||
const setNewSessionDraftTarget = useSessionStore((state) => state.setNewSessionDraftTarget);
|
||||
const availableWorktreesByProject = useSessionStore((state) => state.availableWorktreesByProject);
|
||||
const abortCurrentOperation = useSessionStore((state) => state.abortCurrentOperation);
|
||||
const acknowledgeSessionAbort = useSessionStore((state) => state.acknowledgeSessionAbort);
|
||||
const abortPromptSessionId = useSessionStore((state) => state.abortPromptSessionId);
|
||||
const clearAbortPrompt = useSessionStore((state) => state.clearAbortPrompt);
|
||||
const attachedFiles = useSessionStore((state) => state.attachedFiles);
|
||||
const addAttachedFile = useSessionStore((state) => state.addAttachedFile);
|
||||
const clearAttachedFiles = useSessionStore((state) => state.clearAttachedFiles);
|
||||
const saveSessionAgentSelection = useSessionStore((state) => state.saveSessionAgentSelection);
|
||||
const consumePendingInputText = useSessionStore((state) => state.consumePendingInputText);
|
||||
const setPendingInputText = useSessionStore((state) => state.setPendingInputText);
|
||||
const pendingInputText = useSessionStore((state) => state.pendingInputText);
|
||||
const consumePendingSyntheticParts = useSessionStore((state) => state.consumePendingSyntheticParts);
|
||||
const currentManagementSessionId = useSessionManagementStore((state) => state.currentSessionId);
|
||||
const setNewSessionDraftTarget = useSessionUIStore((s) => s.setNewSessionDraftTarget);
|
||||
const availableWorktreesByProject = useSessionUIStore((s) => s.availableWorktreesByProject);
|
||||
const abortPromptSessionId = useSessionUIStore((s) => s.abortPromptSessionId);
|
||||
const clearAbortPrompt = useSessionUIStore((s) => s.clearAbortPrompt);
|
||||
const attachedFiles = useInputStore((s) => s.attachedFiles);
|
||||
const addAttachedFile = useInputStore((s) => s.addAttachedFile);
|
||||
const clearAttachedFiles = useInputStore((s) => s.clearAttachedFiles);
|
||||
const saveSessionAgentSelection = useSelectionStore((s) => s.saveSessionAgentSelection);
|
||||
const consumePendingInputText = useInputStore((s) => s.consumePendingInputText);
|
||||
const setPendingInputText = useInputStore((s) => s.setPendingInputText);
|
||||
const pendingInputText = useInputStore((s) => s.pendingInputText);
|
||||
const consumePendingSyntheticParts = useInputStore((s) => s.consumePendingSyntheticParts);
|
||||
const acknowledgeSessionAbort = useSessionUIStore((s) => s.acknowledgeSessionAbort);
|
||||
const abortCurrentOperation = React.useCallback(
|
||||
(sessionIdOverride?: string) => sessionActions.abortCurrentOperation(sessionIdOverride ?? currentSessionId ?? ''),
|
||||
[currentSessionId],
|
||||
);
|
||||
const currentManagementSessionId = currentSessionId;
|
||||
const projects = useProjectsStore((state) => state.projects);
|
||||
const activeProjectId = useProjectsStore((state) => state.activeProjectId);
|
||||
const setActiveProjectIdOnly = useProjectsStore((state) => state.setActiveProjectIdOnly);
|
||||
@@ -339,7 +371,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
const { currentProviderId, currentModelId, currentVariant, currentAgentName, setAgent, getVisibleAgents } = useConfigStore();
|
||||
const agents = getVisibleAgents();
|
||||
const primaryAgents = React.useMemo(() => agents.filter((agent) => agent.mode === 'primary'), [agents]);
|
||||
const { isMobile, inputBarOffset, isKeyboardOpen, setTimelineDialogOpen, cornerRadius, persistChatDraft, inputSpellcheckEnabled, isExpandedInput, setExpandedInput } = useUIStore();
|
||||
const { isMobile, inputBarOffset, isKeyboardOpen, cornerRadius, persistChatDraft, inputSpellcheckEnabled, isExpandedInput, setExpandedInput } = useUIStore();
|
||||
const { working } = useAssistantStatus();
|
||||
const { git: runtimeGit } = useRuntimeAPIs();
|
||||
const { currentTheme } = useThemeSystem();
|
||||
@@ -351,10 +383,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
const isDesktopExpanded = isExpandedInput && !isMobile;
|
||||
const chatInputRadius = 'var(--radius-lg)';
|
||||
|
||||
const sendableAttachedFiles = React.useMemo(
|
||||
() => attachedFiles.filter((file) => file.source !== 'server'),
|
||||
[attachedFiles],
|
||||
);
|
||||
const sendableAttachedFiles = attachedFiles;
|
||||
|
||||
const hasInlineMentionForHighlight = React.useMemo(() => {
|
||||
if (!message || !message.includes('@') || inputMode === 'shell') {
|
||||
@@ -426,8 +455,12 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
|
||||
const sanitizeAttachmentsForSend = React.useCallback(
|
||||
(files: AttachedFile[] | undefined): AttachedFile[] => (files ?? [])
|
||||
.filter((file) => file.source !== 'server')
|
||||
.map((file) => ({ ...file })),
|
||||
.map((file) => ({
|
||||
...file,
|
||||
dataUrl: file.source === 'server' && file.serverPath
|
||||
? toServerFileUrl(file.serverPath)
|
||||
: file.dataUrl,
|
||||
})),
|
||||
[],
|
||||
);
|
||||
|
||||
@@ -498,7 +531,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
filename,
|
||||
mimeType: 'text/plain',
|
||||
size: 0,
|
||||
dataUrl: normalizedServerPath,
|
||||
dataUrl: toServerFileUrl(normalizedServerPath),
|
||||
source: 'server',
|
||||
serverPath: normalizedServerPath,
|
||||
});
|
||||
@@ -565,15 +598,10 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
|
||||
// User message history for up/down arrow navigation
|
||||
// Get raw messages from store (stable reference)
|
||||
const sessionMessages = useMessageStore(
|
||||
React.useCallback(
|
||||
(state) => (currentSessionId ? state.messages.get(currentSessionId) : undefined),
|
||||
[currentSessionId]
|
||||
)
|
||||
);
|
||||
const sessionMessages = useSessionMessageRecords(currentSessionId ?? "");
|
||||
// Derive user message history with useMemo to avoid infinite re-renders
|
||||
const userMessageHistory = React.useMemo(() => {
|
||||
if (!sessionMessages) return [];
|
||||
if (!sessionMessages || !currentSessionId) return [];
|
||||
return sessionMessages
|
||||
.filter((m) => m.info.role === 'user')
|
||||
.map((m) => {
|
||||
@@ -585,7 +613,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
})
|
||||
.filter((text) => text.length > 0)
|
||||
.reverse(); // Most recent first
|
||||
}, [sessionMessages]);
|
||||
}, [sessionMessages, currentSessionId]);
|
||||
|
||||
// Keep messageRef in sync with message state
|
||||
React.useEffect(() => {
|
||||
@@ -866,6 +894,12 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
addToQueue(currentSessionId, {
|
||||
content: messageToQueue,
|
||||
attachments: attachmentsToQueue.length > 0 ? attachmentsToQueue : undefined,
|
||||
sendConfig: currentProviderId && currentModelId ? {
|
||||
providerID: currentProviderId,
|
||||
modelID: currentModelId,
|
||||
agent: currentAgentName ?? undefined,
|
||||
variant: currentVariant ?? undefined,
|
||||
} : undefined,
|
||||
});
|
||||
|
||||
// Clear input and attachments
|
||||
@@ -877,7 +911,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
if (!isMobile) {
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [hasContent, currentSessionId, message, sendableAttachedFiles, sanitizeAttachmentsForSend, addToQueue, clearAttachedFiles, isMobile, consumeDrafts]);
|
||||
}, [hasContent, currentSessionId, message, sendableAttachedFiles, sanitizeAttachmentsForSend, addToQueue, clearAttachedFiles, isMobile, consumeDrafts, currentProviderId, currentModelId, currentAgentName, currentVariant]);
|
||||
|
||||
const handleSubmit = async (options?: SubmitOptions) => {
|
||||
const queuedOnly = options?.queuedOnly ?? false;
|
||||
@@ -1037,25 +1071,26 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
.split(/\s+/)[0]
|
||||
?.toLowerCase();
|
||||
|
||||
// NEW: /undo - revert to last message (populates input with reverted message text)
|
||||
if (commandName === 'undo' && currentSessionId) {
|
||||
await useSessionStore.getState().handleSlashUndo(currentSessionId);
|
||||
// Don't clear message - pendingInputText will populate it with reverted message
|
||||
await useSessionUIStore.getState().handleSlashUndo(currentSessionId);
|
||||
scrollToBottom?.({ instant: true, force: true });
|
||||
return; // Don't send to assistant
|
||||
return;
|
||||
}
|
||||
// NEW: /redo - unrevert or partial redo (populates input with message text)
|
||||
else if (commandName === 'redo' && currentSessionId) {
|
||||
await useSessionStore.getState().handleSlashRedo(currentSessionId);
|
||||
// Don't clear message - pendingInputText will populate it
|
||||
await useSessionUIStore.getState().handleSlashRedo(currentSessionId);
|
||||
scrollToBottom?.({ instant: true, force: true });
|
||||
return; // Don't send to assistant
|
||||
return;
|
||||
}
|
||||
// NEW: /timeline - open timeline dialog
|
||||
else if (commandName === 'timeline' && currentSessionId) {
|
||||
setTimelineDialogOpen(true);
|
||||
setMessage('');
|
||||
return; // Don't send to assistant
|
||||
else if (commandName === 'compact' && currentSessionId) {
|
||||
const { opencodeClient } = await import('@/lib/opencode/client');
|
||||
const sdk = opencodeClient.getSdkClient();
|
||||
const configState = useConfigStore.getState();
|
||||
await sdk.session.summarize({
|
||||
sessionID: currentSessionId,
|
||||
modelID: configState.currentModelId || '',
|
||||
providerID: configState.currentProviderId || '',
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1108,21 +1143,21 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
if (normalized.includes('payload too large') || normalized.includes('413') || normalized.includes('entity too large')) {
|
||||
toast.error('Attachments are too large to send. Please try reducing the number or size of images.');
|
||||
if (allAttachments.length > 0) {
|
||||
useFileStore.setState({ attachedFiles: allAttachments });
|
||||
useInputStore.setState({ attachedFiles: allAttachments });
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isSoftNetworkError) {
|
||||
if (allAttachments.length > 0) {
|
||||
useFileStore.setState({ attachedFiles: allAttachments });
|
||||
useInputStore.setState({ attachedFiles: allAttachments });
|
||||
toast.error('Failed to send attachments. Try fewer files or smaller images.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (allAttachments.length > 0) {
|
||||
useFileStore.setState({ attachedFiles: allAttachments });
|
||||
useInputStore.setState({ attachedFiles: allAttachments });
|
||||
}
|
||||
toast.error(rawMessage || 'Message failed to send. Attachments restored.');
|
||||
});
|
||||
@@ -2560,7 +2595,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
if (!selectedDraftDirectory || !selectedDraftBranchIsKnown) {
|
||||
return;
|
||||
}
|
||||
useSessionStore.getState().setDraftPreserveDirectoryOverride(false);
|
||||
useSessionUIStore.getState().setDraftPreserveDirectoryOverride(false);
|
||||
}, [newSessionDraft?.open, newSessionDraft?.preserveDirectoryOverride, selectedDraftBranchIsKnown, selectedDraftDirectory]);
|
||||
|
||||
const shouldShowDraftBranchSelector = React.useMemo(() => {
|
||||
@@ -2574,7 +2609,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
}, [isDiscoveringDraftBranches, projectRootBranchOption, worktreeBranchOptions.length]);
|
||||
|
||||
const handleDraftProjectChange = React.useCallback((projectId: string) => {
|
||||
const draft = useSessionStore.getState().newSessionDraft;
|
||||
const draft = useSessionUIStore.getState().newSessionDraft;
|
||||
if (draft?.pendingWorktreeRequestId || draft?.bootstrapPendingDirectory || draft?.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
@@ -2592,7 +2627,7 @@ export const ChatInput: React.FC<ChatInputProps> = ({ onOpenSettings, scrollToBo
|
||||
}, [activeProjectId, projects, setActiveProjectIdOnly, setNewSessionDraftTarget]);
|
||||
|
||||
const handleDraftDirectoryChange = React.useCallback((directory: string) => {
|
||||
const draft = useSessionStore.getState().newSessionDraft;
|
||||
const draft = useSessionUIStore.getState().newSessionDraft;
|
||||
if (draft?.pendingWorktreeRequestId || draft?.bootstrapPendingDirectory || draft?.preserveDirectoryOverride) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -4,10 +4,13 @@ import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
import { defaultCodeDark, defaultCodeLight } from '@/lib/codeTheme';
|
||||
import { MessageFreshnessDetector } from '@/lib/messageFreshness';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useContextStore } from '@/stores/contextStore';
|
||||
import { useStreamingStore } from '@/sync/streaming';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSelectionStore } from '@/sync/selection-store';
|
||||
import * as sessionActions from '@/sync/session-actions';
|
||||
import { useDeviceInfo } from '@/lib/device';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { generateSyntaxTheme } from '@/lib/theme/syntaxThemeGenerator';
|
||||
@@ -26,6 +29,8 @@ import { isLikelyProviderAuthFailure, PROVIDER_AUTH_FAILURE_MESSAGE } from '@/li
|
||||
import type { TurnGroupingContext } from './lib/turns/types';
|
||||
import { copyTextToClipboard } from '@/lib/clipboard';
|
||||
import { FadeInOnReveal } from './message/FadeInOnReveal';
|
||||
import { streamPerfCount } from '@/stores/utils/streamDebug';
|
||||
import { areOptionalRenderRelevantMessagesEqual, areRenderRelevantMessageInfoEqual, areRenderRelevantPartsEqual } from './message/renderCompare';
|
||||
|
||||
const ToolOutputDialog = React.lazy(() => import('./message/ToolOutputDialog'));
|
||||
|
||||
@@ -123,6 +128,8 @@ interface ChatMessageProps {
|
||||
animationHandlers?: AnimationHandlers;
|
||||
scrollToBottom?: (options?: { instant?: boolean; force?: boolean }) => void;
|
||||
turnGroupingContext?: TurnGroupingContext;
|
||||
assistantHeaderMessageId?: string;
|
||||
isInActiveTurn?: boolean;
|
||||
animateUserOnMount?: boolean;
|
||||
onUserAnimationConsumed?: (messageId: string) => void;
|
||||
}
|
||||
@@ -134,6 +141,8 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
onContentChange,
|
||||
animationHandlers,
|
||||
turnGroupingContext,
|
||||
assistantHeaderMessageId,
|
||||
isInActiveTurn = false,
|
||||
animateUserOnMount = false,
|
||||
onUserAnimationConsumed,
|
||||
}) => {
|
||||
@@ -141,36 +150,31 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
const { currentTheme } = useThemeSystem();
|
||||
const messageContainerRef = React.useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const sessionState = useSessionStore(
|
||||
useShallow((state) => ({
|
||||
lifecyclePhase: state.messageStreamStates.get(message.info.id)?.phase ?? null,
|
||||
isStreamingMessage: (() => {
|
||||
const sessionId =
|
||||
(message.info as { sessionID?: string }).sessionID ??
|
||||
state.currentSessionId ??
|
||||
null;
|
||||
if (!sessionId) return false;
|
||||
return (state.streamingMessageIds.get(sessionId) ?? null) === message.info.id;
|
||||
})(),
|
||||
currentSessionId: state.currentSessionId,
|
||||
getAgentModelForSession: state.getAgentModelForSession,
|
||||
getSessionModelSelection: state.getSessionModelSelection,
|
||||
revertToMessage: state.revertToMessage,
|
||||
forkFromMessage: state.forkFromMessage,
|
||||
}))
|
||||
);
|
||||
const currentSessionId = useSessionUIStore((s) => s.currentSessionId);
|
||||
const streamState = useStreamingStore((s) => s.messageStreamStates.get(message.info.id));
|
||||
const lifecyclePhase = isInActiveTurn ? (streamState?.phase ?? null) : null;
|
||||
|
||||
const {
|
||||
lifecyclePhase,
|
||||
isStreamingMessage,
|
||||
currentSessionId,
|
||||
getAgentModelForSession,
|
||||
getSessionModelSelection,
|
||||
revertToMessage,
|
||||
forkFromMessage,
|
||||
} = sessionState;
|
||||
const msgSessionId = (message.info as { sessionID?: string }).sessionID ?? currentSessionId ?? null;
|
||||
const streamingMsgForSession = useStreamingStore((s) => msgSessionId ? s.streamingMessageIds.get(msgSessionId) ?? null : null);
|
||||
const isStreamingMessage = isInActiveTurn ? streamingMsgForSession === message.info.id : false;
|
||||
const hasActiveStreamInSession = typeof streamingMsgForSession === 'string' && streamingMsgForSession.length > 0;
|
||||
|
||||
const providers = useConfigStore((state) => state.providers);
|
||||
const getAgentModelForSession = useSelectionStore((s) => s.getAgentModelForSession);
|
||||
const getSessionModelSelection = useSelectionStore((s) => s.getSessionModelSelection);
|
||||
const revertToMessage = sessionActions.revertToMessage;
|
||||
const forkFromMessage = sessionActions.forkFromMessage;
|
||||
|
||||
streamPerfCount('ui.chat_message.render');
|
||||
if (isStreamingMessage) {
|
||||
streamPerfCount('ui.chat_message.render.streaming');
|
||||
} else if (hasActiveStreamInSession) {
|
||||
streamPerfCount('ui.chat_message.render.static_during_stream');
|
||||
if (!isInActiveTurn) {
|
||||
streamPerfCount('ui.chat_message.render.static_outside_active_turn_during_stream');
|
||||
}
|
||||
}
|
||||
|
||||
const providers = useConfigStore.getState().providers;
|
||||
const { showReasoningTraces, stickyUserHeader, chatRenderMode, showExpandedBashTools, showExpandedEditTools } = useUIStore(
|
||||
useShallow((state) => ({
|
||||
showReasoningTraces: state.showReasoningTraces,
|
||||
@@ -211,11 +215,11 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
|
||||
const sessionId = message.info.sessionID;
|
||||
|
||||
// Subscribe to context changes so badges update immediately on mode switches.
|
||||
// Keep non-active-turn rows detached from context-store churn.
|
||||
const { currentContextAgent, savedSessionAgentSelection } = useContextStore(
|
||||
useShallow((state) => ({
|
||||
currentContextAgent: sessionId ? state.currentAgentContext.get(sessionId) : undefined,
|
||||
savedSessionAgentSelection: sessionId ? state.sessionAgentSelections.get(sessionId) : undefined,
|
||||
currentContextAgent: isInActiveTurn && sessionId ? state.currentAgentContext.get(sessionId) : undefined,
|
||||
savedSessionAgentSelection: isInActiveTurn && sessionId ? state.sessionAgentSelections.get(sessionId) : undefined,
|
||||
}))
|
||||
);
|
||||
|
||||
@@ -607,7 +611,7 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
}, [message.info.id]);
|
||||
|
||||
React.useEffect(() => {
|
||||
const headerMessageId = turnGroupingContext?.headerMessageId;
|
||||
const headerMessageId = assistantHeaderMessageId ?? turnGroupingContext?.headerMessageId;
|
||||
if (isUser || !headerMessageId || headerMessageId !== message.info.id) {
|
||||
return;
|
||||
}
|
||||
@@ -616,13 +620,13 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
if (isCurrentlyStreaming) {
|
||||
setHasStartedStreamingHeader(true);
|
||||
}
|
||||
}, [isUser, message.info.id, streamPhase, turnGroupingContext?.headerMessageId]);
|
||||
}, [assistantHeaderMessageId, isUser, message.info.id, streamPhase, turnGroupingContext?.headerMessageId]);
|
||||
|
||||
const shouldShowHeader = React.useMemo(() => {
|
||||
if (isUser) return true;
|
||||
|
||||
// Use turn grouping context if available for more precise control
|
||||
const headerMessageId = turnGroupingContext?.headerMessageId;
|
||||
const headerMessageId = assistantHeaderMessageId ?? turnGroupingContext?.headerMessageId;
|
||||
if (headerMessageId) {
|
||||
// For turn grouping: only show header for the first assistant message in the turn
|
||||
const isFirstAssistantInTurn = message.info.id === headerMessageId;
|
||||
@@ -644,7 +648,7 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
|
||||
// Ungrouped fallback path: always show assistant header.
|
||||
return true;
|
||||
}, [hasStartedStreamingHeader, isUser, turnGroupingContext, streamPhase, message.info.id]);
|
||||
}, [assistantHeaderMessageId, hasStartedStreamingHeader, isUser, turnGroupingContext, streamPhase, message.info.id]);
|
||||
|
||||
const handleCopyCode = React.useCallback((code: string) => {
|
||||
void copyTextToClipboard(code).then((result) => {
|
||||
@@ -1086,6 +1090,7 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
)}
|
||||
|
||||
<MessageBody
|
||||
sessionId={message.info.sessionID}
|
||||
messageId={message.info.id}
|
||||
parts={visibleParts}
|
||||
isUser={isUser}
|
||||
@@ -1131,4 +1136,15 @@ const ChatMessage: React.FC<ChatMessageProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(ChatMessage);
|
||||
export default React.memo(ChatMessage, (prev, next) => {
|
||||
return areRenderRelevantMessageInfoEqual(prev.message.info, next.message.info)
|
||||
&& areRenderRelevantPartsEqual(prev.message.parts, next.message.parts)
|
||||
&& areOptionalRenderRelevantMessagesEqual(prev.previousMessage, next.previousMessage)
|
||||
&& areOptionalRenderRelevantMessagesEqual(prev.nextMessage, next.nextMessage)
|
||||
&& prev.onContentChange === next.onContentChange
|
||||
&& prev.turnGroupingContext === next.turnGroupingContext
|
||||
&& prev.assistantHeaderMessageId === next.assistantHeaderMessageId
|
||||
&& prev.isInActiveTurn === next.isInActiveTurn
|
||||
&& prev.animateUserOnMount === next.animateUserOnMount
|
||||
&& prev.onUserAnimationConsumed === next.onUserAnimationConsumed;
|
||||
});
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import React from 'react';
|
||||
import { RiCommandLine, RiFileLine, RiFlashlightLine, RiRefreshLine, RiScissorsLine, RiTerminalBoxLine, RiArrowGoBackLine, RiArrowGoForwardLine, RiTimeLine } from '@remixicon/react';
|
||||
import { RiCommandLine, RiFileLine, RiFlashlightLine, RiRefreshLine, RiScissorsLine, RiTerminalBoxLine, RiArrowGoBackLine, RiArrowGoForwardLine } from '@remixicon/react';
|
||||
import { cn, fuzzyMatch } from '@/lib/utils';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSessionMessages } from '@/sync/sync-context';
|
||||
import { useCommandsStore } from '@/stores/useCommandsStore';
|
||||
import { useSkillsStore } from '@/stores/useSkillsStore';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
|
||||
|
||||
interface CommandInfo {
|
||||
@@ -42,16 +42,9 @@ export const CommandAutocomplete = React.forwardRef<CommandAutocompleteHandle, C
|
||||
onTabSelect,
|
||||
style,
|
||||
}, ref) => {
|
||||
const { hasMessagesInCurrentSession, currentSessionId } = useSessionStore(
|
||||
useShallow((state) => {
|
||||
const sessionId = state.currentSessionId;
|
||||
const messageCount = sessionId ? (state.messages.get(sessionId)?.length ?? 0) : 0;
|
||||
return {
|
||||
hasMessagesInCurrentSession: messageCount > 0,
|
||||
currentSessionId: sessionId,
|
||||
};
|
||||
})
|
||||
);
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const sessionMessages = useSessionMessages(currentSessionId ?? '');
|
||||
const hasMessagesInCurrentSession = sessionMessages.length > 0;
|
||||
const hasSession = Boolean(currentSessionId);
|
||||
|
||||
const [commands, setCommands] = React.useState<CommandInfo[]>([]);
|
||||
@@ -114,7 +107,6 @@ export const CommandAutocomplete = React.forwardRef<CommandAutocompleteHandle, C
|
||||
? [
|
||||
{ name: 'undo', description: 'Undo the last message', isBuiltIn: true },
|
||||
{ name: 'redo', description: 'Redo previously undone messages', isBuiltIn: true },
|
||||
{ name: 'timeline', description: 'Jump to a specific message', isBuiltIn: true },
|
||||
]
|
||||
: []
|
||||
),
|
||||
@@ -158,7 +150,6 @@ export const CommandAutocomplete = React.forwardRef<CommandAutocompleteHandle, C
|
||||
? [
|
||||
{ name: 'undo', description: 'Undo the last message', isBuiltIn: true },
|
||||
{ name: 'redo', description: 'Redo previously undone messages', isBuiltIn: true },
|
||||
{ name: 'timeline', description: 'Jump to a specific message', isBuiltIn: true },
|
||||
]
|
||||
: []
|
||||
),
|
||||
@@ -233,8 +224,6 @@ export const CommandAutocomplete = React.forwardRef<CommandAutocompleteHandle, C
|
||||
return <RiArrowGoBackLine className="h-3.5 w-3.5 text-orange-500" />;
|
||||
case 'redo':
|
||||
return <RiArrowGoForwardLine className="h-3.5 w-3.5 text-orange-500" />;
|
||||
case 'timeline':
|
||||
return <RiTimeLine className="h-3.5 w-3.5 text-blue-500" />;
|
||||
case 'compact':
|
||||
return <RiScissorsLine className="h-3.5 w-3.5 text-purple-500" />;
|
||||
case 'test':
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useRef, memo } from 'react';
|
||||
import { RiAttachment2, RiCloseLine, RiFileImageLine, RiFileLine, RiFilePdfLine, RiGithubLine, RiGitPullRequestLine } from '@remixicon/react';
|
||||
import { useSessionStore, type AttachedFile } from '@/stores/useSessionStore';
|
||||
import { useInputStore } from '@/sync/input-store';
|
||||
import type { AttachedFile } from '@/sync/session-ui-store';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { toast } from '@/components/ui';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -13,7 +14,7 @@ import type { ToolPopupContent } from './message/types';
|
||||
|
||||
export const FileAttachmentButton = memo(() => {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { addAttachedFile } = useSessionStore();
|
||||
const { addAttachedFile } = useInputStore();
|
||||
const { isMobile } = useUIStore();
|
||||
const isVSCodeRuntime = useIsVSCodeRuntime();
|
||||
const buttonSizeClass = isMobile ? 'h-9 w-9' : 'h-7 w-7';
|
||||
@@ -255,7 +256,7 @@ const FileChip = memo(({ file, onRemove }: FileChipProps) => {
|
||||
FileChip.displayName = 'FileChip';
|
||||
|
||||
export const AttachedFilesList = memo(() => {
|
||||
const { attachedFiles, removeAttachedFile } = useSessionStore();
|
||||
const { attachedFiles, removeAttachedFile } = useInputStore();
|
||||
|
||||
const localFiles = attachedFiles.filter((file) => file.source !== 'server');
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSelectionStore } from '@/sync/selection-store';
|
||||
import { getAgentDisplayName } from './mobileControlsUtils';
|
||||
import { getAgentColor } from '@/lib/agentColors';
|
||||
|
||||
@@ -16,8 +17,8 @@ const LONG_PRESS_MS = 500;
|
||||
// NOTE: Use pointer events instead of onClick to keep soft keyboard open on mobile
|
||||
export const MobileAgentButton: React.FC<MobileAgentButtonProps> = ({ onCycleAgent, onOpenAgentPanel, className }) => {
|
||||
const { currentAgentName, getVisibleAgents } = useConfigStore();
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const sessionAgentName = useSessionStore((state) =>
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const sessionAgentName = useSelectionStore((state) =>
|
||||
currentSessionId ? state.getSessionAgentSelection(currentSessionId) : null
|
||||
);
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import React from 'react';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSelectionStore } from '@/sync/selection-store';
|
||||
import { useSessions, useAllSessionStatuses } from '@/sync/sync-context';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
@@ -52,6 +54,7 @@ import { ProjectEditDialog } from '@/components/layout/ProjectEditDialog';
|
||||
import { useDrawerSwipe } from '@/hooks/useDrawerSwipe';
|
||||
import { MobileOverlayPanel } from '@/components/ui/MobileOverlayPanel';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { useNotificationStore } from '@/sync/notification-store';
|
||||
|
||||
interface MobileSessionStatusBarProps {
|
||||
onSessionSwitch?: (sessionId: string) => void;
|
||||
@@ -74,9 +77,10 @@ const normalize = (value: string): string => {
|
||||
|
||||
function useSessionGrouping(
|
||||
sessions: Session[],
|
||||
sessionStatus: Map<string, { type: string }> | undefined,
|
||||
sessionAttentionStates: Map<string, { needsAttention: boolean }> | undefined
|
||||
sessionStatus: Record<string, { type: string }> | undefined
|
||||
) {
|
||||
const unseenCounts = useNotificationStore((s) => s.index.session.unseenCount);
|
||||
|
||||
const parentChildMap = React.useMemo(() => {
|
||||
const map = new Map<string, Session[]>();
|
||||
const allIds = new Set(sessions.map((s) => s.id));
|
||||
@@ -91,7 +95,7 @@ function useSessionGrouping(
|
||||
}, [sessions]);
|
||||
|
||||
const getStatusType = React.useCallback((sessionId: string): 'busy' | 'retry' | 'idle' => {
|
||||
const status = sessionStatus?.get(sessionId);
|
||||
const status = sessionStatus?.[sessionId];
|
||||
if (status?.type === 'busy' || status?.type === 'retry') return status.type;
|
||||
return 'idle';
|
||||
}, [sessionStatus]);
|
||||
@@ -126,7 +130,7 @@ function useSessionGrouping(
|
||||
topLevel.forEach((session) => {
|
||||
const statusType = getStatusType(session.id);
|
||||
const hasRunning = hasRunningChildren(session.id);
|
||||
const attention = sessionAttentionStates?.get(session.id)?.needsAttention ?? false;
|
||||
const attention = (unseenCounts[session.id] ?? 0) > 0;
|
||||
|
||||
const enriched: SessionWithStatus = {
|
||||
...session,
|
||||
@@ -155,28 +159,27 @@ function useSessionGrouping(
|
||||
viewed.sort(sortByUpdated);
|
||||
|
||||
return [...running, ...viewed];
|
||||
}, [sessions, getStatusType, hasRunningChildren, getRunningChildrenCount, getChildIndicators, sessionAttentionStates]);
|
||||
}, [sessions, getStatusType, hasRunningChildren, getRunningChildrenCount, getChildIndicators, unseenCounts]);
|
||||
|
||||
const totalRunning = processedSessions.reduce((sum, s) => {
|
||||
const selfRunning = s._statusType !== 'idle' ? 1 : 0;
|
||||
return sum + selfRunning + (s._runningChildrenCount ?? 0);
|
||||
}, 0);
|
||||
|
||||
const totalUnread = processedSessions.filter((s) => sessionAttentionStates?.get(s.id)?.needsAttention ?? false).length;
|
||||
const totalUnread = processedSessions.filter((s) => (unseenCounts[s.id] ?? 0) > 0).length;
|
||||
|
||||
return { sessions: processedSessions, totalRunning, totalUnread, totalCount: processedSessions.length };
|
||||
}
|
||||
|
||||
function useSessionHelpers(
|
||||
agents: Array<{ name: string }>,
|
||||
sessionStatus: Map<string, { type: string }> | undefined,
|
||||
sessionAttentionStates: Map<string, { needsAttention: boolean }> | undefined
|
||||
sessionStatus: Record<string, { type: string }> | undefined
|
||||
) {
|
||||
const getSessionAgentName = React.useCallback((session: Session): string => {
|
||||
const agent = (session as { agent?: string }).agent;
|
||||
if (agent) return agent;
|
||||
|
||||
const sessionAgentSelection = useSessionStore.getState().getSessionAgentSelection(session.id);
|
||||
const sessionAgentSelection = useSelectionStore.getState().getSessionAgentSelection(session.id);
|
||||
if (sessionAgentSelection) return sessionAgentSelection;
|
||||
|
||||
return agents[0]?.name ?? 'agent';
|
||||
@@ -189,14 +192,14 @@ function useSessionHelpers(
|
||||
}, []);
|
||||
|
||||
const isRunning = React.useCallback((sessionId: string): boolean => {
|
||||
const status = sessionStatus?.get(sessionId);
|
||||
const status = sessionStatus?.[sessionId];
|
||||
return status?.type === 'busy' || status?.type === 'retry';
|
||||
}, [sessionStatus]);
|
||||
|
||||
// Use server-authoritative attention state instead of local activity state
|
||||
const unseenCounts = useNotificationStore((s) => s.index.session.unseenCount);
|
||||
const needsAttention = React.useCallback((sessionId: string): boolean => {
|
||||
return sessionAttentionStates?.get(sessionId)?.needsAttention ?? false;
|
||||
}, [sessionAttentionStates]);
|
||||
return (unseenCounts[sessionId] ?? 0) > 0;
|
||||
}, [unseenCounts]);
|
||||
|
||||
return { getSessionAgentName, getSessionTitle, isRunning, needsAttention };
|
||||
}
|
||||
@@ -204,17 +207,16 @@ function useSessionHelpers(
|
||||
// Hook to calculate project status indicators
|
||||
function useProjectStatus(
|
||||
sessions: Session[],
|
||||
sessionStatus: Map<string, { type: string }> | undefined,
|
||||
sessionAttentionStates: Map<string, { needsAttention: boolean }> | undefined,
|
||||
sessionStatus: Record<string, { type: string }> | undefined,
|
||||
currentSessionId: string | null
|
||||
) {
|
||||
const availableWorktreesByProject = useSessionStore((state) => state.availableWorktreesByProject);
|
||||
const sessionsByDirectory = useSessionStore((state) => state.sessionsByDirectory);
|
||||
const getSessionsByDirectory = useSessionStore((state) => state.getSessionsByDirectory);
|
||||
const availableWorktreesByProject = useSessionUIStore((state) => state.availableWorktreesByProject);
|
||||
const getSessionsByDirectory = useSessionUIStore((state) => state.getSessionsByDirectory);
|
||||
const notifUnseenCounts = useNotificationStore((s) => s.index.session.unseenCount);
|
||||
|
||||
const projectStatusMap = React.useCallback((projectPath: string): { hasRunning: boolean; hasUnread: boolean } => {
|
||||
const getStatusType = (sessionId: string): 'busy' | 'retry' | 'idle' => {
|
||||
const status = sessionStatus?.get(sessionId);
|
||||
const status = sessionStatus?.[sessionId];
|
||||
if (status?.type === 'busy' || status?.type === 'retry') return status.type;
|
||||
return 'idle';
|
||||
};
|
||||
@@ -241,7 +243,7 @@ function useProjectStatus(
|
||||
let hasUnread = false;
|
||||
|
||||
for (const dir of dirs) {
|
||||
const list = sessionsByDirectory.get(dir) ?? getSessionsByDirectory(dir);
|
||||
const list = getSessionsByDirectory(dir);
|
||||
for (const session of list) {
|
||||
if (!session?.id || seen.has(session.id)) {
|
||||
continue;
|
||||
@@ -253,7 +255,7 @@ function useProjectStatus(
|
||||
hasRunning = true;
|
||||
}
|
||||
|
||||
if (session.id !== currentSessionId && sessionAttentionStates?.get(session.id)?.needsAttention === true) {
|
||||
if (session.id !== currentSessionId && (notifUnseenCounts[session.id] ?? 0) > 0) {
|
||||
hasUnread = true;
|
||||
}
|
||||
|
||||
@@ -267,7 +269,7 @@ function useProjectStatus(
|
||||
}
|
||||
|
||||
return { hasRunning, hasUnread };
|
||||
}, [sessionsByDirectory, getSessionsByDirectory, availableWorktreesByProject, sessionStatus, sessionAttentionStates, currentSessionId]);
|
||||
}, [getSessionsByDirectory, availableWorktreesByProject, sessionStatus, notifUnseenCounts, currentSessionId]);
|
||||
|
||||
return projectStatusMap;
|
||||
}
|
||||
@@ -1290,7 +1292,7 @@ function ExpandedView({
|
||||
const [collapsedHeight, setCollapsedHeight] = React.useState<number | null>(null);
|
||||
const [hasMeasured, setHasMeasured] = React.useState(false);
|
||||
const { handleTouchStart, handleTouchMove, handleTouchEnd } = useDrawerSwipe();
|
||||
const availableWorktreesByProject = useSessionStore((state) => state.availableWorktreesByProject);
|
||||
const availableWorktreesByProject = useSessionUIStore((state) => state.availableWorktreesByProject);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (containerRef.current && !hasMeasured && !isExpanded) {
|
||||
@@ -1429,13 +1431,12 @@ export const MobileSessionStatusBar: React.FC<MobileSessionStatusBarProps> = ({
|
||||
cornerRadius,
|
||||
}) => {
|
||||
const { currentTheme } = useThemeSystem();
|
||||
const sessions = useSessionStore((state) => state.sessions);
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const sessionStatus = useSessionStore((state) => state.sessionStatus);
|
||||
const sessionAttentionStates = useSessionStore((state) => state.sessionAttentionStates);
|
||||
const setCurrentSession = useSessionStore((state) => state.setCurrentSession);
|
||||
const openNewSessionDraft = useSessionStore((state) => state.openNewSessionDraft);
|
||||
const getContextUsage = useSessionStore((state) => state.getContextUsage);
|
||||
const sessions = useSessions();
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const sessionStatus = useAllSessionStatuses();
|
||||
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
|
||||
const openNewSessionDraft = useSessionUIStore((state) => state.openNewSessionDraft);
|
||||
const getContextUsage = useSessionUIStore((state) => state.getContextUsage);
|
||||
const agents = useConfigStore((state) => state.agents);
|
||||
const { getCurrentModel } = useConfigStore();
|
||||
const { isMobile, showMobileSessionStatusBar, isMobileSessionStatusBarCollapsed, setIsMobileSessionStatusBarCollapsed } = useUIStore();
|
||||
@@ -1452,9 +1453,9 @@ export const MobileSessionStatusBar: React.FC<MobileSessionStatusBarProps> = ({
|
||||
// Directory store
|
||||
const homeDirectory = useDirectoryStore((state) => state.homeDirectory);
|
||||
|
||||
const { sessions: sortedSessions, totalRunning, totalUnread, totalCount } = useSessionGrouping(sessions, sessionStatus, sessionAttentionStates);
|
||||
const { getSessionAgentName, getSessionTitle, needsAttention } = useSessionHelpers(agents, sessionStatus, sessionAttentionStates);
|
||||
const getProjectStatus = useProjectStatus(sessions, sessionStatus, sessionAttentionStates, currentSessionId);
|
||||
const { sessions: sortedSessions, totalRunning, totalUnread, totalCount } = useSessionGrouping(sessions, sessionStatus);
|
||||
const { getSessionAgentName, getSessionTitle, needsAttention } = useSessionHelpers(agents, sessionStatus);
|
||||
const getProjectStatus = useProjectStatus(sessions, sessionStatus, currentSessionId);
|
||||
|
||||
const currentSession = sessions.find((s) => s.id === currentSessionId);
|
||||
const currentSessionTitle = currentSession
|
||||
|
||||
@@ -47,7 +47,10 @@ import { getEditModeColors } from '@/lib/permissions/editModeColors';
|
||||
import { cn, fuzzyMatch } from '@/lib/utils';
|
||||
import { useContextStore } from '@/stores/contextStore';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSelectionStore } from '@/sync/selection-store';
|
||||
import { useDirectorySync, useSessionMessages } from '@/sync/sync-context';
|
||||
import { useSync } from '@/sync/use-sync';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useModelLists } from '@/hooks/useModelLists';
|
||||
import { useIsTextTruncated } from '@/hooks/useIsTextTruncated';
|
||||
@@ -314,20 +317,23 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
const agents = getVisibleAgents();
|
||||
const primaryAgents = React.useMemo(() => agents.filter((agent) => agent.mode === 'primary'), [agents]);
|
||||
|
||||
const currentSessionId = useSessionUIStore((s) => s.currentSessionId);
|
||||
const getDirectoryForSession = useSessionUIStore((s) => s.getDirectoryForSession);
|
||||
const sync = useSync();
|
||||
|
||||
const {
|
||||
currentSessionId,
|
||||
messages,
|
||||
getSessionModelSelection,
|
||||
saveSessionModelSelection,
|
||||
saveSessionAgentSelection,
|
||||
saveAgentModelForSession,
|
||||
getAgentModelForSession,
|
||||
saveAgentModelVariantForSession,
|
||||
getAgentModelVariantForSession,
|
||||
analyzeAndSaveExternalSessionChoices,
|
||||
} = useSessionStore();
|
||||
} = useSelectionStore();
|
||||
|
||||
const contextHydrated = useContextStore((state) => state.hasHydrated);
|
||||
|
||||
const sessionSavedAgentName = useContextStore((state) =>
|
||||
const sessionSavedAgentName = useSelectionStore((state) =>
|
||||
currentSessionId ? state.sessionAgentSelections.get(currentSessionId) ?? null : null
|
||||
);
|
||||
|
||||
@@ -563,31 +569,45 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
];
|
||||
|
||||
const prevAgentNameRef = React.useRef<string | undefined>(undefined);
|
||||
const latestLoadedUserChoiceRestoreRef = React.useRef<string | null>(null);
|
||||
|
||||
const currentSessionMessageCount = currentSessionId ? (messages.get(currentSessionId)?.length ?? -1) : -1;
|
||||
const currentSessionDirectory = currentSessionId ? getDirectoryForSession(currentSessionId) : undefined;
|
||||
const hasCurrentSessionMessagesEntry = useDirectorySync(
|
||||
React.useCallback(
|
||||
(state) => (currentSessionId ? state.message[currentSessionId] !== undefined : false),
|
||||
[currentSessionId],
|
||||
),
|
||||
currentSessionDirectory ?? undefined,
|
||||
);
|
||||
const currentSessionMessagesFromSync = useSessionMessages(currentSessionId ?? '', currentSessionDirectory ?? undefined);
|
||||
const latestLoadedUserChoice = React.useMemo(() => {
|
||||
for (let i = currentSessionMessagesFromSync.length - 1; i >= 0; i -= 1) {
|
||||
const message = currentSessionMessagesFromSync[i] as typeof currentSessionMessagesFromSync[number] & {
|
||||
model?: { providerID?: string; modelID?: string };
|
||||
variant?: string;
|
||||
mode?: string;
|
||||
};
|
||||
if (message.role !== 'user') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const sessionInitializationRef = React.useRef<{
|
||||
sessionId: string;
|
||||
resolved: boolean;
|
||||
inFlight: boolean;
|
||||
} | null>(null);
|
||||
const providerID = typeof message.model?.providerID === 'string' && message.model.providerID.trim().length > 0
|
||||
? message.model.providerID
|
||||
: undefined;
|
||||
const modelID = typeof message.model?.modelID === 'string' && message.model.modelID.trim().length > 0
|
||||
? message.model.modelID
|
||||
: undefined;
|
||||
const agent = typeof message.agent === 'string' && message.agent.trim().length > 0
|
||||
? message.agent
|
||||
: (typeof message.mode === 'string' && message.mode.trim().length > 0 ? message.mode : undefined);
|
||||
const variant = typeof message.variant === 'string' && message.variant.trim().length > 0
|
||||
? message.variant
|
||||
: undefined;
|
||||
|
||||
// If we have an explicit per-session agent selection (eg. server-injected mode switch),
|
||||
// treat the session as resolved and don't run inference/fallback that could cause flicker.
|
||||
React.useEffect(() => {
|
||||
if (!currentSessionId) {
|
||||
return;
|
||||
return { id: message.id, agent, providerID, modelID, variant };
|
||||
}
|
||||
const refState = sessionInitializationRef.current;
|
||||
if (!refState || refState.sessionId !== currentSessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (sessionSavedAgentName && agents.some((agent) => agent.name === sessionSavedAgentName)) {
|
||||
refState.resolved = true;
|
||||
refState.inFlight = false;
|
||||
}
|
||||
}, [agents, currentSessionId, sessionSavedAgentName]);
|
||||
return null;
|
||||
}, [currentSessionMessagesFromSync]);
|
||||
|
||||
const tryApplyModelSelection = React.useCallback(
|
||||
(providerId: string, modelId: string, agentName?: string): ModelApplyResult => {
|
||||
@@ -606,21 +626,93 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
return 'model-missing';
|
||||
}
|
||||
|
||||
const providerMatches = currentProviderId === providerId;
|
||||
const modelMatches = currentModelId === modelId;
|
||||
if (providerMatches && modelMatches) {
|
||||
return 'applied';
|
||||
}
|
||||
|
||||
setProvider(providerId);
|
||||
setModel(modelId);
|
||||
|
||||
if (currentSessionId && agentName) {
|
||||
saveAgentModelForSession(currentSessionId, agentName, providerId, modelId);
|
||||
if (currentSessionId) {
|
||||
saveSessionModelSelection(currentSessionId, providerId, modelId);
|
||||
if (agentName) {
|
||||
saveAgentModelForSession(currentSessionId, agentName, providerId, modelId);
|
||||
}
|
||||
}
|
||||
|
||||
return 'applied';
|
||||
},
|
||||
[providers, setProvider, setModel, currentSessionId, saveAgentModelForSession],
|
||||
[providers, currentProviderId, currentModelId, setProvider, setModel, currentSessionId, saveAgentModelForSession, saveSessionModelSelection],
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!currentSessionId) {
|
||||
sessionInitializationRef.current = null;
|
||||
latestLoadedUserChoiceRestoreRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!contextHydrated || providers.length === 0 || !hasCurrentSessionMessagesEntry || !latestLoadedUserChoice?.providerID || !latestLoadedUserChoice.modelID) {
|
||||
return;
|
||||
}
|
||||
|
||||
const restoreKey = [
|
||||
currentSessionId,
|
||||
latestLoadedUserChoice.id,
|
||||
latestLoadedUserChoice.agent ?? '',
|
||||
latestLoadedUserChoice.providerID,
|
||||
latestLoadedUserChoice.modelID,
|
||||
latestLoadedUserChoice.variant ?? '',
|
||||
].join('|');
|
||||
|
||||
if (latestLoadedUserChoiceRestoreRef.current === restoreKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (latestLoadedUserChoice.agent && currentAgentName !== latestLoadedUserChoice.agent) {
|
||||
setAgent(latestLoadedUserChoice.agent);
|
||||
}
|
||||
|
||||
const applyResult = tryApplyModelSelection(
|
||||
latestLoadedUserChoice.providerID,
|
||||
latestLoadedUserChoice.modelID,
|
||||
latestLoadedUserChoice.agent || currentAgentName || undefined,
|
||||
);
|
||||
if (applyResult !== 'applied') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (latestLoadedUserChoice.agent) {
|
||||
saveSessionAgentSelection(currentSessionId, latestLoadedUserChoice.agent);
|
||||
saveAgentModelVariantForSession(
|
||||
currentSessionId,
|
||||
latestLoadedUserChoice.agent,
|
||||
latestLoadedUserChoice.providerID,
|
||||
latestLoadedUserChoice.modelID,
|
||||
latestLoadedUserChoice.variant,
|
||||
);
|
||||
}
|
||||
saveSessionModelSelection(currentSessionId, latestLoadedUserChoice.providerID, latestLoadedUserChoice.modelID);
|
||||
latestLoadedUserChoiceRestoreRef.current = restoreKey;
|
||||
|
||||
}, [
|
||||
currentSessionId,
|
||||
currentAgentName,
|
||||
contextHydrated,
|
||||
providers,
|
||||
hasCurrentSessionMessagesEntry,
|
||||
latestLoadedUserChoice,
|
||||
setAgent,
|
||||
tryApplyModelSelection,
|
||||
saveSessionAgentSelection,
|
||||
saveAgentModelVariantForSession,
|
||||
saveSessionModelSelection,
|
||||
]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!currentSessionId) {
|
||||
latestLoadedUserChoiceRestoreRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -628,31 +720,10 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
return;
|
||||
}
|
||||
|
||||
if (!sessionInitializationRef.current || sessionInitializationRef.current.sessionId !== currentSessionId) {
|
||||
sessionInitializationRef.current = { sessionId: currentSessionId, resolved: false, inFlight: false };
|
||||
}
|
||||
|
||||
const state = sessionInitializationRef.current;
|
||||
if (!state || state.resolved || state.inFlight) {
|
||||
return;
|
||||
}
|
||||
|
||||
let isCancelled = false;
|
||||
|
||||
const finalize = () => {
|
||||
if (isCancelled) {
|
||||
return;
|
||||
}
|
||||
const refState = sessionInitializationRef.current;
|
||||
if (refState && refState.sessionId === currentSessionId) {
|
||||
refState.resolved = true;
|
||||
refState.inFlight = false;
|
||||
}
|
||||
};
|
||||
|
||||
const applySavedSelections = (): 'resolved' | 'waiting' | 'continue' => {
|
||||
const savedSessionModel = getSessionModelSelection(currentSessionId);
|
||||
const savedAgentName = currentSessionId
|
||||
? (useContextStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current)
|
||||
? useSelectionStore.getState().getSessionAgentSelection(currentSessionId)
|
||||
: null;
|
||||
if (savedAgentName) {
|
||||
if (currentAgentName !== savedAgentName) {
|
||||
@@ -668,9 +739,17 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
if (result === 'provider-missing') {
|
||||
return 'waiting';
|
||||
}
|
||||
} else {
|
||||
}
|
||||
}
|
||||
|
||||
if (savedSessionModel) {
|
||||
const result = tryApplyModelSelection(savedSessionModel.providerId, savedSessionModel.modelId, savedAgentName || currentAgentName || undefined);
|
||||
if (result === 'applied') {
|
||||
return 'resolved';
|
||||
}
|
||||
if (result === 'provider-missing') {
|
||||
return 'waiting';
|
||||
}
|
||||
}
|
||||
|
||||
for (const agent of agents) {
|
||||
@@ -683,7 +762,7 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
setAgent(agent.name);
|
||||
}
|
||||
|
||||
const existingSelection = useContextStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current;
|
||||
const existingSelection = useSelectionStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current;
|
||||
if (!existingSelection) {
|
||||
saveSessionAgentSelection(currentSessionId, agent.name);
|
||||
}
|
||||
@@ -705,14 +784,14 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
}
|
||||
|
||||
const existingSelection = currentSessionId
|
||||
? (useContextStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current)
|
||||
? (useSelectionStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current)
|
||||
: null;
|
||||
|
||||
// If we already have a valid agent selected (often from server-injected mode switch),
|
||||
// don't override it with a fallback.
|
||||
const preferred =
|
||||
(currentSessionId
|
||||
? (useContextStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current)
|
||||
? (useSelectionStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current)
|
||||
: null) ||
|
||||
currentAgentName;
|
||||
if (preferred && agents.some((agent) => agent.name === preferred)) {
|
||||
@@ -740,174 +819,38 @@ export const ModelControls: React.FC<ModelControlsProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const resolveSessionPreferences = async () => {
|
||||
try {
|
||||
const savedOutcome = applySavedSelections();
|
||||
if (savedOutcome === 'resolved') {
|
||||
finalize();
|
||||
return;
|
||||
}
|
||||
if (savedOutcome === 'waiting') {
|
||||
return;
|
||||
}
|
||||
const savedOutcome = applySavedSelections();
|
||||
if (savedOutcome === 'resolved' || savedOutcome === 'waiting') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentSessionMessageCount === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentSessionMessageCount > 0) {
|
||||
state.inFlight = true;
|
||||
try {
|
||||
const discoveredChoices = await analyzeAndSaveExternalSessionChoices(currentSessionId, agents);
|
||||
if (isCancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (discoveredChoices.size > 0) {
|
||||
let latestAgent: string | null = null;
|
||||
let latestTimestamp = -Infinity;
|
||||
|
||||
for (const [agentName, choice] of discoveredChoices) {
|
||||
if (choice.timestamp > latestTimestamp) {
|
||||
latestTimestamp = choice.timestamp;
|
||||
latestAgent = agentName;
|
||||
}
|
||||
}
|
||||
|
||||
if (latestAgent) {
|
||||
// If server/user already selected an agent for this session, don't override
|
||||
// with heuristic inference mid-stream.
|
||||
const latestSaved = useContextStore.getState().getSessionAgentSelection(currentSessionId) || stickySessionAgentRef.current;
|
||||
if (latestSaved && latestSaved !== latestAgent) {
|
||||
finalize();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!latestSaved) {
|
||||
saveSessionAgentSelection(currentSessionId, latestAgent);
|
||||
}
|
||||
if (currentAgentName !== latestAgent) {
|
||||
setAgent(latestAgent);
|
||||
}
|
||||
|
||||
const latestChoice = discoveredChoices.get(latestAgent);
|
||||
if (latestChoice) {
|
||||
const applyResult = tryApplyModelSelection(
|
||||
latestChoice.providerId,
|
||||
latestChoice.modelId,
|
||||
latestAgent,
|
||||
);
|
||||
|
||||
if (applyResult === 'applied') {
|
||||
finalize();
|
||||
return;
|
||||
}
|
||||
|
||||
if (applyResult === 'provider-missing') {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
finalize();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isCancelled) {
|
||||
console.error('[ModelControls] Error resolving session from messages:', error);
|
||||
}
|
||||
} finally {
|
||||
const refState = sessionInitializationRef.current;
|
||||
if (!isCancelled && refState && refState.sessionId === currentSessionId) {
|
||||
refState.inFlight = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isCancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
applyFallbackAgent();
|
||||
finalize();
|
||||
} catch (error) {
|
||||
if (!isCancelled) {
|
||||
console.error('[ModelControls] Error in session switch:', error);
|
||||
}
|
||||
if (!hasCurrentSessionMessagesEntry) {
|
||||
if (!sync.isLoading(currentSessionId)) {
|
||||
void sync.syncSession(currentSessionId);
|
||||
}
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
resolveSessionPreferences();
|
||||
if (latestLoadedUserChoice) {
|
||||
return;
|
||||
}
|
||||
|
||||
return () => {
|
||||
isCancelled = true;
|
||||
};
|
||||
applyFallbackAgent();
|
||||
}, [
|
||||
currentSessionId,
|
||||
currentSessionMessageCount,
|
||||
hasCurrentSessionMessagesEntry,
|
||||
latestLoadedUserChoice,
|
||||
agents,
|
||||
primaryAgents,
|
||||
currentAgentName,
|
||||
getSessionModelSelection,
|
||||
getAgentModelForSession,
|
||||
setAgent,
|
||||
tryApplyModelSelection,
|
||||
analyzeAndSaveExternalSessionChoices,
|
||||
saveSessionAgentSelection,
|
||||
contextHydrated,
|
||||
providers,
|
||||
sessionSavedAgentName,
|
||||
]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!contextHydrated || !currentSessionId || providers.length === 0 || agents.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preferredAgent = sessionSavedAgentName || currentAgentName;
|
||||
if (!preferredAgent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preferredSelection = getAgentModelForSession(currentSessionId, preferredAgent);
|
||||
if (!preferredSelection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const provider = providers.find(p => p.id === preferredSelection.providerId);
|
||||
if (!provider) {
|
||||
return;
|
||||
}
|
||||
|
||||
const modelExists = Array.isArray(provider.models)
|
||||
? provider.models.some((m: ProviderModel) => m.id === preferredSelection.modelId)
|
||||
: false;
|
||||
if (!modelExists) {
|
||||
return;
|
||||
}
|
||||
|
||||
const providerMatches = currentProviderId === preferredSelection.providerId;
|
||||
const modelMatches = currentModelId === preferredSelection.modelId;
|
||||
if (providerMatches && modelMatches) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (preferredAgent !== currentAgentName) {
|
||||
setAgent(preferredAgent);
|
||||
}
|
||||
|
||||
tryApplyModelSelection(preferredSelection.providerId, preferredSelection.modelId, preferredAgent);
|
||||
}, [
|
||||
contextHydrated,
|
||||
currentSessionId,
|
||||
currentAgentName,
|
||||
currentProviderId,
|
||||
currentModelId,
|
||||
providers,
|
||||
agents,
|
||||
getAgentModelForSession,
|
||||
tryApplyModelSelection,
|
||||
setAgent,
|
||||
sessionSavedAgentName,
|
||||
sync,
|
||||
]);
|
||||
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -2,7 +2,9 @@ import React from 'react';
|
||||
import { RiCheckLine, RiCloseLine, RiFileEditLine, RiGlobalLine, RiPencilAiLine, RiQuestionLine, RiTerminalBoxLine, RiTimeLine, RiToolsLine } from '@remixicon/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { PermissionRequest, PermissionResponse } from '@/types/permission';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSessions } from '@/sync/sync-context';
|
||||
import * as sessionActions from '@/sync/session-actions';
|
||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
||||
import { useThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { generateSyntaxTheme } from '@/lib/theme/syntaxThemeGenerator';
|
||||
@@ -62,15 +64,14 @@ export const PermissionCard: React.FC<PermissionCardProps> = ({
|
||||
}) => {
|
||||
const [isResponding, setIsResponding] = React.useState(false);
|
||||
const [hasResponded, setHasResponded] = React.useState(false);
|
||||
const { respondToPermission } = useSessionStore();
|
||||
const isFromSubagent = useSessionStore(
|
||||
React.useCallback((state) => {
|
||||
const currentSessionId = state.currentSessionId;
|
||||
if (!currentSessionId || permission.sessionID === currentSessionId) return false;
|
||||
const sourceSession = state.sessions.find((session) => session.id === permission.sessionID);
|
||||
return Boolean(sourceSession?.parentID && sourceSession.parentID === currentSessionId);
|
||||
}, [permission.sessionID])
|
||||
);
|
||||
const respondToPermission = sessionActions.respondToPermission;;
|
||||
const sessions = useSessions();
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const isFromSubagent = React.useMemo(() => {
|
||||
if (!currentSessionId || permission.sessionID === currentSessionId) return false;
|
||||
const sourceSession = sessions.find((session) => session.id === permission.sessionID);
|
||||
return Boolean(sourceSession?.parentID && sourceSession.parentID === currentSessionId);
|
||||
}, [permission.sessionID, currentSessionId, sessions]);
|
||||
const { currentTheme } = useThemeSystem();
|
||||
const syntaxTheme = React.useMemo(() => generateSyntaxTheme(currentTheme), [currentTheme]);
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import React from 'react';
|
||||
import { RiCheckLine, RiCloseLine, RiTimeLine } from '@remixicon/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { PermissionRequest as PermissionRequestPayload, PermissionResponse } from '@/types/permission';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import * as sessionActions from '@/sync/session-actions';
|
||||
|
||||
interface PermissionRequestProps {
|
||||
permission: PermissionRequestPayload;
|
||||
@@ -15,7 +15,7 @@ export const PermissionRequest: React.FC<PermissionRequestProps> = ({
|
||||
}) => {
|
||||
const [isResponding, setIsResponding] = React.useState(false);
|
||||
const [hasResponded, setHasResponded] = React.useState(false);
|
||||
const { respondToPermission } = useSessionStore();
|
||||
const respondToPermission = sessionActions.respondToPermission;;
|
||||
|
||||
const handleResponse = async (response: PermissionResponse) => {
|
||||
setIsResponding(true);
|
||||
|
||||
@@ -4,7 +4,9 @@ import { Checkbox } from '@/components/ui/checkbox';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { QuestionRequest } from '@/types/question';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSessions } from '@/sync/sync-context';
|
||||
import * as sessionActions from '@/sync/session-actions';
|
||||
|
||||
interface QuestionCardProps {
|
||||
question: QuestionRequest;
|
||||
@@ -14,15 +16,15 @@ type TabKey = string;
|
||||
const SUMMARY_TAB = 'summary';
|
||||
|
||||
export const QuestionCard: React.FC<QuestionCardProps> = ({ question }) => {
|
||||
const { respondToQuestion, rejectQuestion } = useSessionStore();
|
||||
const isFromSubagent = useSessionStore(
|
||||
React.useCallback((state) => {
|
||||
const currentSessionId = state.currentSessionId;
|
||||
if (!currentSessionId || question.sessionID === currentSessionId) return false;
|
||||
const sourceSession = state.sessions.find((session) => session.id === question.sessionID);
|
||||
return Boolean(sourceSession?.parentID && sourceSession.parentID === currentSessionId);
|
||||
}, [question.sessionID])
|
||||
);
|
||||
const respondToQuestion = sessionActions.respondToQuestion;
|
||||
const rejectQuestion = sessionActions.rejectQuestion;;
|
||||
const sessions = useSessions();
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const isFromSubagent = React.useMemo(() => {
|
||||
if (!currentSessionId || question.sessionID === currentSessionId) return false;
|
||||
const sourceSession = sessions.find((session) => session.id === question.sessionID);
|
||||
return Boolean(sourceSession?.parentID && sourceSession.parentID === currentSessionId);
|
||||
}, [question.sessionID, currentSessionId, sessions]);
|
||||
const [activeTab, setActiveTab] = React.useState<TabKey>('0');
|
||||
const [isResponding, setIsResponding] = React.useState(false);
|
||||
const [hasResponded, setHasResponded] = React.useState(false);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import React, { memo } from 'react';
|
||||
import { RiCloseLine, RiMessage2Line } from '@remixicon/react';
|
||||
import { useMessageQueueStore, type QueuedMessage } from '@/stores/messageQueueStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useFileStore } from '@/stores/fileStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useInputStore } from '@/sync/input-store';
|
||||
|
||||
interface QueuedMessageChipProps {
|
||||
message: QueuedMessage;
|
||||
@@ -67,7 +67,7 @@ interface QueuedMessageChipsProps {
|
||||
const EMPTY_QUEUE: QueuedMessage[] = [];
|
||||
|
||||
export const QueuedMessageChips = memo(({ onEditMessage }: QueuedMessageChipsProps) => {
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const queuedMessages = useMessageQueueStore(
|
||||
React.useCallback(
|
||||
(state) => {
|
||||
@@ -84,10 +84,9 @@ export const QueuedMessageChips = memo(({ onEditMessage }: QueuedMessageChipsPro
|
||||
|
||||
const popped = popToInput(currentSessionId, message.id);
|
||||
if (popped) {
|
||||
// Restore attachments to file store if any
|
||||
if (popped.attachments && popped.attachments.length > 0) {
|
||||
const currentAttachments = useFileStore.getState().attachedFiles;
|
||||
useFileStore.setState({
|
||||
const currentAttachments = useInputStore.getState().attachedFiles;
|
||||
useInputStore.setState({
|
||||
attachedFiles: [...currentAttachments, ...popped.attachments]
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useContextStore } from '@/stores/contextStore';
|
||||
import { formatEffortLabel, getAgentDisplayName, getModelDisplayName } from './mobileControlsUtils';
|
||||
|
||||
@@ -19,7 +19,7 @@ export const StatusChip: React.FC<StatusChipProps> = ({ onClick, className }) =>
|
||||
getCurrentModelVariants,
|
||||
getVisibleAgents,
|
||||
} = useConfigStore();
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const sessionAgentName = useContextStore((state) =>
|
||||
currentSessionId ? state.getSessionAgentSelection(currentSessionId) : null
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React from "react";
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import {
|
||||
RiArrowDownSLine,
|
||||
RiArrowUpDoubleLine,
|
||||
@@ -9,8 +10,13 @@ import {
|
||||
RiTimeLine,
|
||||
} from "@remixicon/react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTodoStore, type TodoItem, type TodoPriority, type TodoStatus } from "@/stores/useTodoStore";
|
||||
import { useSessionStore } from "@/stores/useSessionStore";
|
||||
import { useDirectorySync } from "@/sync/sync-context";
|
||||
import type { Todo } from "@opencode-ai/sdk/v2/client";
|
||||
|
||||
// Compat aliases for old TodoItem shape
|
||||
type TodoItem = Todo & { id?: string };
|
||||
type TodoStatus = string;
|
||||
type TodoPriority = string;
|
||||
import { useUIStore } from "@/stores/useUIStore";
|
||||
import { WorkingPlaceholder } from "./message/parts/WorkingPlaceholder";
|
||||
import { isVSCodeRuntime } from "@/lib/desktop";
|
||||
@@ -146,21 +152,15 @@ export const StatusRow: React.FC<StatusRowProps> = ({
|
||||
agentName,
|
||||
}) => {
|
||||
const [isExpanded, setIsExpanded] = React.useState(false);
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const todos = useTodoStore((state) =>
|
||||
currentSessionId ? state.sessionTodos.get(currentSessionId) ?? EMPTY_TODOS : EMPTY_TODOS
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const todosRecord = useDirectorySync((state) => state.todo);
|
||||
const todos: TodoItem[] = React.useMemo(
|
||||
() => (currentSessionId ? todosRecord[currentSessionId] ?? EMPTY_TODOS : EMPTY_TODOS),
|
||||
[todosRecord, currentSessionId],
|
||||
);
|
||||
const loadTodos = useTodoStore((state) => state.loadTodos);
|
||||
const { isMobile } = useUIStore();
|
||||
const isCompact = isMobile || isVSCodeRuntime();
|
||||
|
||||
// Load todos when session changes
|
||||
React.useEffect(() => {
|
||||
if (currentSessionId) {
|
||||
void loadTodos(currentSessionId);
|
||||
}
|
||||
}, [currentSessionId, loadTodos]);
|
||||
|
||||
// Filter out cancelled todos for display and keep original order.
|
||||
// This prevents items from jumping around when status changes.
|
||||
const visibleTodos = React.useMemo(() => {
|
||||
@@ -313,8 +313,8 @@ export const StatusRow: React.FC<StatusRowProps> = ({
|
||||
|
||||
{/* Todo list */}
|
||||
<div className="px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border">
|
||||
{visibleTodos.map((todo) => (
|
||||
<TodoItemRow key={todo.id} todo={todo} />
|
||||
{visibleTodos.map((todo, index) => (
|
||||
<TodoItemRow key={todo.id ?? `todo-${index}`} todo={todo} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import React from 'react';
|
||||
import { useAssistantStatus } from '@/hooks/useAssistantStatus';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { StatusRow } from './StatusRow';
|
||||
|
||||
/**
|
||||
* Self-contained wrapper — subscribes to assistant status internally
|
||||
* so MessageList doesn't re-render on every streaming part delta.
|
||||
*/
|
||||
export const StatusRowContainer: React.FC = React.memo(() => {
|
||||
const { working } = useAssistantStatus();
|
||||
const currentAgentName = useConfigStore((state) => state.currentAgentName);
|
||||
|
||||
return (
|
||||
<StatusRow
|
||||
isWorking={working.isWorking}
|
||||
statusText={working.statusText}
|
||||
isGenericStatus={working.isGenericStatus}
|
||||
isWaitingForPermission={working.isWaitingForPermission}
|
||||
wasAborted={working.wasAborted}
|
||||
abortActive={working.abortActive}
|
||||
retryInfo={working.retryInfo}
|
||||
showAssistantStatus
|
||||
showTodos={false}
|
||||
agentName={currentAgentName}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
StatusRowContainer.displayName = 'StatusRowContainer';
|
||||
@@ -7,8 +7,8 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useMessageStore } from '@/stores/messageStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSessionMessageRecords } from '@/sync/sync-context';
|
||||
import { RiLoader4Line, RiSearchLine, RiTimeLine, RiGitBranchLine, RiArrowGoBackLine } from '@remixicon/react';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import type { Part } from '@opencode-ai/sdk/v2';
|
||||
@@ -44,13 +44,10 @@ export const TimelineDialog: React.FC<TimelineDialogProps> = ({
|
||||
onScrollByTurnOffset,
|
||||
onResumeToLatest,
|
||||
}) => {
|
||||
const currentSessionId = useSessionStore((state) => state.currentSessionId);
|
||||
const messages = useMessageStore((state) =>
|
||||
currentSessionId ? state.messages.get(currentSessionId) || [] : []
|
||||
);
|
||||
const revertToMessage = useSessionStore((state) => state.revertToMessage);
|
||||
const forkFromMessage = useSessionStore((state) => state.forkFromMessage);
|
||||
const loadSessions = useSessionStore((state) => state.loadSessions);
|
||||
const currentSessionId = useSessionUIStore((state) => state.currentSessionId);
|
||||
const messages = useSessionMessageRecords(currentSessionId ?? '');
|
||||
const revertToMessage = useSessionUIStore((state) => state.revertToMessage);
|
||||
const forkFromMessage = useSessionUIStore((state) => state.forkFromMessage);
|
||||
|
||||
const [forkingMessageId, setForkingMessageId] = React.useState<string | null>(null);
|
||||
const [searchQuery, setSearchQuery] = React.useState('');
|
||||
@@ -78,7 +75,6 @@ export const TimelineDialog: React.FC<TimelineDialogProps> = ({
|
||||
setForkingMessageId(messageId);
|
||||
try {
|
||||
await forkFromMessage(currentSessionId, messageId);
|
||||
await loadSessions();
|
||||
onOpenChange(false);
|
||||
} finally {
|
||||
setForkingMessageId(null);
|
||||
|
||||
@@ -3,7 +3,8 @@ import { MobileOverlayPanel } from '@/components/ui/MobileOverlayPanel';
|
||||
import { ProviderLogo } from '@/components/ui/ProviderLogo';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useConfigStore } from '@/stores/useConfigStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSelectionStore } from '@/sync/selection-store';
|
||||
import { useContextStore } from '@/stores/contextStore';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useModelLists } from '@/hooks/useModelLists';
|
||||
@@ -55,11 +56,8 @@ export const UnifiedControlsDrawer: React.FC<UnifiedControlsDrawerProps> = ({
|
||||
} = useConfigStore();
|
||||
const { addRecentModel, addRecentEffort, recentEfforts } = useUIStore();
|
||||
const { recentModelsList } = useModelLists();
|
||||
const {
|
||||
currentSessionId,
|
||||
saveAgentModelForSession,
|
||||
saveAgentModelVariantForSession,
|
||||
} = useSessionStore();
|
||||
const currentSessionId = useSessionUIStore((s) => s.currentSessionId);
|
||||
const { saveAgentModelForSession, saveAgentModelVariantForSession } = useSelectionStore();
|
||||
const sessionAgentName = useContextStore((state) =>
|
||||
currentSessionId ? state.getSessionAgentSelection(currentSessionId) : null
|
||||
);
|
||||
|
||||
@@ -10,7 +10,18 @@ interface TurnListProps<TEntry extends TurnListEntry> {
|
||||
}
|
||||
|
||||
const TurnList = <TEntry extends TurnListEntry>({ entries, renderEntry }: TurnListProps<TEntry>): React.ReactElement => {
|
||||
return <>{entries.map((entry) => renderEntry(entry))}</>;
|
||||
return (
|
||||
<>
|
||||
{entries.map((entry) => (
|
||||
<div
|
||||
key={entry.key}
|
||||
data-turn-entry={entry.key}
|
||||
>
|
||||
{renderEntry(entry)}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(TurnList) as typeof TurnList;
|
||||
|
||||
@@ -141,7 +141,7 @@ export const useChatTimelineController = ({
|
||||
historyMetaRef.current = historyMeta;
|
||||
}, [historyMeta]);
|
||||
|
||||
React.useEffect(() => {
|
||||
React.useLayoutEffect(() => {
|
||||
if (initializedSessionRef.current === sessionId) {
|
||||
return;
|
||||
}
|
||||
@@ -153,11 +153,11 @@ export const useChatTimelineController = ({
|
||||
previousTurnCountRef.current = turnWindowModel.turnCount;
|
||||
}, [sessionId, turnWindowModel.turnCount]);
|
||||
|
||||
React.useEffect(() => {
|
||||
React.useLayoutEffect(() => {
|
||||
setTurnStart((current) => clampTurnStart(current, turnWindowModel.turnCount));
|
||||
}, [turnWindowModel.turnCount]);
|
||||
|
||||
React.useEffect(() => {
|
||||
React.useLayoutEffect(() => {
|
||||
const previousTurnCount = previousTurnCountRef.current;
|
||||
const nextTurnCount = turnWindowModel.turnCount;
|
||||
if (previousTurnCount === nextTurnCount) {
|
||||
@@ -180,6 +180,42 @@ export const useChatTimelineController = ({
|
||||
return windowMessagesByTurn(messages, turnWindowModel, turnStart);
|
||||
}, [messages, turnStart, turnWindowModel]);
|
||||
|
||||
// --- Synchronous scroll compensation for load-more / reveal ---
|
||||
// fetchOlderHistory and revealBufferedTurns store a snapshot here
|
||||
// before triggering the state change. useLayoutEffect consumes it
|
||||
// after React commits new DOM — before the browser paints.
|
||||
const prePrependScrollRef = React.useRef<{
|
||||
height: number;
|
||||
top: number;
|
||||
anchor: ViewportAnchor | null;
|
||||
} | null>(null);
|
||||
|
||||
React.useLayoutEffect(() => {
|
||||
const snap = prePrependScrollRef.current;
|
||||
const container = scrollRef.current;
|
||||
if (!snap || !container) return;
|
||||
prePrependScrollRef.current = null;
|
||||
|
||||
// Try anchor-based restoration first (pixel-perfect)
|
||||
if (snap.anchor) {
|
||||
const anchorEl = container.querySelector<HTMLElement>(
|
||||
`[data-message-id="${snap.anchor.messageId}"]`,
|
||||
);
|
||||
if (anchorEl) {
|
||||
const containerRect = container.getBoundingClientRect();
|
||||
const anchorTop = anchorEl.getBoundingClientRect().top - containerRect.top;
|
||||
container.scrollTop += anchorTop - snap.anchor.offsetTop;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: height-delta compensation
|
||||
const delta = container.scrollHeight - snap.height;
|
||||
if (delta > 0) {
|
||||
container.scrollTop = snap.top + delta;
|
||||
}
|
||||
}, [renderedMessages, scrollRef]);
|
||||
|
||||
const captureViewportAnchor = React.useCallback((): ViewportAnchor | null => {
|
||||
return messageListRef.current?.captureViewportAnchor() ?? null;
|
||||
}, [messageListRef]);
|
||||
@@ -188,35 +224,19 @@ export const useChatTimelineController = ({
|
||||
return messageListRef.current?.restoreViewportAnchor(anchor) ?? false;
|
||||
}, [messageListRef]);
|
||||
|
||||
const restoreViewportWithFallback = React.useCallback((input: {
|
||||
anchor: ViewportAnchor | null;
|
||||
previousHeight: number | null;
|
||||
previousTop: number | null;
|
||||
}) => {
|
||||
const container = scrollRef.current;
|
||||
if (input.anchor && restoreViewportAnchor(input.anchor)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!container || input.previousHeight === null || input.previousTop === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const heightDelta = container.scrollHeight - input.previousHeight;
|
||||
if (heightDelta !== 0) {
|
||||
container.scrollTop = input.previousTop + heightDelta;
|
||||
}
|
||||
}, [restoreViewportAnchor, scrollRef]);
|
||||
|
||||
const revealBufferedTurns = React.useCallback(async (): Promise<boolean> => {
|
||||
if (turnStartRef.current <= 0 || pendingRevealWorkRef.current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const anchor = captureViewportAnchor();
|
||||
const container = scrollRef.current;
|
||||
const previousHeight = container?.scrollHeight ?? null;
|
||||
const previousTop = container?.scrollTop ?? null;
|
||||
if (container) {
|
||||
prePrependScrollRef.current = {
|
||||
height: container.scrollHeight,
|
||||
top: container.scrollTop,
|
||||
anchor: captureViewportAnchor(),
|
||||
};
|
||||
}
|
||||
|
||||
setPendingRevealWork(true);
|
||||
setTurnStart((current) => {
|
||||
@@ -225,14 +245,9 @@ export const useChatTimelineController = ({
|
||||
});
|
||||
|
||||
await waitForFrames(1);
|
||||
restoreViewportWithFallback({
|
||||
anchor,
|
||||
previousHeight,
|
||||
previousTop,
|
||||
});
|
||||
setPendingRevealWork(false);
|
||||
return true;
|
||||
}, [captureViewportAnchor, restoreViewportWithFallback, scrollRef]);
|
||||
}, [captureViewportAnchor, scrollRef]);
|
||||
|
||||
const fetchOlderHistory = React.useCallback(async (input: {
|
||||
preserveViewport: boolean;
|
||||
@@ -244,16 +259,22 @@ export const useChatTimelineController = ({
|
||||
return false;
|
||||
}
|
||||
|
||||
const anchor = input.preserveViewport ? captureViewportAnchor() : null;
|
||||
const container = scrollRef.current;
|
||||
const previousHeight = input.preserveViewport ? (container?.scrollHeight ?? null) : null;
|
||||
const previousTop = input.preserveViewport ? (container?.scrollTop ?? null) : null;
|
||||
const beforeMessages = messagesRef.current;
|
||||
const beforeMessageCount = beforeMessages.length;
|
||||
const beforeOldestMessageId = beforeMessages[0]?.info?.id ?? null;
|
||||
const beforeLimit = historyMetaRef.current?.limit ?? getMemoryLimits().HISTORICAL_MESSAGES;
|
||||
|
||||
setPendingRevealWork(true);
|
||||
// Store scroll snapshot BEFORE the fetch so useLayoutEffect can
|
||||
// compensate synchronously when React commits the new messages.
|
||||
if (input.preserveViewport && container) {
|
||||
prePrependScrollRef.current = {
|
||||
height: container.scrollHeight,
|
||||
top: container.scrollTop,
|
||||
anchor: captureViewportAnchor(),
|
||||
};
|
||||
}
|
||||
|
||||
setIsLoadingOlder(true);
|
||||
|
||||
try {
|
||||
@@ -274,20 +295,11 @@ export const useChatTimelineController = ({
|
||||
&& typeof afterOldestMessageId === 'string'
|
||||
&& beforeOldestMessageId !== afterOldestMessageId);
|
||||
|
||||
if (input.preserveViewport) {
|
||||
restoreViewportWithFallback({
|
||||
anchor,
|
||||
previousHeight,
|
||||
previousTop,
|
||||
});
|
||||
}
|
||||
|
||||
return historyGrew || afterLimit > beforeLimit;
|
||||
} finally {
|
||||
setIsLoadingOlder(false);
|
||||
setPendingRevealWork(false);
|
||||
}
|
||||
}, [captureViewportAnchor, loadMoreMessages, restoreViewportWithFallback, scrollRef]);
|
||||
}, [captureViewportAnchor, loadMoreMessages, scrollRef]);
|
||||
|
||||
const loadEarlier = React.useCallback(async () => {
|
||||
if (await revealBufferedTurns()) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import React from 'react';
|
||||
import { projectTurnRecords } from '../lib/turns/projectTurnRecords';
|
||||
import { stabilizeTurnProjection } from '../lib/turns/stabilizeTurnProjection';
|
||||
import type { ChatMessageEntry, TurnProjectionResult } from '../lib/turns/types';
|
||||
import type { ChatMessageEntry, TurnProjectionResult, TurnRecord } from '../lib/turns/types';
|
||||
import { streamPerfMeasure } from '@/stores/utils/streamDebug';
|
||||
|
||||
interface UseTurnRecordsOptions {
|
||||
sessionKey?: string;
|
||||
showTextJustificationActivity: boolean;
|
||||
}
|
||||
|
||||
@@ -18,33 +20,59 @@ export const useTurnRecords = (
|
||||
options: UseTurnRecordsOptions,
|
||||
): TurnRecordsResult => {
|
||||
const previousProjectionRef = React.useRef<TurnProjectionResult | null>(null);
|
||||
const staticTurnsRef = React.useRef<TurnRecord[]>([]);
|
||||
const streamingTurnRef = React.useRef<TurnRecord | undefined>(undefined);
|
||||
|
||||
React.useEffect(() => {
|
||||
previousProjectionRef.current = null;
|
||||
}, [options.showTextJustificationActivity]);
|
||||
staticTurnsRef.current = [];
|
||||
streamingTurnRef.current = undefined;
|
||||
}, [options.sessionKey, options.showTextJustificationActivity]);
|
||||
|
||||
const projection = React.useMemo(() => {
|
||||
const rawProjection = projectTurnRecords(messages, {
|
||||
previousProjection: previousProjectionRef.current,
|
||||
showTextJustificationActivity: options.showTextJustificationActivity,
|
||||
return streamPerfMeasure('ui.turns.projection_ms', () => {
|
||||
const rawProjection = projectTurnRecords(messages, {
|
||||
previousProjection: previousProjectionRef.current,
|
||||
showTextJustificationActivity: options.showTextJustificationActivity,
|
||||
});
|
||||
const stabilizedProjection = stabilizeTurnProjection(rawProjection, previousProjectionRef.current);
|
||||
previousProjectionRef.current = stabilizedProjection;
|
||||
return stabilizedProjection;
|
||||
});
|
||||
const stabilizedProjection = stabilizeTurnProjection(rawProjection, previousProjectionRef.current);
|
||||
previousProjectionRef.current = stabilizedProjection;
|
||||
return stabilizedProjection;
|
||||
}, [messages, options.showTextJustificationActivity]);
|
||||
|
||||
const staticTurns = React.useMemo(() => {
|
||||
if (projection.turns.length <= 1) {
|
||||
return [];
|
||||
const nextStatic = projection.turns.length <= 1
|
||||
? []
|
||||
: projection.turns.slice(0, -1);
|
||||
const previousStatic = staticTurnsRef.current;
|
||||
|
||||
if (previousStatic.length === nextStatic.length) {
|
||||
let isSame = true;
|
||||
for (let index = 0; index < nextStatic.length; index += 1) {
|
||||
if (previousStatic[index] !== nextStatic[index]) {
|
||||
isSame = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isSame) {
|
||||
return previousStatic;
|
||||
}
|
||||
}
|
||||
return projection.turns.slice(0, -1);
|
||||
|
||||
staticTurnsRef.current = nextStatic;
|
||||
return nextStatic;
|
||||
}, [projection.turns]);
|
||||
|
||||
const streamingTurn = React.useMemo(() => {
|
||||
if (projection.turns.length === 0) {
|
||||
return undefined;
|
||||
const nextStreamingTurn = projection.turns.length === 0
|
||||
? undefined
|
||||
: projection.turns[projection.turns.length - 1];
|
||||
if (streamingTurnRef.current === nextStreamingTurn) {
|
||||
return streamingTurnRef.current;
|
||||
}
|
||||
return projection.turns[projection.turns.length - 1];
|
||||
streamingTurnRef.current = nextStreamingTurn;
|
||||
return nextStreamingTurn;
|
||||
}, [projection.turns]);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { SessionMemoryState } from '@/stores/types/sessionTypes';
|
||||
import type { SessionMemoryState } from '@/sync/viewport-store';
|
||||
|
||||
export interface TurnHistorySignalsInput {
|
||||
memoryState: SessionMemoryState | null;
|
||||
|
||||
@@ -171,16 +171,11 @@ export const projectTurnActivity = (input: ProjectActivityInput): ProjectActivit
|
||||
});
|
||||
|
||||
let firstWithAny: string | undefined;
|
||||
let cumulative = 0;
|
||||
for (const message of input.assistantMessages) {
|
||||
const count = countByMessage.get(message.info.id) ?? 0;
|
||||
if (count > 0 && !firstWithAny) {
|
||||
firstWithAny = message.info.id;
|
||||
}
|
||||
cumulative += count;
|
||||
if (cumulative >= 2) {
|
||||
return message.info.id;
|
||||
}
|
||||
}
|
||||
|
||||
return firstWithAny;
|
||||
|
||||
@@ -20,8 +20,8 @@ export interface StageTurnsResult {
|
||||
}
|
||||
|
||||
const DEFAULT_STAGE_CONFIG: TurnStageConfig = {
|
||||
init: 1,
|
||||
batch: 3,
|
||||
init: 10,
|
||||
batch: 8,
|
||||
};
|
||||
|
||||
export const getInitialStageCount = (total: number, config: TurnStageConfig): number => {
|
||||
|
||||
@@ -105,6 +105,7 @@ export type Turn = Pick<TurnRecord, 'turnId' | 'userMessage' | 'assistantMessage
|
||||
|
||||
export interface TurnGroupingContext {
|
||||
turnId: string;
|
||||
activityOwnerMessageId?: string;
|
||||
isFirstAssistantInTurn: boolean;
|
||||
isLastAssistantInTurn: boolean;
|
||||
summaryBody?: string;
|
||||
|
||||
@@ -19,7 +19,7 @@ import { ArrowsMerge } from '@/components/icons/ArrowsMerge';
|
||||
import type { ContentChangeReason } from '@/hooks/useChatScrollManager';
|
||||
|
||||
import { SimpleMarkdownRenderer } from '../MarkdownRenderer';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { flattenAssistantTextParts } from '@/lib/messages/messageText';
|
||||
import { MULTIRUN_EXECUTION_FORK_PROMPT_META_TEXT } from '@/lib/messages/executionMeta';
|
||||
@@ -35,6 +35,7 @@ import { ToolRevealOnMount } from './parts/ToolRevealOnMount';
|
||||
import { StaticToolRow } from './parts/ProgressiveGroup';
|
||||
import { isExpandableTool, isStandaloneTool } from './parts/toolRenderUtils';
|
||||
import TurnActivity from '../components/TurnActivity';
|
||||
import { areRenderRelevantPartsEqual } from './renderCompare';
|
||||
|
||||
type SubtaskPartLike = Part & {
|
||||
type: 'subtask';
|
||||
@@ -77,7 +78,7 @@ const normalizeSubtaskModel = (model: SubtaskPartLike['model']): string | null =
|
||||
|
||||
const UserSubtaskPart: React.FC<{ part: SubtaskPartLike }> = ({ part }) => {
|
||||
const [expanded, setExpanded] = React.useState(false);
|
||||
const setCurrentSession = useSessionStore((state) => state.setCurrentSession);
|
||||
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
|
||||
|
||||
const description = typeof part.description === 'string' ? part.description.trim() : '';
|
||||
const command = typeof part.command === 'string' ? part.command.trim() : '';
|
||||
@@ -254,6 +255,7 @@ const formatTurnDuration = (durationMs: number): string => {
|
||||
|
||||
|
||||
interface MessageBodyProps {
|
||||
sessionId?: string;
|
||||
messageId: string;
|
||||
parts: Part[];
|
||||
isUser: boolean;
|
||||
@@ -562,6 +564,7 @@ const UserMessageBody: React.FC<{
|
||||
};
|
||||
|
||||
const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
sessionId,
|
||||
messageId,
|
||||
parts,
|
||||
isMessageCompleted,
|
||||
@@ -696,7 +699,7 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
return visibleParts.filter((part) => part.type === 'text');
|
||||
}, [visibleParts]);
|
||||
|
||||
const createSessionFromAssistantMessage = useSessionStore((state) => state.createSessionFromAssistantMessage);
|
||||
const createSessionFromAssistantMessage = useSessionUIStore((state) => state.createSessionFromAssistantMessage);
|
||||
const openMultiRunLauncherWithPrompt = useUIStore((state) => state.openMultiRunLauncherWithPrompt);
|
||||
const chatRenderMode = useUIStore((state) => state.chatRenderMode);
|
||||
const isSortedRenderMode = chatRenderMode === 'sorted';
|
||||
@@ -1065,6 +1068,8 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
return all.filter((segment) => segment.anchorMessageId === messageId);
|
||||
}, [isSortedRenderMode, messageId, turnGroupingContext?.activityGroupSegments]);
|
||||
|
||||
const hasAnchoredActivitySegments = activityGroupSegmentsForMessage.length > 0;
|
||||
|
||||
const activityByPart = React.useMemo(() => {
|
||||
const byRef = new Map<Part, (typeof activityPartsForTurn)[number]>();
|
||||
const byId = new Map<string, (typeof activityPartsForTurn)[number]>();
|
||||
@@ -1092,9 +1097,14 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
}, [activityPartsForTurn]);
|
||||
|
||||
const toggleActivityGroup = turnGroupingContext?.toggleGroup;
|
||||
const isActivityOwnerMessage = !isSortedRenderMode
|
||||
|| !turnGroupingContext?.activityOwnerMessageId
|
||||
|| turnGroupingContext.activityOwnerMessageId === messageId
|
||||
|| hasAnchoredActivitySegments;
|
||||
|
||||
const shouldRenderActivityGroup = isSortedRenderMode
|
||||
&& activityGroupSegmentsForMessage.length > 0
|
||||
&& isActivityOwnerMessage
|
||||
&& hasAnchoredActivitySegments
|
||||
&& Boolean(toggleActivityGroup);
|
||||
|
||||
|
||||
@@ -1155,6 +1165,7 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
<AssistantTextPart
|
||||
key={`assistant-text-${messageId}-${i}`}
|
||||
part={part}
|
||||
sessionId={sessionId}
|
||||
messageId={messageId}
|
||||
streamPhase={streamPhase}
|
||||
chatRenderMode={chatRenderMode}
|
||||
@@ -1190,6 +1201,7 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
<AssistantTextPart
|
||||
key={`reasoning-${messageId}-${i}`}
|
||||
part={part}
|
||||
sessionId={sessionId}
|
||||
messageId={messageId}
|
||||
streamPhase={streamPhase}
|
||||
chatRenderMode={chatRenderMode}
|
||||
@@ -1206,8 +1218,13 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
const toolPart = part as ToolPartType;
|
||||
const toolName = toolPart.tool?.toLowerCase() ?? '';
|
||||
|
||||
if (isSortedRenderMode && !isActivityOwnerMessage) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const activity = activityByPart.get(part);
|
||||
if (activity?.kind === 'tool' && !isStandaloneTool(toolName)) {
|
||||
if (activity?.kind === 'tool' && (shouldRenderActivityGroup || !isStandaloneTool(toolName))) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
@@ -1279,8 +1296,10 @@ const AssistantMessageBody: React.FC<Omit<MessageBodyProps, 'isUser'>> = ({
|
||||
expandedTools,
|
||||
hasStopFinish,
|
||||
isMobile,
|
||||
isActivityOwnerMessage,
|
||||
isSortedRenderMode,
|
||||
messageId,
|
||||
sessionId,
|
||||
onContentChange,
|
||||
onShowPopup,
|
||||
onToggleTool,
|
||||
@@ -1525,4 +1544,37 @@ const MessageBody: React.FC<MessageBodyProps> = ({ isUser, ...props }) => {
|
||||
return <AssistantMessageBody {...props} />;
|
||||
};
|
||||
|
||||
export default React.memo(MessageBody);
|
||||
export default React.memo(MessageBody, (prev, next) => {
|
||||
return prev.sessionId === next.sessionId
|
||||
&& prev.messageId === next.messageId
|
||||
&& prev.isUser === next.isUser
|
||||
&& areRenderRelevantPartsEqual(prev.parts, next.parts)
|
||||
&& prev.isMessageCompleted === next.isMessageCompleted
|
||||
&& prev.messageFinish === next.messageFinish
|
||||
&& prev.messageCompletedAt === next.messageCompletedAt
|
||||
&& prev.messageCreatedAt === next.messageCreatedAt
|
||||
&& prev.syntaxTheme === next.syntaxTheme
|
||||
&& prev.isMobile === next.isMobile
|
||||
&& prev.hasTouchInput === next.hasTouchInput
|
||||
&& prev.copiedCode === next.copiedCode
|
||||
&& prev.expandedTools === next.expandedTools
|
||||
&& prev.streamPhase === next.streamPhase
|
||||
&& prev.allowAnimation === next.allowAnimation
|
||||
&& prev.shouldShowHeader === next.shouldShowHeader
|
||||
&& prev.hasTextContent === next.hasTextContent
|
||||
&& prev.copiedMessage === next.copiedMessage
|
||||
&& prev.showReasoningTraces === next.showReasoningTraces
|
||||
&& prev.agentMention === next.agentMention
|
||||
&& prev.turnGroupingContext === next.turnGroupingContext
|
||||
&& prev.errorMessage === next.errorMessage
|
||||
&& prev.userActionsMode === next.userActionsMode
|
||||
&& prev.stickyUserHeaderEnabled === next.stickyUserHeaderEnabled
|
||||
&& prev.onCopyCode === next.onCopyCode
|
||||
&& prev.onToggleTool === next.onToggleTool
|
||||
&& prev.onShowPopup === next.onShowPopup
|
||||
&& prev.onContentChange === next.onContentChange
|
||||
&& prev.onCopyMessage === next.onCopyMessage
|
||||
&& prev.onAuxiliaryContentComplete === next.onAuxiliaryContentComplete
|
||||
&& prev.onRevert === next.onRevert
|
||||
&& prev.onFork === next.onFork;
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useInputStore } from '@/sync/input-store';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { RiChatNewLine, RiAddLine, RiFileCopyLine } from '@remixicon/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -196,8 +197,8 @@ export const TextSelectionMenu: React.FC<TextSelectionMenuProps> = ({ containerR
|
||||
const pendingSelectionRef = React.useRef<SelectionPayload | null>(null);
|
||||
const openRafRef = React.useRef<number | null>(null);
|
||||
const isMenuVisibleRef = React.useRef(false);
|
||||
const createSession = useSessionStore((state) => state.createSession);
|
||||
const setPendingInputText = useSessionStore((state) => state.setPendingInputText);
|
||||
const createSession = useSessionUIStore((state) => state.createSession);
|
||||
const setPendingInputText = useInputStore((state) => state.setPendingInputText);
|
||||
const isMobile = useUIStore((state) => state.isMobile);
|
||||
|
||||
React.useEffect(() => {
|
||||
|
||||
@@ -5,11 +5,13 @@ import type { StreamPhase } from '../types';
|
||||
import type { ContentChangeReason } from '@/hooks/useChatScrollManager';
|
||||
import { useStreamingTextThrottle } from '../../hooks/useStreamingTextThrottle';
|
||||
import { resolveAssistantDisplayText, shouldRenderAssistantText } from './assistantTextVisibility';
|
||||
import { streamPerfCount, streamPerfObserve } from '@/stores/utils/streamDebug';
|
||||
|
||||
type PartWithText = Part & { text?: string; content?: string; value?: string; time?: { start?: number; end?: number } };
|
||||
|
||||
interface AssistantTextPartProps {
|
||||
part: Part;
|
||||
sessionId?: string;
|
||||
messageId: string;
|
||||
streamPhase: StreamPhase;
|
||||
chatRenderMode?: 'sorted' | 'live';
|
||||
@@ -22,6 +24,8 @@ const AssistantTextPart: React.FC<AssistantTextPartProps> = ({
|
||||
streamPhase,
|
||||
chatRenderMode = 'live',
|
||||
}) => {
|
||||
// Use part directly from props — parent provides the latest version from the store.
|
||||
// No store subscription here to avoid re-render cascade from unrelated delta events.
|
||||
const partWithText = part as PartWithText;
|
||||
const rawText = typeof partWithText.text === 'string' ? partWithText.text : '';
|
||||
const contentText = typeof partWithText.content === 'string' ? partWithText.content : '';
|
||||
@@ -33,6 +37,11 @@ const AssistantTextPart: React.FC<AssistantTextPartProps> = ({
|
||||
const isCooldownPhase = streamPhase === 'cooldown';
|
||||
const isStreaming = chatRenderMode === 'live' && (isStreamingPhase || isCooldownPhase);
|
||||
|
||||
streamPerfCount('ui.assistant_text_part.render');
|
||||
if (isStreaming) {
|
||||
streamPerfCount('ui.assistant_text_part.render.streaming');
|
||||
}
|
||||
|
||||
const throttledTextContent = useStreamingTextThrottle({
|
||||
text: textContent,
|
||||
isStreaming,
|
||||
@@ -45,32 +54,7 @@ const AssistantTextPart: React.FC<AssistantTextPartProps> = ({
|
||||
isStreaming,
|
||||
});
|
||||
|
||||
const lastDisplayLengthRef = React.useRef(0);
|
||||
React.useEffect(() => {
|
||||
if (!isStreaming || typeof window === 'undefined') {
|
||||
lastDisplayLengthRef.current = displayTextContent.length;
|
||||
return;
|
||||
}
|
||||
const debugEnabled = window.localStorage.getItem('openchamber_stream_debug') === '1';
|
||||
if (!debugEnabled) {
|
||||
lastDisplayLengthRef.current = displayTextContent.length;
|
||||
return;
|
||||
}
|
||||
if (displayTextContent.length < lastDisplayLengthRef.current) {
|
||||
console.info('[STREAM-TRACE] render_shrink', {
|
||||
messageId,
|
||||
partId: part.id,
|
||||
rawTextLen: rawText.length,
|
||||
contentLen: contentText.length,
|
||||
valueLen: valueText.length,
|
||||
chosenLen: textContent.length,
|
||||
throttledLen: throttledTextContent.length,
|
||||
displayLen: displayTextContent.length,
|
||||
prevDisplayLen: lastDisplayLengthRef.current,
|
||||
});
|
||||
}
|
||||
lastDisplayLengthRef.current = displayTextContent.length;
|
||||
}, [contentText.length, displayTextContent.length, isStreaming, messageId, part.id, rawText.length, textContent.length, throttledTextContent.length, valueText.length]);
|
||||
streamPerfObserve('ui.assistant_text_part.display_len', displayTextContent.length);
|
||||
|
||||
const time = partWithText.time;
|
||||
const isFinalized = Boolean(time && typeof time.end !== 'undefined');
|
||||
@@ -105,4 +89,4 @@ const AssistantTextPart: React.FC<AssistantTextPartProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default AssistantTextPart;
|
||||
export default React.memo(AssistantTextPart);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useDurationTickerNow } from './useDurationTicker';
|
||||
import { MarkdownRenderer } from '../../MarkdownRenderer';
|
||||
import { useStreamingTextThrottle } from '../../hooks/useStreamingTextThrottle';
|
||||
|
||||
type PartWithText = Part & { text?: string; content?: string; time?: { start?: number; end?: number } };
|
||||
|
||||
@@ -201,16 +202,21 @@ const ReasoningPart: React.FC<ReasoningPartProps> = ({
|
||||
const textContent = React.useMemo(() => cleanReasoningText(rawText), [rawText]);
|
||||
const time = partWithText.time;
|
||||
const isStreaming = chatRenderMode === 'live' && typeof time?.end !== 'number';
|
||||
const throttledText = useStreamingTextThrottle({
|
||||
text: textContent,
|
||||
isStreaming,
|
||||
identityKey: `${messageId}:${part.id ?? 'reasoning'}`,
|
||||
});
|
||||
|
||||
// Show reasoning even if time.end isn't set yet (during streaming)
|
||||
// Only hide if there's no text content
|
||||
if (!textContent || textContent.trim().length === 0) {
|
||||
if (!throttledText || throttledText.trim().length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ReasoningTimelineBlock
|
||||
text={textContent}
|
||||
text={throttledText}
|
||||
variant="thinking"
|
||||
onContentChange={onContentChange}
|
||||
blockId={part.id || `${messageId}-reasoning`}
|
||||
|
||||
@@ -11,7 +11,9 @@ import { toolDisplayStyles } from '@/lib/typography';
|
||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
||||
import { useOptionalThemeSystem } from '@/contexts/useThemeSystem';
|
||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||
import { useSessionStore } from '@/stores/useSessionStore';
|
||||
import { useSessionUIStore } from '@/sync/session-ui-store';
|
||||
import { useSessionMessageRecords } from '@/sync/sync-context';
|
||||
import { getSyncChildStores, getSyncDirectory } from '@/sync/sync-refs';
|
||||
import { useUIStore } from '@/stores/useUIStore';
|
||||
import { useSessionActivity } from '@/hooks/useSessionActivity';
|
||||
import { opencodeClient } from '@/lib/opencode/client';
|
||||
@@ -572,8 +574,6 @@ type TaskToolSummaryEntry = {
|
||||
|
||||
type SessionMessageWithParts = MessageRecord;
|
||||
|
||||
const EMPTY_SESSION_MESSAGES: SessionMessageWithParts[] = [];
|
||||
|
||||
const normalizeSessionIdCandidate = (value: unknown): string | undefined => {
|
||||
if (typeof value !== 'string') {
|
||||
return undefined;
|
||||
@@ -844,7 +844,7 @@ const TaskToolSummary: React.FC<{
|
||||
animateTailText?: boolean;
|
||||
isActive?: boolean;
|
||||
}> = ({ entries, isExpanded, isMobile, output, sessionId, onShowPopup, input, animateTailText = true, isActive = false }) => {
|
||||
const setCurrentSession = useSessionStore((state) => state.setCurrentSession);
|
||||
const setCurrentSession = useSessionUIStore((state) => state.setCurrentSession);
|
||||
const showToolFileIcons = useUIStore((state) => state.showToolFileIcons);
|
||||
const displayEntries = entries;
|
||||
|
||||
@@ -1674,14 +1674,7 @@ const ToolPart: React.FC<ToolPartProps> = ({
|
||||
return readTaskSessionIdFromOutput(taskOutputString);
|
||||
}, [isTaskTool, metadata, parsedTaskMetadata.sessionId, partMetadata, taskOutputString]);
|
||||
|
||||
const childSessionMessages = useSessionStore(
|
||||
React.useCallback((store) => {
|
||||
if (!taskSessionId) {
|
||||
return EMPTY_SESSION_MESSAGES;
|
||||
}
|
||||
return (store.messages.get(taskSessionId) as SessionMessageWithParts[] | undefined) ?? EMPTY_SESSION_MESSAGES;
|
||||
}, [taskSessionId])
|
||||
);
|
||||
const childSessionMessages = useSessionMessageRecords(taskSessionId ?? '');
|
||||
|
||||
const metadataTaskSummaryEntries = React.useMemo<TaskToolSummaryEntry[]>(() => {
|
||||
if (!isTaskTool) {
|
||||
@@ -1901,7 +1894,20 @@ const ToolPart: React.FC<ToolPartProps> = ({
|
||||
|
||||
taskPollLastSignatureRef.current = nextSignature;
|
||||
taskPollNoChangeCountRef.current = 0;
|
||||
useSessionStore.getState().syncMessages(taskSessionId, messages);
|
||||
// Inject fetched subagent messages into sync child store
|
||||
const childStores = getSyncChildStores();
|
||||
const dir = getSyncDirectory();
|
||||
childStores.update(dir, (prev) => {
|
||||
const records = messages as SessionMessageWithParts[];
|
||||
const partPatch: Record<string, import('@opencode-ai/sdk/v2').Part[]> = { ...prev.part };
|
||||
for (const rec of records) {
|
||||
partPatch[rec.info.id] = rec.parts;
|
||||
}
|
||||
return {
|
||||
message: { ...prev.message, [taskSessionId]: records.map((r) => r.info) as import('@opencode-ai/sdk/v2').Message[] },
|
||||
part: partPatch,
|
||||
};
|
||||
});
|
||||
} catch {
|
||||
// Ignore transient subagent fetch errors.
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { Message, Part } from '@opencode-ai/sdk/v2';
|
||||
|
||||
type MessageRecord = {
|
||||
info: Message;
|
||||
parts: Part[];
|
||||
};
|
||||
|
||||
const readPartId = (part: Part | undefined): string | null => {
|
||||
if (!part) return null;
|
||||
const candidate = (part as { id?: unknown }).id;
|
||||
return typeof candidate === 'string' && candidate.length > 0 ? candidate : null;
|
||||
};
|
||||
|
||||
const readToolStatus = (part: Part | undefined): string | null => {
|
||||
const status = (part as { state?: { status?: unknown } } | undefined)?.state?.status;
|
||||
return typeof status === 'string' ? status : null;
|
||||
};
|
||||
|
||||
const readPartTime = (part: Part | undefined) => {
|
||||
const time = (part as { time?: { start?: unknown; end?: unknown } } | undefined)?.time;
|
||||
return {
|
||||
start: typeof time?.start === 'number' ? time.start : null,
|
||||
end: typeof time?.end === 'number' ? time.end : null,
|
||||
};
|
||||
};
|
||||
|
||||
const readPartText = (part: Part | undefined): string => {
|
||||
const candidate = part as { text?: unknown; content?: unknown; value?: unknown } | undefined;
|
||||
if (!candidate) return '';
|
||||
const text = typeof candidate.text === 'string' ? candidate.text : '';
|
||||
const content = typeof candidate.content === 'string' ? candidate.content : '';
|
||||
const value = typeof candidate.value === 'string' ? candidate.value : '';
|
||||
return [text, content, value].reduce((best, next) => (next.length > best.length ? next : best), '');
|
||||
};
|
||||
|
||||
export const areRenderRelevantPartsEqual = (left: Part[], right: Part[]): boolean => {
|
||||
if (left === right) return true;
|
||||
if (left.length !== right.length) return false;
|
||||
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
const leftPart = left[index];
|
||||
const rightPart = right[index];
|
||||
|
||||
if (leftPart.type !== rightPart.type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const leftId = readPartId(leftPart);
|
||||
const rightId = readPartId(rightPart);
|
||||
if (leftId !== rightId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (leftPart.type === 'tool') {
|
||||
if (readToolStatus(leftPart) !== readToolStatus(rightPart)) {
|
||||
return false;
|
||||
}
|
||||
const leftTime = readPartTime(leftPart);
|
||||
const rightTime = readPartTime(rightPart);
|
||||
if (leftTime.start !== rightTime.start || leftTime.end !== rightTime.end) {
|
||||
return false;
|
||||
}
|
||||
const leftTool = (leftPart as { tool?: unknown }).tool;
|
||||
const rightTool = (rightPart as { tool?: unknown }).tool;
|
||||
if (leftTool !== rightTool) {
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const leftTime = readPartTime(leftPart);
|
||||
const rightTime = readPartTime(rightPart);
|
||||
if (leftTime.start !== rightTime.start || leftTime.end !== rightTime.end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (leftPart.type === 'text' || leftPart.type === 'reasoning') {
|
||||
if (readPartText(leftPart) !== readPartText(rightPart)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
export const areRenderRelevantMessageInfoEqual = (left: Message, right: Message): boolean => {
|
||||
if (left === right) return true;
|
||||
|
||||
return left.id === right.id
|
||||
&& left.role === right.role
|
||||
&& left.sessionID === right.sessionID
|
||||
&& (left as { finish?: unknown }).finish === (right as { finish?: unknown }).finish
|
||||
&& (left as { status?: unknown }).status === (right as { status?: unknown }).status
|
||||
&& (left as { mode?: unknown }).mode === (right as { mode?: unknown }).mode
|
||||
&& (left as { agent?: unknown }).agent === (right as { agent?: unknown }).agent
|
||||
&& (left as { providerID?: unknown }).providerID === (right as { providerID?: unknown }).providerID
|
||||
&& (left as { modelID?: unknown }).modelID === (right as { modelID?: unknown }).modelID
|
||||
&& (left as { variant?: unknown }).variant === (right as { variant?: unknown }).variant
|
||||
&& (left as { clientRole?: unknown }).clientRole === (right as { clientRole?: unknown }).clientRole
|
||||
&& (left as { userMessageMarker?: unknown }).userMessageMarker === (right as { userMessageMarker?: unknown }).userMessageMarker
|
||||
&& ((left as { time?: { created?: unknown; completed?: unknown } }).time?.created ?? null) === ((right as { time?: { created?: unknown; completed?: unknown } }).time?.created ?? null)
|
||||
&& ((left as { time?: { created?: unknown; completed?: unknown } }).time?.completed ?? null) === ((right as { time?: { created?: unknown; completed?: unknown } }).time?.completed ?? null);
|
||||
};
|
||||
|
||||
export const areRenderRelevantMessagesEqual = (left: MessageRecord, right: MessageRecord): boolean => {
|
||||
return areRenderRelevantMessageInfoEqual(left.info, right.info) && areRenderRelevantPartsEqual(left.parts, right.parts);
|
||||
};
|
||||
|
||||
export const areOptionalRenderRelevantMessagesEqual = (left?: MessageRecord, right?: MessageRecord): boolean => {
|
||||
if (!left || !right) {
|
||||
return left === right;
|
||||
}
|
||||
return areRenderRelevantMessagesEqual(left, right);
|
||||
};
|
||||
Reference in New Issue
Block a user