feat(web): add dev debug logging for git-status, dockview, and chat messages (#961)
This commit is contained in:
@@ -7,9 +7,42 @@ import { measureDockviewContainer } from "@/lib/state/dockview-measure";
|
||||
import type { LayoutState } from "@/lib/state/layout-manager";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
import { getEnvLayout, getEnvMaximizeState, removeEnvMaximizeState } from "@/lib/local-storage";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("dockview:restore");
|
||||
|
||||
const LAYOUT_STORAGE_KEY = "dockview-layout-v1";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
function describeSanitizeMode(options: {
|
||||
stripSessionPanels?: boolean;
|
||||
excludeSessionIds?: Set<string>;
|
||||
}): string {
|
||||
if (options.stripSessionPanels) return "stripAllSessions";
|
||||
if (options.excludeSessionIds) return "excludeSpecificSessions";
|
||||
return "keepAll";
|
||||
}
|
||||
|
||||
function logSanitizeOutcome(
|
||||
options: { stripSessionPanels?: boolean; excludeSessionIds?: Set<string> },
|
||||
totalPanels: Record<string, any>,
|
||||
validPanels: Record<string, any>,
|
||||
invalidIds: Set<string>,
|
||||
): void {
|
||||
if (!IS_DEBUG) return;
|
||||
debug("sanitizeLayout", {
|
||||
mode: describeSanitizeMode(options),
|
||||
excludeSessionCount: options.excludeSessionIds?.size ?? 0,
|
||||
excludeSessionIds: options.excludeSessionIds
|
||||
? Array.from(options.excludeSessionIds)
|
||||
: undefined,
|
||||
totalPanels: Object.keys(totalPanels).length,
|
||||
keptPanels: Object.keys(validPanels).length,
|
||||
strippedPanels: Array.from(invalidIds),
|
||||
});
|
||||
}
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
export function sanitizeLayout(
|
||||
layout: any,
|
||||
@@ -18,7 +51,10 @@ export function sanitizeLayout(
|
||||
| { stripSessionPanels: true; excludeSessionIds?: never }
|
||||
| { stripSessionPanels?: false | undefined; excludeSessionIds?: Set<string> } = {},
|
||||
): any {
|
||||
if (!isLayoutShapeHealthy(layout)) return null;
|
||||
if (!isLayoutShapeHealthy(layout)) {
|
||||
debug("sanitizeLayout: layout shape unhealthy, returning null");
|
||||
return null;
|
||||
}
|
||||
|
||||
const invalidIds = new Set<string>();
|
||||
const validPanels: Record<string, any> = {};
|
||||
@@ -55,6 +91,8 @@ export function sanitizeLayout(
|
||||
}
|
||||
}
|
||||
|
||||
logSanitizeOutcome(options, layout.panels, validPanels, invalidIds);
|
||||
|
||||
if (invalidIds.size === 0) return layout;
|
||||
|
||||
function cleanNode(node: any): any {
|
||||
@@ -73,7 +111,10 @@ export function sanitizeLayout(
|
||||
}
|
||||
|
||||
const cleanedRoot = cleanNode(layout.grid.root);
|
||||
if (!cleanedRoot) return null;
|
||||
if (!cleanedRoot) {
|
||||
debug("sanitizeLayout: cleanedRoot is null after stripping, returning null");
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...layout,
|
||||
@@ -139,11 +180,33 @@ function tryRestoreEnvLayout(
|
||||
phantomSessionIds: Set<string> | undefined,
|
||||
): boolean {
|
||||
const envLayout = getEnvLayout(envId);
|
||||
if (!envLayout) return false;
|
||||
if (!envLayout) {
|
||||
debug("tryRestoreEnvLayout: no saved layout for env", { envId });
|
||||
return false;
|
||||
}
|
||||
if (IS_DEBUG) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const rawPanelIds = Object.keys((envLayout as any).panels ?? {});
|
||||
debug("tryRestoreEnvLayout: loaded saved layout", {
|
||||
envId,
|
||||
rawPanelCount: rawPanelIds.length,
|
||||
rawPanelIds,
|
||||
phantomSessionIds: phantomSessionIds ? Array.from(phantomSessionIds) : [],
|
||||
});
|
||||
}
|
||||
const sanitized = sanitizeLayout(envLayout, validComponents, {
|
||||
excludeSessionIds: phantomSessionIds,
|
||||
});
|
||||
if (!sanitized) return false;
|
||||
if (!sanitized) {
|
||||
debug("tryRestoreEnvLayout: sanitize returned null", { envId });
|
||||
return false;
|
||||
}
|
||||
if (IS_DEBUG) {
|
||||
debug("tryRestoreEnvLayout: calling api.fromJSON", {
|
||||
envId,
|
||||
sanitizedPanelIds: Object.keys(sanitized.panels),
|
||||
});
|
||||
}
|
||||
api.fromJSON(sanitized as SerializedDockview);
|
||||
applyFixupsWithMaximize(api, envId);
|
||||
return true;
|
||||
@@ -217,5 +280,21 @@ export function restoreEnvLayout(
|
||||
validComponents: Set<string>,
|
||||
): boolean {
|
||||
const phantoms = envId ? collectPhantomSessionIdsForEnv(appStore.getState(), envId) : undefined;
|
||||
return tryRestoreLayout(api, envId, validComponents, phantoms);
|
||||
if (IS_DEBUG) {
|
||||
debug("restoreEnvLayout: entry", {
|
||||
envId,
|
||||
phantomCount: phantoms?.size ?? 0,
|
||||
phantomSessionIds: phantoms ? Array.from(phantoms) : [],
|
||||
livePanelIdsBefore: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
const result = tryRestoreLayout(api, envId, validComponents, phantoms);
|
||||
if (IS_DEBUG) {
|
||||
debug("restoreEnvLayout: result", {
|
||||
envId,
|
||||
restored: result,
|
||||
livePanelIdsAfter: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import { focusOrAddPanel } from "@/lib/state/dockview-layout-builders";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { wasPRPanelOffered, markPRPanelOffered } from "@/lib/local-storage";
|
||||
import { sessionId as toSessionId } from "@/lib/types/ids";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("dockview:session-tabs");
|
||||
|
||||
/**
|
||||
* Sync `activeSessionId` in the store when the user clicks a session tab.
|
||||
@@ -234,6 +237,7 @@ export function reconcileRemovedSessionPanels(
|
||||
keepSessionId: string,
|
||||
): void {
|
||||
const currentIds = new Set(currentSessionIds);
|
||||
const removed: string[] = [];
|
||||
// Snapshot before iterating: closing a panel can mutate `api.panels`
|
||||
// synchronously, which would skip elements in a `for...of` over the live
|
||||
// array. Matches the pattern in `removeEphemeralPanels`.
|
||||
@@ -244,11 +248,22 @@ export function reconcileRemovedSessionPanels(
|
||||
if (currentIds.has(sid)) continue;
|
||||
try {
|
||||
panel.api.close();
|
||||
removed.push(panel.id);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
createdSet.delete(sid);
|
||||
}
|
||||
if (IS_DEBUG) {
|
||||
const sessionPanels = api.panels.filter((p) => p.id.startsWith("session:"));
|
||||
debug("reconcileRemovedSessionPanels", {
|
||||
keepSessionId,
|
||||
currentSessionIds,
|
||||
liveSessionPanelIds: sessionPanels.map((p) => p.id),
|
||||
removed,
|
||||
createdSetAfter: Array.from(createdSet),
|
||||
});
|
||||
}
|
||||
// Drop any remaining stale entries (panel already removed externally, e.g.
|
||||
// by the right-click delete handler) so the ref stays in sync with reality.
|
||||
for (const sid of [...createdSet]) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useSessionGitStatus, useSessionGitStatusByRepo } from "./use-session-gi
|
||||
import { useSessionCommits } from "./use-session-commits";
|
||||
import { useCumulativeDiff } from "./use-cumulative-diff";
|
||||
import { useGitOperations } from "@/hooks/use-git-operations";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
import type {
|
||||
FileInfo,
|
||||
SessionCommit,
|
||||
@@ -41,6 +42,8 @@ export type GitOperationResult = RawGitOperationResult & {
|
||||
|
||||
export type { PRCreateResult };
|
||||
|
||||
const debugDeriv = createDebugLogger("git-status:derive");
|
||||
|
||||
export type SessionGit = {
|
||||
// Branch info
|
||||
branch: string | null;
|
||||
@@ -596,6 +599,18 @@ function useFileDerivations(
|
||||
() => aggregateFilesAcrossRepos(statusByRepo, gitStatus),
|
||||
[statusByRepo, gitStatus],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!IS_DEBUG) return;
|
||||
debugDeriv("aggregate", {
|
||||
path: statusByRepo.length > 0 ? "multi-repo" : "single-repo-fallback",
|
||||
statusByRepoEntries: statusByRepo.map((s) => ({
|
||||
repo: s.repository_name,
|
||||
files: Object.keys(s.status?.files ?? {}).length,
|
||||
})),
|
||||
legacyGitStatusFiles: Object.keys(gitStatus?.files ?? {}).length,
|
||||
allFilesCount: allFiles.length,
|
||||
});
|
||||
}, [statusByRepo, gitStatus, allFiles]);
|
||||
const unstagedFiles = useMemo(() => allFiles.filter((f) => !f.staged), [allFiles]);
|
||||
const stagedFiles = useMemo(() => allFiles.filter((f) => f.staged), [allFiles]);
|
||||
const repoForPath = useMemo(() => {
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import type { Message } from "@/lib/types/http";
|
||||
|
||||
const mockListTaskSessionMessages = vi.fn();
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
listTaskSessionMessages: (...args: unknown[]) => mockListTaskSessionMessages(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/ws/connection", () => ({
|
||||
getWebSocketClient: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: () => null,
|
||||
useAppStoreApi: () => null,
|
||||
}));
|
||||
|
||||
import { taskId, sessionId } from "@/lib/types/ids";
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockListTaskSessionMessages.mockResolvedValue({ messages: [], has_more: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
import {
|
||||
hasUserOrAgentMessage,
|
||||
runBackfillRound,
|
||||
autoBackfillUntilUserMessage,
|
||||
} from "./use-session-messages";
|
||||
|
||||
function makeMessage(overrides: Partial<Message>): Message {
|
||||
return {
|
||||
id: "msg-1",
|
||||
task_id: taskId("task-1"),
|
||||
session_id: sessionId("sess-1"),
|
||||
author_type: "user",
|
||||
content: "hello",
|
||||
type: "message",
|
||||
created_at: "2024-01-01T00:00:00Z",
|
||||
...overrides,
|
||||
} as Message;
|
||||
}
|
||||
|
||||
/** Stateful store mock — prependMessages actually updates the stored messages. */
|
||||
function makeStore(options: {
|
||||
messages?: Message[];
|
||||
hasMore?: boolean;
|
||||
oldestCursor?: string | null;
|
||||
}) {
|
||||
let messages: Message[] = options.messages ?? [];
|
||||
let meta = {
|
||||
hasMore: options.hasMore ?? false,
|
||||
oldestCursor: options.oldestCursor ?? null,
|
||||
isLoading: false,
|
||||
};
|
||||
const prependMessages = vi.fn(
|
||||
(
|
||||
_sessionId: string,
|
||||
newMsgs: Message[],
|
||||
newMeta: { hasMore: boolean; oldestCursor: string | null },
|
||||
) => {
|
||||
messages = [...newMsgs, ...messages];
|
||||
meta = { ...meta, ...newMeta };
|
||||
},
|
||||
);
|
||||
return {
|
||||
getState: () => ({
|
||||
messages: {
|
||||
bySession: { "sess-1": messages },
|
||||
metaBySession: { "sess-1": meta },
|
||||
},
|
||||
prependMessages,
|
||||
}),
|
||||
_prependMessages: prependMessages,
|
||||
};
|
||||
}
|
||||
|
||||
describe("hasUserOrAgentMessage", () => {
|
||||
it("returns true for a user message", () => {
|
||||
expect(hasUserOrAgentMessage([makeMessage({ type: "message", author_type: "user" })])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns true for an agent message", () => {
|
||||
expect(hasUserOrAgentMessage([makeMessage({ type: "message", author_type: "agent" })])).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns false for tool_call only", () => {
|
||||
expect(hasUserOrAgentMessage([makeMessage({ type: "tool_call", author_type: "agent" })])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("returns false for empty array", () => {
|
||||
expect(hasUserOrAgentMessage([])).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true when mixed messages include a user message", () => {
|
||||
const msgs = [
|
||||
makeMessage({ id: "t1", type: "tool_call", author_type: "agent" }),
|
||||
makeMessage({ id: "u1", type: "message", author_type: "user" }),
|
||||
];
|
||||
expect(hasUserOrAgentMessage(msgs)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runBackfillRound", () => {
|
||||
it("returns 'stop' when a user/agent message already exists in the store", async () => {
|
||||
const store = makeStore({
|
||||
messages: [makeMessage({ type: "message", author_type: "user" })],
|
||||
hasMore: true,
|
||||
oldestCursor: "msg-1",
|
||||
});
|
||||
const result = await runBackfillRound("sess-1", store as never, 0);
|
||||
expect(result).toBe("stop");
|
||||
expect(mockListTaskSessionMessages).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 'stop' when hasMore is false", async () => {
|
||||
const store = makeStore({ messages: [], hasMore: false, oldestCursor: "msg-1" });
|
||||
const result = await runBackfillRound("sess-1", store as never, 0);
|
||||
expect(result).toBe("stop");
|
||||
});
|
||||
|
||||
it("returns 'stop' when oldestCursor is null", async () => {
|
||||
const store = makeStore({ messages: [], hasMore: true, oldestCursor: null });
|
||||
const result = await runBackfillRound("sess-1", store as never, 0);
|
||||
expect(result).toBe("stop");
|
||||
});
|
||||
|
||||
it("returns 'continue' and calls prependMessages when older messages are fetched", async () => {
|
||||
mockListTaskSessionMessages.mockResolvedValue({
|
||||
messages: [makeMessage({ id: "old-1" })],
|
||||
has_more: true,
|
||||
});
|
||||
const store = makeStore({ messages: [], hasMore: true, oldestCursor: "msg-1" });
|
||||
const result = await runBackfillRound("sess-1", store as never, 0);
|
||||
expect(result).toBe("continue");
|
||||
expect(store._prependMessages).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns 'stop' when fetched batch is empty", async () => {
|
||||
mockListTaskSessionMessages.mockResolvedValue({ messages: [], has_more: true });
|
||||
const store = makeStore({ messages: [], hasMore: true, oldestCursor: "msg-1" });
|
||||
const result = await runBackfillRound("sess-1", store as never, 0);
|
||||
expect(result).toBe("stop");
|
||||
});
|
||||
|
||||
it("returns 'stop' on fetch error", async () => {
|
||||
mockListTaskSessionMessages.mockRejectedValue(new Error("network error"));
|
||||
const store = makeStore({ messages: [], hasMore: true, oldestCursor: "msg-1" });
|
||||
const result = await runBackfillRound("sess-1", store as never, 0);
|
||||
expect(result).toBe("stop");
|
||||
});
|
||||
});
|
||||
|
||||
describe("autoBackfillUntilUserMessage", () => {
|
||||
it("stops after MAX_BACKFILL_ROUNDS (3) without finding a user/agent message", async () => {
|
||||
mockListTaskSessionMessages.mockResolvedValue({
|
||||
messages: [makeMessage({ id: "t1", type: "tool_call", author_type: "agent" })],
|
||||
has_more: true,
|
||||
});
|
||||
const store = makeStore({ messages: [], hasMore: true, oldestCursor: "cursor-0" });
|
||||
await autoBackfillUntilUserMessage("sess-1", store as never);
|
||||
expect(mockListTaskSessionMessages).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("stops after round 1 once a user message is prepended", async () => {
|
||||
mockListTaskSessionMessages.mockResolvedValue({
|
||||
messages: [makeMessage({ id: "u1", type: "message", author_type: "user" })],
|
||||
has_more: true,
|
||||
});
|
||||
const store = makeStore({ messages: [], hasMore: true, oldestCursor: "cursor-0" });
|
||||
await autoBackfillUntilUserMessage("sess-1", store as never);
|
||||
// After round 0, prependMessages adds the user message; round 1 finds it and stops.
|
||||
expect(mockListTaskSessionMessages).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,47 @@ import { useEffect, useMemo, useRef, useState, type MutableRefObject } from "rea
|
||||
import { getWebSocketClient } from "@/lib/ws/connection";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import type { TaskSessionState, Message } from "@/lib/types/http";
|
||||
import { listTaskSessionMessages } from "@/lib/api";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const INITIAL_FETCH_LIMIT = 100;
|
||||
const BACKFILL_PAGE_LIMIT = 100;
|
||||
const MAX_BACKFILL_ROUNDS = 3;
|
||||
|
||||
export function hasUserOrAgentMessage(messages: Message[]): boolean {
|
||||
return messages.some(
|
||||
(m) => m.type === "message" && (m.author_type === "user" || m.author_type === "agent"),
|
||||
);
|
||||
}
|
||||
|
||||
const debug = createDebugLogger("messages:fetch");
|
||||
|
||||
function summarizeMessages(messages: Message[]): {
|
||||
count: number;
|
||||
byType: Record<string, number>;
|
||||
userMessageCount: number;
|
||||
agentMessageCount: number;
|
||||
oldestCreatedAt: string | null;
|
||||
newestCreatedAt: string | null;
|
||||
} {
|
||||
const byType: Record<string, number> = {};
|
||||
let userMessageCount = 0;
|
||||
let agentMessageCount = 0;
|
||||
for (const m of messages) {
|
||||
const t = m.type ?? "unknown";
|
||||
byType[t] = (byType[t] ?? 0) + 1;
|
||||
if (m.type === "message" && m.author_type === "user") userMessageCount++;
|
||||
if (m.type === "message" && m.author_type === "agent") agentMessageCount++;
|
||||
}
|
||||
return {
|
||||
count: messages.length,
|
||||
byType,
|
||||
userMessageCount,
|
||||
agentMessageCount,
|
||||
oldestCreatedAt: messages[0]?.created_at ?? null,
|
||||
newestCreatedAt: messages[messages.length - 1]?.created_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
interface UseSessionMessagesReturn {
|
||||
isLoading: boolean;
|
||||
@@ -25,12 +66,32 @@ async function fetchAndStoreMessages(
|
||||
return [];
|
||||
}
|
||||
|
||||
const response = await client.request<MessageListResponse>(
|
||||
"message.list",
|
||||
{ session_id: sessionId, limit: 50, sort: "desc" },
|
||||
10000,
|
||||
);
|
||||
const requestParams = {
|
||||
session_id: sessionId,
|
||||
limit: INITIAL_FETCH_LIMIT,
|
||||
sort: "desc" as const,
|
||||
};
|
||||
debug("message.list request", requestParams);
|
||||
const response = await client.request<MessageListResponse>("message.list", requestParams, 10000);
|
||||
const fetched = [...(response.messages ?? [])].reverse();
|
||||
if (IS_DEBUG) {
|
||||
const summary = summarizeMessages(fetched);
|
||||
debug("message.list response", {
|
||||
sessionId,
|
||||
hasMore: response.has_more ?? false,
|
||||
cursor: response.cursor ?? null,
|
||||
...summary,
|
||||
});
|
||||
if (fetched.length > 0 && summary.userMessageCount === 0 && summary.agentMessageCount === 0) {
|
||||
debug("WARNING: fetched window contains no user/agent message rows", {
|
||||
sessionId,
|
||||
limit: requestParams.limit,
|
||||
hasMore: response.has_more ?? false,
|
||||
byType: summary.byType,
|
||||
hint: "The fetch limit may be too small for this session's last turn — user prompt and agent replies live further back. Paginate or raise the limit to see them.",
|
||||
});
|
||||
}
|
||||
}
|
||||
// Merge: keep WS-delivered messages that aren't in the fetch response.
|
||||
// This prevents a slow fetch (sent before messages existed) from wiping
|
||||
// messages that arrived via real-time notifications while the fetch was
|
||||
@@ -52,6 +113,81 @@ async function fetchAndStoreMessages(
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* When the initial fetch window contains no user/agent message rows (common
|
||||
* when the latest turn produced hundreds of tool calls), the chat would render
|
||||
* as an opaque collapsed activity group with nothing meaningful to scroll
|
||||
* past — the lazy-load sentinel at the top of the list never fires because
|
||||
* the user has no anchor to scroll from. Paginate backward via the same HTTP
|
||||
* endpoint `useLazyLoadMessages` uses until we span at least one user/agent
|
||||
* message or hit the round cap.
|
||||
*/
|
||||
export type BackfillStep = "continue" | "stop";
|
||||
|
||||
async function fetchAndPrependOlder(
|
||||
sessionId: string,
|
||||
store: ReturnType<typeof useAppStoreApi>,
|
||||
oldestCursor: string,
|
||||
): Promise<number> {
|
||||
const response = await listTaskSessionMessages(sessionId, {
|
||||
limit: BACKFILL_PAGE_LIMIT,
|
||||
before: oldestCursor,
|
||||
sort: "desc",
|
||||
});
|
||||
const ordered = [...(response.messages ?? [])].reverse();
|
||||
const newOldestCursor = ordered[0]?.id ?? oldestCursor;
|
||||
store.getState().prependMessages(sessionId, ordered, {
|
||||
hasMore: response.has_more ?? false,
|
||||
oldestCursor: newOldestCursor,
|
||||
});
|
||||
return ordered.length;
|
||||
}
|
||||
|
||||
export async function runBackfillRound(
|
||||
sessionId: string,
|
||||
store: ReturnType<typeof useAppStoreApi>,
|
||||
round: number,
|
||||
): Promise<BackfillStep> {
|
||||
const meta = store.getState().messages.metaBySession[sessionId];
|
||||
const messages = store.getState().messages.bySession[sessionId] ?? [];
|
||||
if (hasUserOrAgentMessage(messages)) return "stop";
|
||||
if (!meta?.hasMore || !meta.oldestCursor) {
|
||||
debug("autoBackfill: stopping (no more older messages)", {
|
||||
sessionId,
|
||||
round,
|
||||
hasMore: meta?.hasMore ?? false,
|
||||
});
|
||||
return "stop";
|
||||
}
|
||||
debug("autoBackfill: window has no user/agent message, fetching older", {
|
||||
sessionId,
|
||||
round,
|
||||
currentCount: messages.length,
|
||||
oldestCursor: meta.oldestCursor,
|
||||
});
|
||||
try {
|
||||
const added = await fetchAndPrependOlder(sessionId, store, meta.oldestCursor);
|
||||
return added === 0 ? "stop" : "continue";
|
||||
} catch (err) {
|
||||
debug("autoBackfill: fetch failed, stopping", { sessionId, round, err });
|
||||
return "stop";
|
||||
}
|
||||
}
|
||||
|
||||
export async function autoBackfillUntilUserMessage(
|
||||
sessionId: string,
|
||||
store: ReturnType<typeof useAppStoreApi>,
|
||||
): Promise<void> {
|
||||
for (let round = 0; round < MAX_BACKFILL_ROUNDS; round++) {
|
||||
const step = await runBackfillRound(sessionId, store, round);
|
||||
if (step === "stop") return;
|
||||
}
|
||||
debug("autoBackfill: hit round cap without finding user/agent message", {
|
||||
sessionId,
|
||||
cap: MAX_BACKFILL_ROUNDS,
|
||||
});
|
||||
}
|
||||
|
||||
type FetchMessagesParams = {
|
||||
taskSessionId: string;
|
||||
store: ReturnType<typeof useAppStoreApi>;
|
||||
@@ -81,6 +217,9 @@ async function doFetchMessages({
|
||||
const fetched = await fetchAndStoreMessages(taskSessionId, store);
|
||||
lastFetchedSessionIdRef.current = taskSessionId;
|
||||
if (fetched.length > 0) setIsWaitingForInitialMessages(false);
|
||||
if (fetched.length > 0 && !hasUserOrAgentMessage(fetched)) {
|
||||
await autoBackfillUntilUserMessage(taskSessionId, store);
|
||||
}
|
||||
} catch (error) {
|
||||
if (onError) onError(error);
|
||||
else console.error("Failed to fetch messages:", error);
|
||||
@@ -135,14 +274,46 @@ export function useVisibilityBackfill(
|
||||
store: ReturnType<typeof useAppStoreApi>,
|
||||
) {
|
||||
useEffect(() => {
|
||||
if (!taskSessionId) return;
|
||||
if (!taskSessionId) {
|
||||
debug("visibilityBackfill: skipped attaching (no sessionId)");
|
||||
return;
|
||||
}
|
||||
debug("visibilityBackfill: attached", { sessionId: taskSessionId });
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
fetchAndStoreMessages(taskSessionId, store).catch(() => {});
|
||||
}
|
||||
const visibilityState = document.visibilityState;
|
||||
const state = store.getState();
|
||||
const existingCount = state.messages.bySession[taskSessionId]?.length ?? 0;
|
||||
const newestBefore =
|
||||
state.messages.bySession[taskSessionId]?.slice(-1)[0]?.created_at ?? null;
|
||||
debug("visibilityBackfill: visibilitychange fired", {
|
||||
sessionId: taskSessionId,
|
||||
visibilityState,
|
||||
connectionStatus: state.connection?.status ?? "unknown",
|
||||
existingCount,
|
||||
newestBefore,
|
||||
});
|
||||
if (visibilityState !== "visible") return;
|
||||
fetchAndStoreMessages(taskSessionId, store)
|
||||
.then(() => {
|
||||
const afterCount = store.getState().messages.bySession[taskSessionId]?.length ?? 0;
|
||||
const newestAfter =
|
||||
store.getState().messages.bySession[taskSessionId]?.slice(-1)[0]?.created_at ?? null;
|
||||
debug("visibilityBackfill: refetch complete", {
|
||||
sessionId: taskSessionId,
|
||||
delta: afterCount - existingCount,
|
||||
newestBefore,
|
||||
newestAfter,
|
||||
});
|
||||
})
|
||||
.catch((err) => {
|
||||
debug("visibilityBackfill: refetch failed", { sessionId: taskSessionId, err });
|
||||
});
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
return () => document.removeEventListener("visibilitychange", onVisible);
|
||||
return () => {
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
debug("visibilityBackfill: detached", { sessionId: taskSessionId });
|
||||
};
|
||||
}, [taskSessionId, store]);
|
||||
}
|
||||
|
||||
@@ -153,13 +324,24 @@ function useSessionSubscription(
|
||||
store: ReturnType<typeof useAppStoreApi>,
|
||||
) {
|
||||
useEffect(() => {
|
||||
debug("subscription: effect ran", {
|
||||
sessionId: taskSessionId,
|
||||
connectionStatus,
|
||||
isSessionStartingOrUnknown,
|
||||
});
|
||||
if (!taskSessionId || connectionStatus !== "connected") {
|
||||
debug("subscription: skipped (no session or not connected)", {
|
||||
sessionId: taskSessionId,
|
||||
connectionStatus,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const client = getWebSocketClient();
|
||||
if (!client) {
|
||||
debug("subscription: skipped (no ws client)", { sessionId: taskSessionId });
|
||||
return;
|
||||
}
|
||||
debug("subscription: subscribing", { sessionId: taskSessionId });
|
||||
const unsubscribe = client.subscribeSession(taskSessionId);
|
||||
|
||||
// Re-fetch messages after subscribing to close the gap between SSR
|
||||
@@ -167,6 +349,7 @@ function useSessionSubscription(
|
||||
fetchAndStoreMessages(taskSessionId, store).catch(() => {});
|
||||
|
||||
return () => {
|
||||
debug("subscription: unsubscribing", { sessionId: taskSessionId });
|
||||
unsubscribe();
|
||||
};
|
||||
}, [taskSessionId, connectionStatus, store, isSessionStartingOrUnknown]);
|
||||
|
||||
@@ -1,6 +1,62 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { listTaskSessionMessages } from "@/lib/api";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { createDebugLogger } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("messages:lazyload");
|
||||
|
||||
function describeSkip(args: {
|
||||
sessionId: string | null;
|
||||
isLoading: boolean;
|
||||
hasMore: boolean;
|
||||
}): string {
|
||||
if (!args.sessionId) return "no-session";
|
||||
if (args.isLoading) return "already-loading";
|
||||
if (!args.hasMore) return "no-more";
|
||||
return "no-cursor";
|
||||
}
|
||||
|
||||
type LoadMoreResponseLog = {
|
||||
sessionId: string;
|
||||
requestedBefore: string;
|
||||
ordered: Array<{
|
||||
id: string;
|
||||
created_at: string;
|
||||
type?: string;
|
||||
author_type?: string;
|
||||
}>;
|
||||
responseHasMore: boolean;
|
||||
newOldestCursor: string | null;
|
||||
};
|
||||
|
||||
function logLoadMoreResponse(args: LoadMoreResponseLog) {
|
||||
const { sessionId, requestedBefore, ordered, responseHasMore, newOldestCursor } = args;
|
||||
const first = ordered[0];
|
||||
debug("loadMore: response", {
|
||||
sessionId,
|
||||
requestedBefore,
|
||||
fetchedCount: ordered.length,
|
||||
responseHasMore,
|
||||
newOldestId: newOldestCursor,
|
||||
newOldestCreatedAt: first?.created_at ?? null,
|
||||
newOldestType: first?.type ?? null,
|
||||
newOldestAuthor: first?.author_type ?? null,
|
||||
});
|
||||
if (ordered.length === 0 && responseHasMore) {
|
||||
debug("loadMore: WARNING empty batch with has_more=true — pagination may be stuck", {
|
||||
sessionId,
|
||||
before: requestedBefore,
|
||||
});
|
||||
}
|
||||
if (!responseHasMore && ordered.length > 0) {
|
||||
debug("loadMore: reached oldest — check that the first prompt is present", {
|
||||
sessionId,
|
||||
newOldestId: newOldestCursor,
|
||||
newOldestAuthor: first?.author_type,
|
||||
newOldestType: first?.type,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function useLazyLoadMessages(sessionId: string | null) {
|
||||
// Use refs for values that should not trigger callback recreation
|
||||
@@ -28,9 +84,17 @@ export function useLazyLoadMessages(sessionId: string | null) {
|
||||
const { hasMore, isLoading, oldestCursor } = stateRef.current;
|
||||
|
||||
if (!sessionId || !hasMore || isLoading || !oldestCursor) {
|
||||
debug("loadMore: skipped", {
|
||||
sessionId,
|
||||
reason: describeSkip({ sessionId, isLoading, hasMore }),
|
||||
hasMore,
|
||||
oldestCursor,
|
||||
});
|
||||
return 0;
|
||||
}
|
||||
|
||||
debug("loadMore: requesting older page", { sessionId, before: oldestCursor, limit: 20 });
|
||||
|
||||
// Update ref synchronously so concurrent calls are blocked immediately
|
||||
stateRef.current.isLoading = true;
|
||||
setMessagesMetadata(sessionId, { isLoading: true });
|
||||
@@ -43,6 +107,13 @@ export function useLazyLoadMessages(sessionId: string | null) {
|
||||
const orderedMessages = [...(response.messages ?? [])].reverse();
|
||||
// After reversing, orderedMessages[0] is the oldest message in this batch
|
||||
const newOldestCursor = orderedMessages[0]?.id ?? null;
|
||||
logLoadMoreResponse({
|
||||
sessionId,
|
||||
requestedBefore: oldestCursor,
|
||||
ordered: orderedMessages,
|
||||
responseHasMore: response.has_more,
|
||||
newOldestCursor,
|
||||
});
|
||||
// Sync ref immediately so the next intersection callback sees correct state
|
||||
// (the useEffect sync may not have run yet between store update and next observer fire)
|
||||
stateRef.current = {
|
||||
@@ -57,6 +128,7 @@ export function useLazyLoadMessages(sessionId: string | null) {
|
||||
return orderedMessages.length;
|
||||
} catch (error) {
|
||||
console.error("[useLazyLoadMessages] Error loading messages:", error);
|
||||
debug("loadMore: error", { sessionId, error });
|
||||
stateRef.current.isLoading = false;
|
||||
setMessagesMetadata(sessionId, { isLoading: false });
|
||||
return 0;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import {
|
||||
sessionId as toSessionId,
|
||||
taskId as toTaskId,
|
||||
@@ -11,6 +11,45 @@ import {
|
||||
findPendingClarification,
|
||||
findPendingClarificationGroup,
|
||||
} from "@/lib/utils/pending-clarification";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("messages:process");
|
||||
|
||||
function countByType(messages: Message[]): Record<string, number> {
|
||||
const out: Record<string, number> = {};
|
||||
for (const m of messages) {
|
||||
const t = m.type ?? "unknown";
|
||||
out[t] = (out[t] ?? 0) + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function useDebugProcessedPipeline(args: {
|
||||
sessionId: string | null;
|
||||
messages: Message[];
|
||||
visibleMessages: Message[];
|
||||
footerActionCount: number;
|
||||
groupedItems: RenderItem[];
|
||||
}) {
|
||||
const { sessionId, messages, visibleMessages, footerActionCount, groupedItems } = args;
|
||||
useEffect(() => {
|
||||
if (!IS_DEBUG) return;
|
||||
debug("pipeline", {
|
||||
sessionId,
|
||||
input: { count: messages.length, byType: countByType(messages) },
|
||||
afterFilter: { count: visibleMessages.length, byType: countByType(visibleMessages) },
|
||||
droppedByFilter: messages.length - visibleMessages.length,
|
||||
footerActionCount,
|
||||
groupedItemKinds: groupedItems.reduce<Record<string, number>>((acc, item) => {
|
||||
acc[item.type] = (acc[item.type] ?? 0) + 1;
|
||||
return acc;
|
||||
}, {}),
|
||||
turnGroupSizes: groupedItems
|
||||
.filter((i): i is TurnGroup => i.type === "turn_group")
|
||||
.map((g) => ({ turnId: g.turnId, size: g.messages.length })),
|
||||
});
|
||||
}, [sessionId, messages, visibleMessages, footerActionCount, groupedItems]);
|
||||
}
|
||||
|
||||
const ACTIVITY_MESSAGE_TYPES: Set<MessageType> = new Set([
|
||||
"thinking",
|
||||
@@ -377,6 +416,14 @@ export function useProcessedMessages(
|
||||
return injectPrepareProgressItem(groupActivityMessages(regularMessages), resolvedSessionId);
|
||||
}, [regularMessages, resolvedSessionId]);
|
||||
|
||||
useDebugProcessedPipeline({
|
||||
sessionId: resolvedSessionId,
|
||||
messages,
|
||||
visibleMessages,
|
||||
footerActionCount: footerActionMessages.length,
|
||||
groupedItems,
|
||||
});
|
||||
|
||||
return {
|
||||
visibleMessages,
|
||||
allMessages,
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { createDebugLogger } from "./log";
|
||||
|
||||
describe("createDebugLogger", () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(console, "debug").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("returns a function", () => {
|
||||
expect(typeof createDebugLogger("test")).toBe("function");
|
||||
});
|
||||
|
||||
it("prefixes output with [namespace]", () => {
|
||||
const log = createDebugLogger("my-ns");
|
||||
log("hello");
|
||||
expect(console.debug).toHaveBeenCalledWith("[my-ns] hello");
|
||||
});
|
||||
|
||||
it("logs plain strings as-is", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log("simple message");
|
||||
expect(console.debug).toHaveBeenCalledWith("[ns] simple message");
|
||||
});
|
||||
|
||||
it("flattens plain objects to key=value pairs", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log("msg", { a: 1, b: "hello world" });
|
||||
expect(console.debug).toHaveBeenCalledWith('[ns] msg a=1 b="hello world"');
|
||||
});
|
||||
|
||||
it("quotes values containing spaces", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log({ key: "value with space" });
|
||||
expect(console.debug).toHaveBeenCalledWith('[ns] key="value with space"');
|
||||
});
|
||||
|
||||
it("leaves bare values unquoted", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log({ key: "simple_value" });
|
||||
expect(console.debug).toHaveBeenCalledWith("[ns] key=simple_value");
|
||||
});
|
||||
|
||||
it("formats null and undefined", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log({ a: null, b: undefined });
|
||||
expect(console.debug).toHaveBeenCalledWith("[ns] a=null b=undefined");
|
||||
});
|
||||
|
||||
it("formats numbers and booleans", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log({ count: 42, flag: true });
|
||||
expect(console.debug).toHaveBeenCalledWith("[ns] count=42 flag=true");
|
||||
});
|
||||
|
||||
it("formats Error objects with name and message", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log({ err: new Error("boom") });
|
||||
expect(console.debug).toHaveBeenCalledWith('[ns] err={"name":"Error","message":"boom"}');
|
||||
});
|
||||
|
||||
it("serializes nested objects as JSON", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log({ nested: { x: 1 } });
|
||||
expect(console.debug).toHaveBeenCalledWith('[ns] nested={"x":1}');
|
||||
});
|
||||
|
||||
it("mixes strings and objects in a single call", () => {
|
||||
const log = createDebugLogger("ns");
|
||||
log("prefix", { a: 1 }, "suffix");
|
||||
expect(console.debug).toHaveBeenCalledWith("[ns] prefix a=1 suffix");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Namespaced debug logger for development.
|
||||
*
|
||||
* Active when `NODE_ENV !== "production"` (i.e. `make dev`) **or** when
|
||||
* `NEXT_PUBLIC_KANDEV_DEBUG=true` is set at build time (i.e. `make
|
||||
* start-debug`). In a plain production build both conditions are false and
|
||||
* Next.js dead-code-eliminates everything.
|
||||
*
|
||||
* The `debug()` call itself is free, but JavaScript evaluates its arguments
|
||||
* before the call — so callers that compute expensive values (O(n) maps,
|
||||
* `.reduce()`, spread of large objects) must guard with the exported constant:
|
||||
*
|
||||
* if (IS_DEBUG) { debug(...); }
|
||||
*
|
||||
* Next.js inlines both `process.env` checks at build time and Terser folds
|
||||
* `IS_DEBUG` to a boolean literal, dead-code-eliminating the block in regular
|
||||
* production builds. Simple scalar reads are cheap enough to leave unguarded.
|
||||
*
|
||||
* Output format is logfmt-ish so logs are flat and grep/copy-friendly:
|
||||
*
|
||||
* [namespace] message key1=value key2="value with space" key3={"nested":1}
|
||||
*
|
||||
* Usage:
|
||||
* const debug = createDebugLogger("git-status");
|
||||
* debug("status_update received", { sessionId, fileCount });
|
||||
*
|
||||
* Logs go through `console.debug`, which the log interceptor mirrors into the
|
||||
* ring buffer (see `lib/logger/intercept.ts`), so they also end up in
|
||||
* Improve Kandev reports without extra plumbing.
|
||||
*/
|
||||
|
||||
export type DebugLogger = (...args: unknown[]) => void;
|
||||
|
||||
export const IS_DEBUG =
|
||||
process.env.NODE_ENV !== "production" || process.env.NEXT_PUBLIC_KANDEV_DEBUG === "true";
|
||||
|
||||
const NOOP: DebugLogger = () => {};
|
||||
|
||||
const BARE_VALUE_RE = /^[A-Za-z0-9_\-:./@+]+$/;
|
||||
|
||||
function formatValue(value: unknown): string {
|
||||
if (value === null) return "null";
|
||||
if (value === undefined) return "undefined";
|
||||
if (typeof value === "string") {
|
||||
return BARE_VALUE_RE.test(value) ? value : JSON.stringify(value);
|
||||
}
|
||||
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
|
||||
return String(value);
|
||||
}
|
||||
if (value instanceof Error) {
|
||||
return JSON.stringify({ name: value.name, message: value.message });
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
if (value === null || typeof value !== "object") return false;
|
||||
if (Array.isArray(value)) return false;
|
||||
const proto = Object.getPrototypeOf(value);
|
||||
return proto === Object.prototype || proto === null;
|
||||
}
|
||||
|
||||
function flattenArgs(args: unknown[]): string {
|
||||
const parts: string[] = [];
|
||||
for (const arg of args) {
|
||||
if (typeof arg === "string") {
|
||||
parts.push(arg);
|
||||
continue;
|
||||
}
|
||||
if (isPlainObject(arg)) {
|
||||
for (const [key, val] of Object.entries(arg)) {
|
||||
parts.push(`${key}=${formatValue(val)}`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
parts.push(formatValue(arg));
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
export function createDebugLogger(namespace: string): DebugLogger {
|
||||
if (!IS_DEBUG) return NOOP;
|
||||
const prefix = `[${namespace}]`;
|
||||
return (...args: unknown[]) => {
|
||||
console.debug(`${prefix} ${flattenArgs(args)}`);
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,30 @@ import { applyLayoutFixups } from "./dockview-layout-builders";
|
||||
import { isLayoutShapeHealthy } from "./dockview-layout-health";
|
||||
import { fromDockviewApi, savedLayoutMatchesLive, layoutStructuresMatch } from "./layout-manager";
|
||||
import type { LayoutState, LayoutGroupIds } from "./layout-manager";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("dockview:env-switch");
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function snapshotGridShape(node: any, depth = 0): unknown {
|
||||
if (!node || depth > 6) return null;
|
||||
if (node.type === "leaf") {
|
||||
return {
|
||||
type: "leaf",
|
||||
groupId: node.data?.id,
|
||||
activeView: node.data?.activeView,
|
||||
views: node.data?.views,
|
||||
};
|
||||
}
|
||||
if (node.type === "branch" && Array.isArray(node.data)) {
|
||||
return {
|
||||
type: "branch",
|
||||
orientation: node.orientation,
|
||||
children: node.data.map((c: unknown) => snapshotGridShape(c, depth + 1)),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const EPHEMERAL_COMPONENTS = new Set([
|
||||
"file-editor",
|
||||
@@ -162,6 +186,13 @@ function removeStaleSessionPanels(api: DockviewApi, keepSessionId: string | null
|
||||
const toRemove = api.panels.filter(
|
||||
(p) => p.api.component === "chat" && p.id.startsWith("session:") && p.id !== keepId,
|
||||
);
|
||||
if (IS_DEBUG) {
|
||||
debug("removeStaleSessionPanels", {
|
||||
keepSessionId,
|
||||
livePanelIds: api.panels.map((p) => p.id),
|
||||
removingIds: toRemove.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
for (const p of toRemove) {
|
||||
try {
|
||||
p.api.close();
|
||||
@@ -208,8 +239,30 @@ function tryFastEnvSwitch(params: EnvSwitchParams): LayoutGroupIds | null {
|
||||
structuresMatch = layoutStructuresMatch(currentLayout, getDefaultLayout());
|
||||
}
|
||||
|
||||
if (!structuresMatch) return null;
|
||||
if (saved && savedLayoutHasEphemeralPanels(saved as SerializedDockview)) return null;
|
||||
if (!structuresMatch) {
|
||||
if (IS_DEBUG) {
|
||||
debug("tryFastEnvSwitch: structures do not match, falling back to slow path", {
|
||||
newEnvId,
|
||||
hasSaved: !!saved,
|
||||
currentPanelIds: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (saved && savedLayoutHasEphemeralPanels(saved as SerializedDockview)) {
|
||||
debug("tryFastEnvSwitch: saved layout has ephemeral panels, falling back to slow path", {
|
||||
newEnvId,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
if (IS_DEBUG) {
|
||||
debug("tryFastEnvSwitch: taking fast path", {
|
||||
newEnvId,
|
||||
activeSessionId,
|
||||
hasSaved: !!saved,
|
||||
currentPanelIds: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
|
||||
// Prefer the active session panel so multi-session tasks anchor the
|
||||
// incoming panel to the group the user was looking at, not whichever
|
||||
@@ -281,14 +334,41 @@ function addIncomingSessionPanel(
|
||||
* env-scoped portals before calling this function.
|
||||
*/
|
||||
export function performEnvSwitch(params: EnvSwitchParams): LayoutGroupIds {
|
||||
const { api, newEnvId, activeSessionId, safeWidth, safeHeight, buildDefault } = params;
|
||||
const { api, oldEnvId, newEnvId, activeSessionId, safeWidth, safeHeight, buildDefault } = params;
|
||||
if (IS_DEBUG) {
|
||||
debug("performEnvSwitch: entry", {
|
||||
oldEnvId,
|
||||
newEnvId,
|
||||
activeSessionId,
|
||||
livePanelIdsBefore: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
|
||||
const fastResult = tryFastEnvSwitch(params);
|
||||
if (fastResult) return fastResult;
|
||||
if (fastResult) {
|
||||
if (IS_DEBUG) {
|
||||
debug("performEnvSwitch: completed via fast path", {
|
||||
newEnvId,
|
||||
livePanelIdsAfter: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
return fastResult;
|
||||
}
|
||||
|
||||
const saved = getHealthyEnvLayout(newEnvId);
|
||||
if (saved) {
|
||||
try {
|
||||
if (IS_DEBUG) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const savedPanelIds = Object.keys((saved as any).panels ?? {});
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const savedShape = snapshotGridShape((saved as any).grid?.root);
|
||||
debug("performEnvSwitch: slow path - calling api.fromJSON", {
|
||||
newEnvId,
|
||||
savedPanelIds,
|
||||
savedShape,
|
||||
});
|
||||
}
|
||||
api.fromJSON(saved as SerializedDockview);
|
||||
// Saved layout may carry a stale session panel from a previously-deleted
|
||||
// task (phantom). Strip session panels that don't belong to the incoming
|
||||
@@ -297,13 +377,27 @@ export function performEnvSwitch(params: EnvSwitchParams): LayoutGroupIds {
|
||||
// useAutoSessionTab will add the current session's panel if missing.
|
||||
removeStaleSessionPanels(api, activeSessionId);
|
||||
api.layout(safeWidth, safeHeight);
|
||||
if (IS_DEBUG) {
|
||||
debug("performEnvSwitch: completed via slow path (fromJSON)", {
|
||||
newEnvId,
|
||||
livePanelIdsAfter: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
return applyLayoutFixups(api);
|
||||
} catch (err) {
|
||||
console.warn("performEnvSwitch: fromJSON threw", err);
|
||||
debug("performEnvSwitch: fromJSON threw, falling through to default", { newEnvId, err });
|
||||
/* fall through to default layout build */
|
||||
}
|
||||
}
|
||||
debug("performEnvSwitch: building default layout", { newEnvId, hasSaved: !!saved });
|
||||
buildDefault(api);
|
||||
api.layout(safeWidth, safeHeight);
|
||||
if (IS_DEBUG) {
|
||||
debug("performEnvSwitch: completed via default build", {
|
||||
newEnvId,
|
||||
livePanelIdsAfter: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
return applyLayoutFixups(api);
|
||||
}
|
||||
|
||||
@@ -41,6 +41,10 @@ import {
|
||||
import { preserveChatScrollDuringLayout } from "./dockview-scroll-preserve";
|
||||
import { measureDockviewContainer } from "./dockview-measure";
|
||||
import { panelPortalManager } from "@/lib/layout/panel-portal-manager";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debugSwitch = createDebugLogger("dockview:store-switch");
|
||||
const debugSave = createDebugLogger("dockview:save");
|
||||
|
||||
const RIGHT_PANEL_IDS = new Set(["changes", "files", TERMINAL_DEFAULT_ID]);
|
||||
|
||||
@@ -469,7 +473,17 @@ function saveOutgoingEnv(
|
||||
preMaximizeLayout: LayoutState | null,
|
||||
pinnedWidths: Map<string, number>,
|
||||
): void {
|
||||
if (!oldEnvId) return;
|
||||
if (!oldEnvId) {
|
||||
debugSave("saveOutgoingEnv: skip (no oldEnvId)");
|
||||
return;
|
||||
}
|
||||
if (IS_DEBUG) {
|
||||
debugSave("saveOutgoingEnv: entry", {
|
||||
oldEnvId,
|
||||
livePanelIds: api.panels.map((p) => p.id),
|
||||
maximized: !!preMaximizeLayout,
|
||||
});
|
||||
}
|
||||
if (preMaximizeLayout) {
|
||||
// While maximized, `api.toJSON()` is the 2-column maximize overlay, NOT
|
||||
// the user's intended layout. Persist the pre-max layout under both keys:
|
||||
@@ -513,10 +527,26 @@ function saveOutgoingEnv(
|
||||
function buildEnvSwitchAction(set: StoreSet, get: StoreGet) {
|
||||
return (oldEnvId: string | null, newEnvId: string, activeSessionId: string | null) => {
|
||||
const { api, currentLayoutEnvId, preMaximizeLayout } = get();
|
||||
if (!api) return;
|
||||
if (!api) {
|
||||
debugSwitch("envSwitch: skip (no api)", { oldEnvId, newEnvId, activeSessionId });
|
||||
return;
|
||||
}
|
||||
if (IS_DEBUG) {
|
||||
debugSwitch("envSwitch: entry", {
|
||||
oldEnvId,
|
||||
newEnvId,
|
||||
activeSessionId,
|
||||
currentLayoutEnvId,
|
||||
maximized: !!preMaximizeLayout,
|
||||
livePanelIds: api.panels.map((p) => p.id),
|
||||
});
|
||||
}
|
||||
// Same-env switch (e.g. between sessions of the same task) is a no-op.
|
||||
// The layout, terminals, and env-scoped portals already belong to this env.
|
||||
if (currentLayoutEnvId === newEnvId) return;
|
||||
if (currentLayoutEnvId === newEnvId) {
|
||||
debugSwitch("envSwitch: skip (same env)", { newEnvId });
|
||||
return;
|
||||
}
|
||||
// First adoption — onReady already built the layout; just adopt it.
|
||||
if (!oldEnvId && !currentLayoutEnvId) {
|
||||
set({ isRestoringLayout: true, currentLayoutEnvId: newEnvId });
|
||||
|
||||
@@ -6,6 +6,9 @@ import type {
|
||||
GitStatusEntry,
|
||||
FileInfo,
|
||||
} from "./types";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debugGit = createDebugLogger("git-status:store");
|
||||
|
||||
const maxProcessOutputBytes = 2 * 1024 * 1024;
|
||||
|
||||
@@ -290,6 +293,18 @@ export const createSessionRuntimeSlice: StateCreator<
|
||||
// empty key so consumers using only byEnvironmentRepo still see it.
|
||||
const repoName = gitStatus.repository_name ?? "";
|
||||
const existing = draft.gitStatus.byEnvironmentId[envKey];
|
||||
if (IS_DEBUG) {
|
||||
debugGit("setGitStatus", {
|
||||
sessionId,
|
||||
envKey,
|
||||
usingFallbackKey: envKey === sessionId,
|
||||
repoName,
|
||||
prevFileCount: Object.keys(existing?.files ?? {}).length,
|
||||
nextFileCount: Object.keys(gitStatus.files ?? {}).length,
|
||||
prevRepoKeys: Object.keys(draft.gitStatus.byEnvironmentRepo[envKey] ?? {}),
|
||||
willOverwriteByEnv: !existing || hasGitStatusChanged(existing, gitStatus),
|
||||
});
|
||||
}
|
||||
if (!existing || hasGitStatusChanged(existing, gitStatus)) {
|
||||
draft.gitStatus.byEnvironmentId[envKey] = gitStatus;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,9 @@ import type { StateCreator } from "zustand";
|
||||
import type { TaskSession } from "@/lib/types/http";
|
||||
import type { SessionSlice, SessionSliceState } from "./types";
|
||||
import { migrateEnvKeyedData } from "@/lib/state/slices/session-runtime/session-runtime-slice";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debugEnv = createDebugLogger("session:env-mapping");
|
||||
|
||||
/** Ensure message metadata exists for a session, initializing with defaults if needed. */
|
||||
function ensureMessageMeta(
|
||||
@@ -43,6 +46,21 @@ function mergeMessageFields(target: Record<string, unknown>, source: Record<stri
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function syncEnvironmentMapping(draft: any, sessionId: string, environmentId: string | undefined) {
|
||||
if (!environmentId) return;
|
||||
const previous = draft.environmentIdBySessionId[sessionId];
|
||||
if (IS_DEBUG) {
|
||||
debugEnv("syncEnvironmentMapping", {
|
||||
sessionId,
|
||||
environmentId,
|
||||
previous: previous ?? null,
|
||||
changed: previous !== environmentId,
|
||||
fallbackGitStatusFileCount: Object.keys(
|
||||
draft.gitStatus?.byEnvironmentId?.[sessionId]?.files ?? {},
|
||||
).length,
|
||||
targetGitStatusFileCount: Object.keys(
|
||||
draft.gitStatus?.byEnvironmentId?.[environmentId]?.files ?? {},
|
||||
).length,
|
||||
});
|
||||
}
|
||||
draft.environmentIdBySessionId[sessionId] = environmentId;
|
||||
migrateEnvKeyedData(draft, sessionId, environmentId);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,9 @@ import type {
|
||||
GitBranchSwitchedEvent,
|
||||
} from "@/lib/types/git-events";
|
||||
import { invalidateCumulativeDiffCache } from "@/hooks/domains/session/use-cumulative-diff";
|
||||
import { createDebugLogger, IS_DEBUG } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("git-status:ws");
|
||||
|
||||
// Handler functions for each event type
|
||||
type GitEventHandlers = {
|
||||
@@ -25,6 +28,22 @@ function resolveEnvKey(store: StoreApi<AppState>, sessionId: string): string {
|
||||
|
||||
const gitEventHandlers: GitEventHandlers = {
|
||||
status_update: (store, event) => {
|
||||
if (IS_DEBUG) {
|
||||
debug("status_update", {
|
||||
sessionId: event.session_id,
|
||||
repositoryName: event.status.repository_name ?? null,
|
||||
branch: event.status.branch,
|
||||
fileCount: Object.keys(event.status.files ?? {}).length,
|
||||
modified: event.status.modified?.length ?? 0,
|
||||
added: event.status.added?.length ?? 0,
|
||||
deleted: event.status.deleted?.length ?? 0,
|
||||
untracked: event.status.untracked?.length ?? 0,
|
||||
ahead: event.status.ahead,
|
||||
behind: event.status.behind,
|
||||
envKey: resolveEnvKey(store, event.session_id),
|
||||
envMapped: event.session_id in store.getState().environmentIdBySessionId,
|
||||
});
|
||||
}
|
||||
store.getState().setGitStatus(event.session_id, {
|
||||
branch: event.status.branch,
|
||||
remote_branch: event.status.remote_branch,
|
||||
|
||||
@@ -6,15 +6,20 @@ import { WebSocketClient } from "@/lib/ws/client";
|
||||
import { registerWsHandlers } from "@/lib/ws/router";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
import { setWebSocketClient } from "@/lib/ws/connection";
|
||||
import { createDebugLogger } from "@/lib/debug/log";
|
||||
|
||||
const debug = createDebugLogger("ws:connection");
|
||||
|
||||
export function useWebSocket(store: StoreApi<AppState>, url: string) {
|
||||
const clientRef = useRef<WebSocketClient | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
debug("WS hook mounting", { url });
|
||||
const client = new WebSocketClient(
|
||||
url,
|
||||
(status) => {
|
||||
const setConnectionStatus = store.getState().setConnectionStatus;
|
||||
debug("status transition", { status, timestamp: new Date().toISOString() });
|
||||
// WS client and ConnectionState share one ConnectionStatus vocabulary,
|
||||
// so this is a 1:1 forward with an `error` message attached and a
|
||||
// `subscribeUser()` side-effect on first connect.
|
||||
|
||||
Reference in New Issue
Block a user