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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { IAgentScopeRuntimeWebUISession } from "@agentscope-ai/chat";
import type { ChatStatus } from "../../../../api/types/chat";
import { chatApi } from "../../../../api/modules/chat";
import sessionApi from "../../sessionApi";
import { useMessageQueueStore } from "../../../../stores/messageQueueStore";
import {
  ContextMenu,
  useContextMenu,
  type ContextMenuItem,
} from "../../../../components/ContextMenu";
import { getChannelLabel } from "../../../Control/Channels/components";
import { syncSessionsGlobal } from "../../../../stores/sessionListStore";
import { useAgentStore } from "../../../../stores/agentStore";
import { useAppMessage } from "../../../../hooks/useAppMessage";

export { ContextMenu, useContextMenu, type ContextMenuItem, getChannelLabel };

/**
 * Shallow-compare two session arrays by visible fields.
 * Returns true when the list would look identical, so we can skip
 * the state update and avoid a full re-render cascade.
 */
function sessionsEqual(
  prev: ExtendedChatSession[],
  next: ExtendedChatSession[],
): boolean {
  if (prev.length !== next.length) return false;
  for (let i = 0; i < prev.length; i++) {
    const a = prev[i];
    const b = next[i];
    if (
      a.id !== b.id ||
      a.name !== b.name ||
      a.updatedAt !== b.updatedAt ||
      a.lastFinishedAt !== b.lastFinishedAt ||
      a.pinned !== b.pinned ||
      a.generating !== b.generating ||
      a.status !== b.status ||
      a.archived !== b.archived ||
      a.groupId !== b.groupId ||
      a.source !== b.source
    ) {
      return false;
    }
  }
  return true;
}

/** Sessions from QwenPaw backend include extra fields beyond the runtime UI type */
export interface ExtendedChatSession extends IAgentScopeRuntimeWebUISession {
  realId?: string;
  sessionId?: string;
  userId?: string;
  channel?: string;
  createdAt?: string | null;
  updatedAt?: string | null;
  lastFinishedAt?: string | null;
  meta?: Record<string, unknown>;
  status?: ChatStatus;
  generating?: boolean;
  pinned?: boolean;
  archivedAt?: string | null;
  archived?: boolean;
  source?: "chat" | "cron" | "subagent";
  groupId?: string | null;
  parentSessionId?: string | null;
  rootSessionId?: string | null;
}

/** Resolve the real backend UUID from an extended session (id may be a local timestamp) */
export const getBackendId = (session: ExtendedChatSession): string | null => {
  if (session.realId) return session.realId;
  const id = session.id;
  if (/^\d+-[a-z0-9]+$/.test(id)) return null;
  return id;
};

