mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 00:19:56 +08:00
54 lines
2.0 KiB
TypeScript
54 lines
2.0 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useState, useSyncExternalStore } from "react";
|
|
import { RECOVERY_PRINCIPAL_CHANGED, recoveryPrincipal } from "@/lib/recovery-principal";
|
|
import { subscribeSessionChanges } from "@/lib/session-events";
|
|
import { listWorkspaces, type ChatWorkspaceRegistration } from "@/lib/workspaces-api";
|
|
|
|
type WorkspaceList = { owner: string | null; rows: ChatWorkspaceRegistration[]; error: string };
|
|
let cached: WorkspaceList | null = null;
|
|
let latestRequest = 0;
|
|
|
|
function subscribePrincipal(notify: () => void) {
|
|
window.addEventListener(RECOVERY_PRINCIPAL_CHANGED, notify);
|
|
return () => window.removeEventListener(RECOVERY_PRINCIPAL_CHANGED, notify);
|
|
}
|
|
|
|
function initialList(owner: string | null): WorkspaceList {
|
|
return owner && cached?.owner === owner ? cached : { owner, rows: [], error: "" };
|
|
}
|
|
|
|
export function useChatWorkspaces() {
|
|
const owner = useSyncExternalStore(subscribePrincipal, recoveryPrincipal, () => null);
|
|
const [list, setList] = useState(() => initialList(owner));
|
|
|
|
useEffect(() => {
|
|
let alive = true;
|
|
let requested = 0;
|
|
async function refresh() {
|
|
const request = ++latestRequest;
|
|
requested = request;
|
|
const current = () => alive && request === requested && recoveryPrincipal() === owner;
|
|
try {
|
|
const rows = await listWorkspaces(true);
|
|
if (!current()) return;
|
|
const next = { owner, rows: rows.filter((row) => row.kind === "workspace"), error: "" };
|
|
if (owner && request === latestRequest) cached = next;
|
|
setList(next);
|
|
} catch (err) {
|
|
if (current()) setList((last) => ({
|
|
...last,
|
|
error: err instanceof Error ? err.message : String(err),
|
|
}));
|
|
}
|
|
}
|
|
setList(initialList(owner));
|
|
void refresh();
|
|
const unsubscribe = subscribeSessionChanges(refresh);
|
|
return () => { alive = false; unsubscribe(); };
|
|
}, [owner]);
|
|
|
|
const visible = list.owner === owner ? list : initialList(owner);
|
|
return { workspaces: visible.rows, error: visible.error };
|
|
}
|