Two independent fixes: - opencode-server.ts: stripDcpTags() removes <dcp-message-id>…</dcp-message-id> tags from text deltas before they reach the frame/DB. Applied to all three text paths (session.next.text.delta, message.part.delta text field, handleUpdatedPart text type). Reasoning/tool paths untouched. - useWorkspacePanes.ts: module-level closedPaneStack (capped at 10) captures pane kind + chatIds on removePane and removeTab auto-remove. reopenPane() pops the stack and re-attaches a new pane to the existing chat ids (chats survive pane close server-side). hasClosedPanes drives conditional render. - ChatTabBar.tsx: [+] is now instant new-tab (no dropdown); split-pane dropdown (Columns2 icon) opens Chat/Term/Code in a new pane; reopen button (RotateCcw icon) appears when closed panes exist. - Workspace.tsx: pass reopenPane + hasClosedPanes through to ChatTabBar. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
736 lines
26 KiB
TypeScript
736 lines
26 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
import type { DragEvent } from 'react';
|
|
import { toast } from 'sonner';
|
|
import { api } from '@/api/client';
|
|
import type {
|
|
HtmlArtifactState,
|
|
MarkdownArtifactState,
|
|
WorkspacePane,
|
|
} from '@/api/types';
|
|
import { setActivePaneInfo, clearActivePane } from '@/hooks/useActivePane';
|
|
import { sessionEvents } from '@/hooks/sessionEvents';
|
|
|
|
export const MAX_PANES = 5;
|
|
// v1.12.1: legacy localStorage key. Read once on mount to seed the server
|
|
// for sessions still on per-device state, then deleted. Server is now
|
|
// authoritative via sessions.workspace_panes.
|
|
const LEGACY_STORAGE_KEY = 'boocode.workspace.panes';
|
|
const SAVE_DEBOUNCE_MS = 300;
|
|
|
|
function generateId(): string {
|
|
return crypto.randomUUID();
|
|
}
|
|
|
|
// v1.10.3: optional id arg lets addSplitPane lift id generation out of the
|
|
// setPanes updater so the new pane's id can be returned synchronously to the
|
|
// caller (needed for mobile URL state).
|
|
function emptyPane(id: string = generateId()): WorkspacePane {
|
|
return { id, kind: 'empty', chatIds: [], activeChatIdx: -1 };
|
|
}
|
|
|
|
function chatPane(chatId: string): WorkspacePane {
|
|
return { id: generateId(), kind: 'chat', chatId, chatIds: [chatId], activeChatIdx: 0 };
|
|
}
|
|
|
|
interface ClosedPaneEntry {
|
|
kind: WorkspacePane['kind'];
|
|
chatIds: string[];
|
|
activeChatIdx: number;
|
|
}
|
|
const MAX_CLOSED = 10;
|
|
const closedPaneStack: ClosedPaneEntry[] = [];
|
|
|
|
function pushClosed(pane: WorkspacePane): void {
|
|
if (pane.kind === 'empty' || pane.kind === 'settings') return;
|
|
if (pane.chatIds.length === 0) return;
|
|
closedPaneStack.push({ kind: pane.kind, chatIds: [...pane.chatIds], activeChatIdx: pane.activeChatIdx });
|
|
if (closedPaneStack.length > MAX_CLOSED) closedPaneStack.shift();
|
|
}
|
|
|
|
function chatNameForPaneKind(kind: 'coder' | 'terminal'): string {
|
|
return kind === 'coder' ? 'BooCoder' : 'Terminal';
|
|
}
|
|
|
|
function scopedPane(id: string, kind: 'coder' | 'terminal', chatId: string): WorkspacePane {
|
|
return { id, kind, chatId, chatIds: [chatId], activeChatIdx: 0 };
|
|
}
|
|
|
|
/** Active chat id for a pane row (chat / coder / terminal). */
|
|
export function activePaneChatId(pane: WorkspacePane): string | undefined {
|
|
const idx = pane.activeChatIdx ?? 0;
|
|
if (idx >= 0 && pane.chatIds?.[idx]) return pane.chatIds[idx];
|
|
return pane.chatId;
|
|
}
|
|
|
|
// v1.9: settings pane factory. No chats, no state beyond identity — the
|
|
// SettingsPane component renders Session/Project sections from the
|
|
// surrounding session/project.
|
|
function settingsPane(id: string = generateId()): WorkspacePane {
|
|
return { id, kind: 'settings', chatIds: [], activeChatIdx: -1 };
|
|
}
|
|
|
|
// v1.14.x-html-artifact-panes: artifact pane factories. Payload travels with
|
|
// the pane row so the sessions.workspace_panes jsonb survives reload.
|
|
function markdownArtifactPane(state: MarkdownArtifactState): WorkspacePane {
|
|
return {
|
|
id: generateId(),
|
|
kind: 'markdown_artifact',
|
|
chatIds: [],
|
|
activeChatIdx: -1,
|
|
markdown_artifact_state: state,
|
|
};
|
|
}
|
|
|
|
function htmlArtifactPane(state: HtmlArtifactState): WorkspacePane {
|
|
return {
|
|
id: generateId(),
|
|
kind: 'html_artifact',
|
|
chatIds: [],
|
|
activeChatIdx: -1,
|
|
html_artifact_state: state,
|
|
};
|
|
}
|
|
|
|
// v1.9: settings panes are ephemeral. Filter them out before persisting so a
|
|
// page reload always returns to a clean workspace; the user re-opens via the
|
|
// sidebar Settings button when needed.
|
|
function normalizePaneKind(pane: WorkspacePane): WorkspacePane {
|
|
// v2.3: server once accepted legacy 'agent' before 'coder' landed in the schema.
|
|
if ((pane.kind as string) === 'agent') {
|
|
return { ...pane, kind: 'coder' };
|
|
}
|
|
return pane;
|
|
}
|
|
|
|
function normalizePanes(panes: WorkspacePane[]): WorkspacePane[] {
|
|
return panes.map(normalizePaneKind);
|
|
}
|
|
|
|
function persistablePanes(panes: WorkspacePane[]): WorkspacePane[] {
|
|
return normalizePanes(panes).filter((p) => p.kind !== 'settings');
|
|
}
|
|
|
|
// v1.9: per recon decision (c), settings panes don't count toward MAX_PANES.
|
|
// Helper used at every pane-insertion site so the rule lives in one place.
|
|
function nonSettingsCount(panes: WorkspacePane[]): number {
|
|
return panes.reduce((n, p) => n + (p.kind === 'settings' ? 0 : 1), 0);
|
|
}
|
|
|
|
// v1.12.1: read legacy per-device localStorage. If present, the caller seeds
|
|
// the server then deletes the key. One-time migration per session.
|
|
function readLegacyPanes(sessionId: string): WorkspacePane[] | null {
|
|
try {
|
|
const raw = localStorage.getItem(`${LEGACY_STORAGE_KEY}.${sessionId}`);
|
|
if (!raw) return null;
|
|
const parsed = JSON.parse(raw) as WorkspacePane[];
|
|
if (!Array.isArray(parsed) || parsed.length === 0) return null;
|
|
return parsed;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export interface UseWorkspacePanesResult {
|
|
panes: WorkspacePane[];
|
|
activePaneIdx: number;
|
|
setActivePaneIdx: React.Dispatch<React.SetStateAction<number>>;
|
|
activePaneIdxRef: React.MutableRefObject<number>;
|
|
openChatInPane: (paneIdx: number, chatId: string) => void;
|
|
switchTab: (paneIdx: number, tabIdx: number) => void;
|
|
removeTab: (paneIdx: number, chatId: string) => void;
|
|
closeOtherTabs: (paneIdx: number, keepChatId: string) => void;
|
|
closeTabsToRight: (paneIdx: number, pivotChatId: string) => void;
|
|
closeAllTabs: (paneIdx: number) => void;
|
|
showLandingPage: (paneIdx: number) => void;
|
|
// v1.10.3: returns the new pane's id (or null if the operation was a no-op:
|
|
// max panes reached). Callers can use the
|
|
// id to update mobile URL state so the URL-sync effect doesn't fight the
|
|
// freshly-set activePaneIdx.
|
|
addSplitPane: (kind: 'chat' | 'terminal' | 'coder') => string | null;
|
|
// Open-on-first-click, close-on-second-click. Singleton — settings panes
|
|
// don't count toward MAX_PANES. Closing the only remaining pane (edge case)
|
|
// falls back to an empty pane to preserve the "always one pane" invariant.
|
|
toggleSettingsPane: () => string | null;
|
|
removePane: (idx: number) => void;
|
|
reopenPane: () => void;
|
|
hasClosedPanes: boolean;
|
|
removeChatFromPanes: (chatId: string) => void;
|
|
initializeFirstChatIfEmpty: (chatId: string) => void;
|
|
validatePanes: (validChatIds: Set<string>) => void;
|
|
/** True while a coder/terminal pane is waiting for its scoped chat row. */
|
|
isPaneChatPending: (paneId: string) => boolean;
|
|
handlePaneDragStart: (idx: number) => (e: DragEvent<HTMLDivElement>) => void;
|
|
handlePaneDragOver: (idx: number) => (e: DragEvent<HTMLDivElement>) => void;
|
|
handlePaneDragLeave: () => void;
|
|
handlePaneDrop: (targetIdx: number) => (e: DragEvent<HTMLDivElement>) => void;
|
|
handlePaneDragEnd: () => void;
|
|
dragOverIdx: number | null;
|
|
draggingIdxRef: React.MutableRefObject<number | null>;
|
|
}
|
|
|
|
export function useWorkspacePanes(sessionId: string): UseWorkspacePanesResult {
|
|
const [panes, setPanes] = useState<WorkspacePane[]>(() => [emptyPane()]);
|
|
const [activePaneIdx, setActivePaneIdx] = useState(0);
|
|
const draggingIdxRef = useRef<number | null>(null);
|
|
const [dragOverIdx, setDragOverIdx] = useState<number | null>(null);
|
|
// v1.12.1: skip PATCH while hydrating from the server. Without this, the
|
|
// initial [emptyPane()] would be saved over the server's real state before
|
|
// the GET resolves.
|
|
const hydratedRef = useRef(false);
|
|
// Tracks the last value broadcast by another device (or this one's own
|
|
// round-trip). If a PATCH would echo this exact payload, we skip the call.
|
|
const lastRemoteJsonRef = useRef<string>('[]');
|
|
const pendingPaneChatRef = useRef<Set<string>>(new Set());
|
|
const [pendingPaneChatIds, setPendingPaneChatIds] = useState<Set<string>>(() => new Set());
|
|
|
|
const markPaneChatPending = useCallback((paneId: string, pending: boolean) => {
|
|
setPendingPaneChatIds((prev) => {
|
|
const next = new Set(prev);
|
|
if (pending) next.add(paneId);
|
|
else next.delete(paneId);
|
|
pendingPaneChatRef.current = next;
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const attachChatToPane = useCallback(
|
|
(paneId: string, chatId: string, kind: 'coder' | 'terminal') => {
|
|
setPanes((prev) =>
|
|
prev.map((p) => (p.id === paneId ? scopedPane(paneId, kind, chatId) : p)),
|
|
);
|
|
},
|
|
[],
|
|
);
|
|
|
|
const seedPaneChat = useCallback(
|
|
async (paneId: string, kind: 'coder' | 'terminal') => {
|
|
if (pendingPaneChatRef.current.has(paneId)) return;
|
|
markPaneChatPending(paneId, true);
|
|
try {
|
|
const chat = await api.chats.create(sessionId, { name: chatNameForPaneKind(kind) });
|
|
attachChatToPane(paneId, chat.id, kind);
|
|
} catch (err) {
|
|
toast.error(err instanceof Error ? err.message : 'Failed to create pane chat');
|
|
} finally {
|
|
markPaneChatPending(paneId, false);
|
|
}
|
|
},
|
|
[sessionId, attachChatToPane, markPaneChatPending],
|
|
);
|
|
|
|
const seedEmptyScopedPanes = useCallback(
|
|
(paneList: WorkspacePane[]) => {
|
|
for (const pane of paneList) {
|
|
if (pane.kind !== 'coder' && pane.kind !== 'terminal') continue;
|
|
if ((pane.chatIds?.length ?? 0) > 0 || pane.chatId) continue;
|
|
void seedPaneChat(pane.id, pane.kind);
|
|
}
|
|
},
|
|
[seedPaneChat],
|
|
);
|
|
|
|
// v1.12.1: hydrate from server on mount, then subscribe to remote updates.
|
|
useEffect(() => {
|
|
hydratedRef.current = false;
|
|
let cancelled = false;
|
|
void (async () => {
|
|
try {
|
|
const session = await api.sessions.get(sessionId);
|
|
if (cancelled) return;
|
|
let initial: WorkspacePane[] = Array.isArray(session.workspace_panes)
|
|
? normalizePanes(session.workspace_panes)
|
|
: [];
|
|
// One-time migration: if server is empty but legacy localStorage has
|
|
// a layout, seed the server and delete the local key.
|
|
if (initial.length === 0) {
|
|
const legacy = readLegacyPanes(sessionId);
|
|
if (legacy && legacy.length > 0) {
|
|
try {
|
|
const updated = await api.sessions.updateWorkspacePanes(sessionId, legacy);
|
|
if (cancelled) return;
|
|
initial = updated.workspace_panes;
|
|
localStorage.removeItem(`${LEGACY_STORAGE_KEY}.${sessionId}`);
|
|
} catch {
|
|
initial = legacy;
|
|
}
|
|
}
|
|
}
|
|
const next = initial.length > 0 ? initial : [emptyPane()];
|
|
lastRemoteJsonRef.current = JSON.stringify(persistablePanes(next));
|
|
setPanes(next);
|
|
setActivePaneIdx(0);
|
|
seedEmptyScopedPanes(next);
|
|
} finally {
|
|
if (!cancelled) hydratedRef.current = true;
|
|
}
|
|
})();
|
|
return () => { cancelled = true; };
|
|
}, [sessionId, seedEmptyScopedPanes]);
|
|
|
|
// v1.12.1: live cross-device sync. Replace local state when another device
|
|
// (or our own write echo) lands a session_workspace_updated frame.
|
|
useEffect(() => {
|
|
return sessionEvents.subscribe((ev) => {
|
|
if (ev.type !== 'session_workspace_updated') return;
|
|
if (ev.session_id !== sessionId) return;
|
|
const incoming = normalizePanes(
|
|
Array.isArray(ev.workspace_panes) ? ev.workspace_panes : [],
|
|
);
|
|
const json = JSON.stringify(incoming);
|
|
if (json === lastRemoteJsonRef.current) return;
|
|
lastRemoteJsonRef.current = json;
|
|
setPanes(incoming.length > 0 ? incoming : [emptyPane()]);
|
|
setActivePaneIdx((prev) => Math.min(prev, Math.max(0, incoming.length - 1)));
|
|
seedEmptyScopedPanes(incoming.length > 0 ? incoming : [emptyPane()]);
|
|
});
|
|
}, [sessionId, seedEmptyScopedPanes]);
|
|
|
|
// v1.14.x-html-artifact-panes: ActionRow's "Open in pane" emits one of
|
|
// these per click. If a pane already exists for the same message_id, focus
|
|
// it instead of stacking a duplicate. Otherwise append (capped at MAX_PANES;
|
|
// settings panes don't count, matching addSplitPane's rule).
|
|
useEffect(() => {
|
|
return sessionEvents.subscribe((ev) => {
|
|
if (
|
|
ev.type !== 'open_markdown_artifact_pane' &&
|
|
ev.type !== 'open_html_artifact_pane'
|
|
) {
|
|
return;
|
|
}
|
|
setPanes((prev) => {
|
|
const targetKind: WorkspacePane['kind'] =
|
|
ev.type === 'open_html_artifact_pane' ? 'html_artifact' : 'markdown_artifact';
|
|
const messageId = ev.state.message_id;
|
|
const existingIdx = prev.findIndex((p) =>
|
|
p.kind === 'markdown_artifact'
|
|
? p.markdown_artifact_state?.message_id === messageId
|
|
: p.kind === 'html_artifact'
|
|
? p.html_artifact_state?.message_id === messageId
|
|
: false,
|
|
);
|
|
if (existingIdx >= 0) {
|
|
setActivePaneIdx(existingIdx);
|
|
return prev;
|
|
}
|
|
if (nonSettingsCount(prev) >= MAX_PANES) {
|
|
toast.error(`Maximum ${MAX_PANES} panes`);
|
|
return prev;
|
|
}
|
|
const newPane =
|
|
ev.type === 'open_html_artifact_pane'
|
|
? htmlArtifactPane(ev.state)
|
|
: markdownArtifactPane(ev.state);
|
|
// Defensive: assert kind matches for the discriminated union.
|
|
if (newPane.kind !== targetKind) return prev;
|
|
const next = [...prev, newPane];
|
|
setActivePaneIdx(next.length - 1);
|
|
return next;
|
|
});
|
|
});
|
|
}, []);
|
|
|
|
// v1.12.1: debounced PATCH on every change. Settings panes are stripped
|
|
// before saving (ephemeral per v1.9).
|
|
useEffect(() => {
|
|
if (!hydratedRef.current) return;
|
|
const payload = persistablePanes(panes);
|
|
const json = JSON.stringify(payload);
|
|
if (json === lastRemoteJsonRef.current) return;
|
|
const timer = setTimeout(() => {
|
|
lastRemoteJsonRef.current = json;
|
|
api.sessions.updateWorkspacePanes(sessionId, payload).catch(() => {
|
|
// Non-fatal: next change retries. Persistent failures surface via
|
|
// the network layer's existing reconnect toast.
|
|
});
|
|
}, SAVE_DEBOUNCE_MS);
|
|
return () => clearTimeout(timer);
|
|
}, [sessionId, panes]);
|
|
|
|
useEffect(() => {
|
|
const active = panes[activePaneIdx];
|
|
if (!active) {
|
|
clearActivePane();
|
|
return;
|
|
}
|
|
setActivePaneInfo({
|
|
sessionId,
|
|
paneId: active.id,
|
|
kind: active.kind,
|
|
activeFile: null,
|
|
});
|
|
}, [sessionId, panes, activePaneIdx]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
clearActivePane();
|
|
};
|
|
}, []);
|
|
|
|
const activePaneIdxRef = useRef(activePaneIdx);
|
|
activePaneIdxRef.current = activePaneIdx;
|
|
|
|
const openChatInPane = useCallback((paneIdx: number, chatId: string) => {
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const pane = next[paneIdx]!;
|
|
const existing = pane.chatIds.indexOf(chatId);
|
|
if (existing >= 0) {
|
|
next[paneIdx] = { ...pane, kind: 'chat', chatId, activeChatIdx: existing };
|
|
} else {
|
|
const newIds = [...pane.chatIds, chatId];
|
|
next[paneIdx] = {
|
|
...pane,
|
|
kind: 'chat',
|
|
chatId,
|
|
chatIds: newIds,
|
|
activeChatIdx: newIds.length - 1,
|
|
};
|
|
}
|
|
return next;
|
|
});
|
|
setActivePaneIdx(paneIdx);
|
|
}, []);
|
|
|
|
const switchTab = useCallback((paneIdx: number, tabIdx: number) => {
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const pane = next[paneIdx]!;
|
|
const chatId = pane.chatIds[tabIdx];
|
|
if (!chatId) return prev;
|
|
next[paneIdx] = { ...pane, chatId, activeChatIdx: tabIdx };
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const removeTab = useCallback((paneIdx: number, chatId: string) => {
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const pane = next[paneIdx]!;
|
|
const nextIds = pane.chatIds.filter((id) => id !== chatId);
|
|
if (nextIds.length === 0) {
|
|
if (next.length > 1) {
|
|
// Last tab closed and other panes exist — remove the whole pane
|
|
// instead of leaving an orphaned empty panel.
|
|
pushClosed(pane); setHasClosedPanes(true);
|
|
const spliced = next.filter((_, i) => i !== paneIdx);
|
|
setActivePaneIdx((ai) => Math.min(ai, spliced.length - 1));
|
|
return spliced;
|
|
}
|
|
next[paneIdx] = { ...pane, kind: 'empty', chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
|
} else {
|
|
const nextActiveIdx = Math.min(pane.activeChatIdx, nextIds.length - 1);
|
|
next[paneIdx] = {
|
|
...pane,
|
|
chatIds: nextIds,
|
|
activeChatIdx: nextActiveIdx,
|
|
chatId: nextIds[nextActiveIdx],
|
|
};
|
|
}
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
// Keep only the right-clicked tab open in this pane.
|
|
const closeOtherTabs = useCallback((paneIdx: number, keepChatId: string) => {
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const pane = next[paneIdx]!;
|
|
const keepIdx = pane.chatIds.indexOf(keepChatId);
|
|
if (keepIdx < 0) return prev;
|
|
next[paneIdx] = {
|
|
...pane,
|
|
kind: 'chat',
|
|
chatId: keepChatId,
|
|
chatIds: [keepChatId],
|
|
activeChatIdx: 0,
|
|
};
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
// Close every tab to the right of the right-clicked one.
|
|
const closeTabsToRight = useCallback((paneIdx: number, pivotChatId: string) => {
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const pane = next[paneIdx]!;
|
|
const pivotIdx = pane.chatIds.indexOf(pivotChatId);
|
|
if (pivotIdx < 0 || pivotIdx === pane.chatIds.length - 1) return prev;
|
|
const nextIds = pane.chatIds.slice(0, pivotIdx + 1);
|
|
const nextActiveIdx = Math.min(pane.activeChatIdx, nextIds.length - 1);
|
|
next[paneIdx] = {
|
|
...pane,
|
|
chatIds: nextIds,
|
|
activeChatIdx: nextActiveIdx,
|
|
chatId: nextIds[nextActiveIdx],
|
|
};
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
// Close every tab in this pane; land on landing page.
|
|
const closeAllTabs = useCallback((paneIdx: number) => {
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const pane = next[paneIdx]!;
|
|
next[paneIdx] = { ...pane, kind: 'empty', chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const showLandingPage = useCallback((paneIdx: number) => {
|
|
setPanes((prev) => {
|
|
const pane = prev[paneIdx];
|
|
// Coder/terminal panes are not chat hosts — history button is chat-only.
|
|
if (!pane || pane.kind === 'coder' || pane.kind === 'terminal') return prev;
|
|
const next = [...prev];
|
|
next[paneIdx] = { ...pane, kind: 'empty', chatId: undefined };
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
const addSplitPane = useCallback((kind: 'chat' | 'terminal' | 'coder'): string | null => {
|
|
// Generate the id outside the updater so we can return it deterministically.
|
|
// setPanes's updater can be invoked twice in strict mode; using a fixed id
|
|
// ensures both invocations agree and the returned id matches what landed.
|
|
const newPaneId = generateId();
|
|
let success = false;
|
|
setPanes((prev) => {
|
|
// v1.9: settings panes are excluded from the MAX cap (decision c).
|
|
if (nonSettingsCount(prev) >= MAX_PANES) {
|
|
toast.error(`Maximum ${MAX_PANES} panes`);
|
|
return prev;
|
|
}
|
|
const newPane =
|
|
kind === 'terminal'
|
|
? { id: newPaneId, kind: 'terminal' as const, chatIds: [] as string[], activeChatIdx: -1 }
|
|
: kind === 'coder'
|
|
? { id: newPaneId, kind: 'coder' as const, chatIds: [] as string[], activeChatIdx: -1 }
|
|
: emptyPane(newPaneId);
|
|
const next = [...prev, newPane];
|
|
setActivePaneIdx(next.length - 1);
|
|
success = true;
|
|
if (kind === 'terminal' || kind === 'coder') {
|
|
queueMicrotask(() => void seedPaneChat(newPaneId, kind));
|
|
}
|
|
return next;
|
|
});
|
|
return success ? newPaneId : null;
|
|
}, [seedPaneChat]);
|
|
|
|
// Returns the new settings pane id when one is OPENED (so mobile callers can
|
|
// push ?pane= atomically — see addPaneAndSwitch), or null when it was closed.
|
|
// Id generated outside the updater so a strict-mode double-invoke agrees.
|
|
const toggleSettingsPane = useCallback((): string | null => {
|
|
const newPaneId = generateId();
|
|
let openedId: string | null = null;
|
|
setPanes((prev) => {
|
|
const existingIdx = prev.findIndex((p) => p.kind === 'settings');
|
|
if (existingIdx < 0) {
|
|
const next = [...prev, settingsPane(newPaneId)];
|
|
setActivePaneIdx(next.length - 1);
|
|
openedId = newPaneId;
|
|
return next;
|
|
}
|
|
openedId = null;
|
|
if (prev.length <= 1) {
|
|
setActivePaneIdx(0);
|
|
return [emptyPane()];
|
|
}
|
|
const next = prev.filter((_, i) => i !== existingIdx);
|
|
setActivePaneIdx((ai) => Math.min(ai, next.length - 1));
|
|
return next;
|
|
});
|
|
return openedId;
|
|
}, []);
|
|
|
|
const removePane = useCallback((idx: number) => {
|
|
setPanes((prev) => {
|
|
if (prev.length <= 1) {
|
|
// Settings is the only kind that can be the last pane and still need
|
|
// closing (X / Esc / sidebar toggle). Fall back to empty.
|
|
if (prev[idx]?.kind === 'settings') {
|
|
setActivePaneIdx(0);
|
|
return [emptyPane()];
|
|
}
|
|
return prev;
|
|
}
|
|
// v1.10.8c: with per-pane tmux sessions, an unkilled session leaks until
|
|
// the next `tmux kill-server`. Fire-and-forget /kill on terminal removal.
|
|
// The endpoint is idempotent (404 on missing session) so a strict-mode
|
|
// double-invoke of the updater is safe.
|
|
const removed = prev[idx];
|
|
if (removed) { pushClosed(removed); setHasClosedPanes(true); }
|
|
if (removed?.kind === 'terminal') {
|
|
api.terminals.kill(sessionId, removed.id).catch(() => { /* non-fatal */ });
|
|
}
|
|
const next = prev.filter((_, i) => i !== idx);
|
|
setActivePaneIdx((ai) => Math.min(ai, next.length - 1));
|
|
return next;
|
|
});
|
|
}, [sessionId]);
|
|
|
|
const [hasClosedPanes, setHasClosedPanes] = useState(closedPaneStack.length > 0);
|
|
|
|
const reopenPane = useCallback(() => {
|
|
const entry = closedPaneStack.pop();
|
|
setHasClosedPanes(closedPaneStack.length > 0);
|
|
if (!entry) return;
|
|
setPanes((prev) => {
|
|
const restored: WorkspacePane = {
|
|
id: generateId(),
|
|
kind: entry.kind,
|
|
chatId: entry.chatIds[entry.activeChatIdx] ?? entry.chatIds[0],
|
|
chatIds: entry.chatIds,
|
|
activeChatIdx: Math.min(entry.activeChatIdx, entry.chatIds.length - 1),
|
|
};
|
|
const next = [...prev, restored];
|
|
setActivePaneIdx(next.length - 1);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
// Replaces a single empty default pane with a chat pane. Used by the initial
|
|
// chat fetch to land on the most-recent open chat if no saved pane state.
|
|
const initializeFirstChatIfEmpty = useCallback((chatId: string) => {
|
|
setPanes((prev) => {
|
|
if (prev.length === 1 && prev[0]!.kind === 'empty') {
|
|
return [chatPane(chatId)];
|
|
}
|
|
return prev;
|
|
});
|
|
}, []);
|
|
|
|
const validatePanes = useCallback((validChatIds: Set<string>) => {
|
|
setPanes((prev) => {
|
|
const cleaned = prev.map((pane) => {
|
|
const usesChat =
|
|
pane.kind === 'chat' || pane.kind === 'coder' || pane.kind === 'terminal';
|
|
if (!usesChat || pane.chatIds.length === 0) return pane;
|
|
const nextIds = pane.chatIds.filter((id) => validChatIds.has(id));
|
|
if (nextIds.length === pane.chatIds.length) return pane;
|
|
if (nextIds.length === 0) {
|
|
if (pane.kind === 'chat') {
|
|
return { ...pane, kind: 'empty' as const, chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
|
}
|
|
return { ...pane, chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
|
}
|
|
const nextActiveIdx = Math.min(pane.activeChatIdx, nextIds.length - 1);
|
|
return { ...pane, chatIds: nextIds, activeChatIdx: nextActiveIdx, chatId: nextIds[nextActiveIdx] };
|
|
});
|
|
const unchanged = cleaned.every((p, i) => p === prev[i]);
|
|
const next = unchanged ? prev : cleaned;
|
|
if (!unchanged) {
|
|
for (const pane of next) {
|
|
if (pane.kind === 'coder' && !activePaneChatId(pane)) {
|
|
queueMicrotask(() => void seedPaneChat(pane.id, 'coder'));
|
|
} else if (pane.kind === 'terminal' && !activePaneChatId(pane)) {
|
|
queueMicrotask(() => void seedPaneChat(pane.id, 'terminal'));
|
|
}
|
|
}
|
|
}
|
|
return next;
|
|
});
|
|
}, [seedPaneChat]);
|
|
|
|
const isPaneChatPending = useCallback(
|
|
(paneId: string) => pendingPaneChatIds.has(paneId),
|
|
[pendingPaneChatIds],
|
|
);
|
|
|
|
const removeChatFromPanes = useCallback((chatId: string) => {
|
|
setPanes((prev) => prev.map((p) => {
|
|
const idx = p.chatIds.indexOf(chatId);
|
|
if (idx < 0) return p;
|
|
const nextIds = p.chatIds.filter((id) => id !== chatId);
|
|
if (nextIds.length === 0) {
|
|
return { ...p, kind: 'empty' as const, chatId: undefined, chatIds: [], activeChatIdx: -1 };
|
|
}
|
|
const nextActiveIdx = Math.min(p.activeChatIdx, nextIds.length - 1);
|
|
return {
|
|
...p,
|
|
chatIds: nextIds,
|
|
activeChatIdx: nextActiveIdx,
|
|
chatId: nextIds[nextActiveIdx],
|
|
};
|
|
}));
|
|
}, []);
|
|
|
|
const handlePaneDragStart = useCallback(
|
|
(idx: number) => (e: DragEvent<HTMLDivElement>) => {
|
|
draggingIdxRef.current = idx;
|
|
e.dataTransfer.effectAllowed = 'move';
|
|
e.dataTransfer.setData('text/plain', String(idx));
|
|
},
|
|
[]
|
|
);
|
|
|
|
const handlePaneDragOver = useCallback(
|
|
(idx: number) => (e: DragEvent<HTMLDivElement>) => {
|
|
if (draggingIdxRef.current === null) return;
|
|
e.preventDefault();
|
|
e.dataTransfer.dropEffect = 'move';
|
|
if (dragOverIdx !== idx) setDragOverIdx(idx);
|
|
},
|
|
[dragOverIdx]
|
|
);
|
|
|
|
const handlePaneDragLeave = useCallback(() => {
|
|
setDragOverIdx(null);
|
|
}, []);
|
|
|
|
const handlePaneDrop = useCallback(
|
|
(targetIdx: number) => (e: DragEvent<HTMLDivElement>) => {
|
|
e.preventDefault();
|
|
const fromIdx = draggingIdxRef.current;
|
|
draggingIdxRef.current = null;
|
|
setDragOverIdx(null);
|
|
if (fromIdx === null || fromIdx === targetIdx) return;
|
|
setPanes((prev) => {
|
|
const next = [...prev];
|
|
const [moved] = next.splice(fromIdx, 1);
|
|
if (!moved) return prev;
|
|
next.splice(targetIdx, 0, moved);
|
|
// Keep active selection on the same logical pane (the one being dragged).
|
|
setActivePaneIdx(targetIdx);
|
|
return next;
|
|
});
|
|
},
|
|
[]
|
|
);
|
|
|
|
const handlePaneDragEnd = useCallback(() => {
|
|
draggingIdxRef.current = null;
|
|
setDragOverIdx(null);
|
|
}, []);
|
|
|
|
return {
|
|
panes,
|
|
activePaneIdx,
|
|
setActivePaneIdx,
|
|
activePaneIdxRef,
|
|
openChatInPane,
|
|
switchTab,
|
|
removeTab,
|
|
closeOtherTabs,
|
|
closeTabsToRight,
|
|
closeAllTabs,
|
|
showLandingPage,
|
|
addSplitPane,
|
|
toggleSettingsPane,
|
|
removePane,
|
|
reopenPane,
|
|
hasClosedPanes,
|
|
removeChatFromPanes,
|
|
initializeFirstChatIfEmpty,
|
|
validatePanes,
|
|
isPaneChatPending,
|
|
handlePaneDragStart,
|
|
handlePaneDragOver,
|
|
handlePaneDragLeave,
|
|
handlePaneDrop,
|
|
handlePaneDragEnd,
|
|
dragOverIdx,
|
|
draggingIdxRef,
|
|
};
|
|
}
|