/** Format an ISO 8601 timestamp to YYYY-MM-DD HH:mm:ss */
export const formatCreatedAt = (raw: string | null | undefined): string => {
  if (!raw) return "";
  const date = new Date(raw);
  if (isNaN(date.getTime())) return "";
  const pad = (n: number) => String(n).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate(),
  )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
    date.getSeconds(),
  )}`;
};

interface UseSessionListDataOptions {
  /** Whether to start fetching (works like `open` in the drawer) */
  active: boolean;
  /** Current session id — used to determine active item and block no-op clicks */
  currentSessionId: string | undefined;
  /** Called when user clicks a session; the hook itself does NOT navigate */
  onSessionClick: (sessionId: string) => void;
  /** Called when the session list changes so the parent can sync (optional) */
  onSessionsChange?: (sessions: ExtendedChatSession[]) => void;
}

export interface SessionListData {
  sortedSessions: ExtendedChatSession[];
  loading: boolean;
  /** ID of session whose switch is in flight (null = none) */
  switchingSessionId: string | null;
  editingSessionId: string | null;
  editValue: string;
  t: ReturnType<typeof useTranslation>["t"];
  handleSessionClick: (sessionId: string) => void;
  handleEditStart: (sessionId: string, currentName: string) => void;
  handleDelete: (sessionId: string) => void;
  handleArchiveToggle: (sessionId: string) => void;
  handlePinToggle: (sessionId: string, pinned: boolean) => void;
  handleEditChange: (value: string) => void;
  handleEditSubmit: () => void;
  handleEditCancel: () => void;
  handleItemContextMenu: (sessionId: string, event: React.MouseEvent) => void;
  /** Shared context-menu state */
  contextMenu: ReturnType<typeof useContextMenu>;
  contextMenuItems: ContextMenuItem[];
  refreshSessions: () => Promise<void>;
}

/**
 * Shared session-list logic extracted from ChatSessionDrawer.
 * Both ChatSessionDrawer and SidebarSessionList use this hook.
 *
 * The `onSessionClick` callback is injected by the caller so that:
 * - ChatSessionDrawer can call setCurrentSessionId directly (inside context).
 * - SidebarSessionList can dispatch a DOM event (outside context).
 */
export function useSessionListData(
  sessions: ExtendedChatSession[],
  setSessions: (s: ExtendedChatSession[]) => void,
  opts: UseSessionListDataOptions,
): SessionListData {
  const { t } = useTranslation();
  const { message } = useAppMessage();
  const { active, currentSessionId, onSessionClick } = opts;
  // Re-fetch immediately when the selected agent changes — the shared store
  // is cleared synchronously on the switch and must be repopulated for the
  // new agent without waiting for the next poll tick.
  const selectedAgent = useAgentStore((s) => s.selectedAgent);

  const [loading, setLoading] = useState(true);
  const [switchingSessionId, setSwitchingSessionId] = useState<string | null>(
    null,
  );
  const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
  const [editValue, setEditValue] = useState("");

  const sharedContextMenu = useContextMenu();
  const [contextMenuSessionId, setContextMenuSessionId] = useState<
    string | null
  >(null);

  /** Cache last polled sessions to skip no-op state updates */
  const lastSessionsRef = useRef<ExtendedChatSession[]>([]);

  const refreshSessions = useCallback(async () => {
    const owner = sessionApi.getActiveOwner();
    try {
      const list = await sessionApi.getSessionList();
      // Never publish a list that finished loading under a previous agent.
      if (!sessionApi.isActiveOwner(owner)) return;
      const extended = list as ExtendedChatSession[];
      setSessions(extended);
      syncSessionsGlobal(extended);
    } catch (err) {
      console.error("useSessionListData: failed to fetch sessions", err);
    }
  }, [setSessions]);

  useEffect(() => {
    if (!active) return;
    let cancelled = false;
    const owner = sessionApi.getActiveOwner();

    const fetchSessions = async () => {
      setLoading(true);
      try {
        const list = await sessionApi.getSessionList();
        if (!cancelled && sessionApi.isActiveOwner(owner)) {
          const extended = list as ExtendedChatSession[];
          if (!sessionsEqual(lastSessionsRef.current, extended)) {
            lastSessionsRef.current = extended;
            setSessions(extended);
            syncSessionsGlobal(extended);
          }
        }
      } catch (err) {
        console.error("useSessionListData: failed to fetch sessions", err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    void fetchSessions();

    const timer = setInterval(async () => {
      // Pause polling during session switch to avoid bandwidth contention
      if (sessionApi.isSessionSwitching) return;
      try {
        const list = await sessionApi.getSessionList();
        if (!cancelled && sessionApi.isActiveOwner(owner)) {
          const extended = list as ExtendedChatSession[];
          if (!sessionsEqual(lastSessionsRef.current, extended)) {
            lastSessionsRef.current = extended;
            setSessions(extended);
            syncSessionsGlobal(extended);
          }
        }
      } catch {
        // ignore polling errors
      }
    }, 3000);

    return () => {
      cancelled = true;
      clearInterval(timer);
    };
  }, [active, setSessions, selectedAgent]);

  const resolvedSessions = useMemo(() => {
    return sessions.filter((s) => {
      const id = s.id ?? "";
      return !(/^\d+-[a-z0-9]+$/.test(id) && !s.realId);
    });
  }, [sessions]);

  const sortedSessions = useMemo(() => {
    return [...resolvedSessions]
      .filter((s) => !s.archived)
      .sort((a, b) => {
        const aTime = a.updatedAt ?? a.createdAt ?? "";
        const bTime = b.updatedAt ?? b.createdAt ?? "";
        if (!aTime && !bTime) return 0;
        if (!aTime) return 1;
        if (!bTime) return -1;
        return bTime < aTime ? -1 : bTime > aTime ? 1 : 0;
      });
  }, [resolvedSessions]);

  const handleSessionClick = useCallback(
    (sessionId: string) => {
      if (sessionId === currentSessionId) return;
      setSwitchingSessionId(sessionId);
      onSessionClick(sessionId);
    },
    [currentSessionId, onSessionClick],
  );

  // Clear switchingSessionId once the URL / currentSessionId has settled
  useEffect(() => {
    setSwitchingSessionId(null);
  }, [currentSessionId]);

  // Also clear switchingSessionId when the switch completes (or fails).
  // This is needed for SidebarSessionList (simple mode) which communicates
  // via DOM events and may not see currentSessionId change on errors.
  useEffect(() => {
    const onDone = () => setSwitchingSessionId(null);
    window.addEventListener("qwenpaw:sidebar-switch-done", onDone);
    return () =>
      window.removeEventListener("qwenpaw:sidebar-switch-done", onDone);
  }, []);

  const handleDelete = useCallback(
    async (sessionId: string) => {
      const owner = sessionApi.getActiveOwner();
      const session = sessions.find((s) => s.id === sessionId);
      const backendId = session ? getBackendId(session) : null;
      if (backendId) await chatApi.deleteChat(backendId);

      // Per-session cleanup is safe regardless of the active agent: it is
      // keyed to the deleted conversation only.
      localStorage.removeItem(`approval_level-${sessionId}`);

      // Clear the message queue for the deleted session so stale items don't
      // linger in storage or get sent after deletion. The queue may be keyed
      // by the local id or the resolved backend id, so clear both.
      const mq = useMessageQueueStore.getState();
      mq.clear(sessionId);
      if (backendId && backendId !== sessionId) mq.clear(backendId);

      // Everything below mutates the CURRENT view (callbacks, shared list,
      // navigation). A delete that finished after an agent switch must not
      // touch the new agent's state.
      if (!sessionApi.isActiveOwner(owner)) return;
      sessionApi.onSessionRemoved?.(backendId ?? sessionId);

      // Fetch fresh session list after deletion
      const freshList =
        (await sessionApi.getSessionList()) as ExtendedChatSession[];
      if (!sessionApi.isActiveOwner(owner)) return;
      setSessions(freshList);
      syncSessionsGlobal(freshList);

      // Post-deletion check: if the currently displayed session no longer
      // exists in the refreshed list, navigate to a new blank chat.
      // This avoids all ID-format mismatch issues between URL chatId,
      // session.id, and session.realId.
      if (currentSessionId) {
        const stillExists = freshList.some(
          (s) =>
            s.id === currentSessionId ||
            (s as ExtendedChatSession).realId === currentSessionId,
        );
        if (!stillExists) {
          window.dispatchEvent(new CustomEvent("qwenpaw:sidebar-new-chat"));
        }
      }
    },
    [sessions, currentSessionId, setSessions],
  );

  const handleEditStart = useCallback(
    (sessionId: string, currentName: string) => {
      setEditingSessionId(sessionId);
      setEditValue(currentName);
    },
    [],
  );

  const handleEditChange = useCallback((value: string) => {
    setEditValue(value);
  }, []);

  const handleEditSubmit = useCallback(async () => {
    if (!editingSessionId) return;
    const owner = sessionApi.getActiveOwner();
    const session = sessions.find((s) => s.id === editingSessionId);
    const backendId = session ? getBackendId(session) : null;
    const newName = editValue.trim();
    if (backendId && newName) {
      await chatApi.updateChat(backendId, { name: newName });
    }
    setEditingSessionId(null);
    setEditValue("");
    if (!sessionApi.isActiveOwner(owner)) return;
    await refreshSessions();
  }, [editingSessionId, editValue, sessions, refreshSessions]);

  const handleEditCancel = useCallback(() => {
    setEditingSessionId(null);
    setEditValue("");
  }, []);

  const handleArchiveToggle = useCallback(
    async (sessionId: string) => {
      const owner = sessionApi.getActiveOwner();
      const session = sessions.find((s) => s.id === sessionId);
      const backendId = session ? getBackendId(session) : null;
      if (!backendId) return;
      const wasArchived = !!session?.archived;
      try {
        if (wasArchived) {
          await chatApi.unarchiveChat(backendId);
        } else {
          await chatApi.archiveChat(backendId);
        }
        if (!sessionApi.isActiveOwner(owner)) return;
        message.success(
          wasArchived
            ? t("sessions.archive.unarchiveSuccess", "Chat unarchived")
            : t("sessions.archive.successHint"),
        );
        await refreshSessions();

        if (!wasArchived && currentSessionId) {
          const isCurrentSession =
            sessionId === currentSessionId || backendId === currentSessionId;
          if (isCurrentSession) {
            window.dispatchEvent(new CustomEvent("qwenpaw:sidebar-new-chat"));
          }
        }
      } catch (err) {
        console.error("Failed to toggle archive status:", err);
        message.error(
          t("sessions.archive.failed", "Failed to update archive status"),
        );
      }
    },
    [sessions, currentSessionId, refreshSessions, message, t],
  );

  const handlePinToggle = useCallback(
    async (sessionId: string, pinned: boolean) => {
      const owner = sessionApi.getActiveOwner();
      const session = sessions.find((item) => item.id === sessionId);
      const backendId = session ? getBackendId(session) : null;
      if (!backendId) return;
      try {
        await chatApi.updateChat(backendId, { pinned });
        if (!sessionApi.isActiveOwner(owner)) return;
        await refreshSessions();
      } catch (error) {
        console.error("Failed to update conversation pin:", error);
        message.error(
          t("chat.contextMenu.pinFailed", "Could not update pinned state"),
        );
      }
    },
    [message, refreshSessions, sessions, t],
  );

  const handleItemContextMenu = useCallback(
    (sessionId: string, event: React.MouseEvent) => {
      setContextMenuSessionId(sessionId);
      sharedContextMenu.show(event);
    },
    [sharedContextMenu],
  );

  const contextMenuItems: ContextMenuItem[] = useMemo(() => {
    if (!contextMenuSessionId) return [];
    const session = sessions.find((s) => s.id === contextMenuSessionId);
    return [
      {
        key: "open",
        label: t("chat.contextMenu.open", "Open"),
        onClick: () => handleSessionClick(contextMenuSessionId),
      },
      {
        key: "rename",
        label: t("chat.contextMenu.rename", "Rename"),
        onClick: () =>
          handleEditStart(contextMenuSessionId, session?.name || "New Chat"),
      },
      {
        key: "pin",
        label: session?.pinned
          ? t("chat.contextMenu.unpin", "Unpin")
          : t("chat.contextMenu.pin", "Pin"),
        onClick: () => handlePinToggle(contextMenuSessionId, !session?.pinned),
      },
      {
        key: "archive",
        label: session?.archived
          ? t("sessions.archive.unaction", "Unarchive")
          : t("sessions.archive.action", "Archive"),
        onClick: () => handleArchiveToggle(contextMenuSessionId),
      },
      { key: "divider-1", label: "", divider: true },
      {
        key: "delete",
        label: t("chat.contextMenu.delete", "Delete"),
        danger: true,
        onClick: () => handleDelete(contextMenuSessionId),
      },
    ];
  }, [
    contextMenuSessionId,
    sessions,
    t,
    handleSessionClick,
    handleEditStart,
    handleArchiveToggle,
    handlePinToggle,
    handleDelete,
  ]);

  return {
    sortedSessions,
    loading,
    switchingSessionId,
    editingSessionId,
    editValue,
    t,
    handleSessionClick,
    handleEditStart,
    handleDelete,
    handleArchiveToggle,
    handlePinToggle,
    handleEditChange,
    handleEditSubmit,
    handleEditCancel,
    handleItemContextMenu,
    contextMenu: sharedContextMenu,
    contextMenuItems,
    refreshSessions,
  };
}