| 1 | import { asArray } from "./array"; |
| 2 | import { getLocale, type DictKey, type Translator } from "./i18n"; |
| 3 | import type { ProjectNode, ProjectTopicStatus } from "./types"; |
| 4 | import { projectSessionIdentity, projectSessionExcluded, projectSessionKeys, canonicalProjectSession, projectSessionResolver } from "./projectSessionIdentity"; |
| 5 | |
| 6 | export type ProjectTreeVariant = "workbench" | "creation"; |
| 7 | export type WorkbenchSortMode = "created" | "updated"; |
| 8 | |
| 9 | // Shared by workbench and creation; key string kept for existing saved choices |
| 10 | // and for downgrade compatibility. |
| 11 | export const WORKBENCH_SORT_KEY = "projectTree:workbenchSort"; |
| 12 | export const WORKBENCH_SORT_CREATED_DEFAULT_MIGRATION_KEY = "projectTree:workbenchSort:createdDefault:v1"; |
| 13 | |
| 14 | export function loadWorkbenchSortMode(): WorkbenchSortMode { |
| 15 | try { |
| 16 | if (localStorage.getItem(WORKBENCH_SORT_CREATED_DEFAULT_MIGRATION_KEY) !== "1") { |
| 17 | // This release intentionally resets every existing choice once. Keep the |
| 18 | // original preference key so older builds can still read the new value. |
| 19 | localStorage.setItem(WORKBENCH_SORT_KEY, "created"); |
| 20 | localStorage.setItem(WORKBENCH_SORT_CREATED_DEFAULT_MIGRATION_KEY, "1"); |
| 21 | return "created"; |
| 22 | } |
| 23 | const value = localStorage.getItem(WORKBENCH_SORT_KEY); |
| 24 | if (value === "created" || value === "updated") return value; |
| 25 | } catch { |
| 26 | /* localStorage unavailable */ |
| 27 | } |
| 28 | return "created"; |
| 29 | } |
| 30 | |
| 31 | export function isRuntimeSessionNode(node: ProjectNode): boolean { |
| 32 | return node.kind === "session" || node.kind === "global_session"; |
| 33 | } |
| 34 | |
| 35 | export function isTopicNode(node: ProjectNode): boolean { |
| 36 | return node.kind === "topic" || node.kind === "global_topic"; |
| 37 | } |
| 38 | |
| 39 | export function projectTreeRevisionIsFresh(currentRevision: number, incomingRevision: number): boolean { |
| 40 | return incomingRevision >= currentRevision; |
| 41 | } |
| 42 | |
| 43 | export function projectTreeTopicPageIsFresh( |
| 44 | revisions: Readonly<Record<string, number>>, |
| 45 | projectKey: string, |
| 46 | incomingRevision: number, |
| 47 | ): boolean { |
| 48 | return projectTreeRevisionIsFresh(revisions[projectKey] ?? 0, incomingRevision); |
| 49 | } |
| 50 | |
| 51 | // Project shells come from desktop-projects.json and are valid even when the |
| 52 | // disposable catalog still reports revision 0. Catalog revision only gates |
| 53 | // topic pages and non-empty tree refreshes after the first shell is painted. |
| 54 | export function projectTreeShouldApplyShellSnapshot(options: { |
| 55 | currentRevision: number; |
| 56 | incomingRevision: number; |
| 57 | treeEmpty: boolean; |
| 58 | }): boolean { |
| 59 | if (options.treeEmpty) return true; |
| 60 | return projectTreeRevisionIsFresh(options.currentRevision, options.incomingRevision); |
| 61 | } |
| 62 | |
| 63 | export function mergeProjectTopicPage(current: ProjectNode[], incoming: ProjectNode[], append: boolean): ProjectNode[] { |
| 64 | // Owner aliases retire the source projection even when its old page arrives |
| 65 | // after adoption. Canonical identity always wins; its durable row metadata is retained. |
| 66 | const identity = projectSessionResolver([...current, ...incoming]); |
| 67 | const canonical = new Map([...current, ...incoming].filter(canonicalProjectSession).map(node => [identity(node), node])); |
| 68 | incoming = incoming.map(row => canonical.get(identity(row)) ?? row); |
| 69 | let base = current; |
| 70 | if (!append) { |
| 71 | // Project snapshots carry every pinned topic shell, while a lazy first |
| 72 | // page is bounded. Keep off-page pins so expanding a busy project cannot |
| 73 | // make its pinned section incomplete again. |
| 74 | const incomingKeys = new Set(incoming.map(identity)); |
| 75 | base = incoming; |
| 76 | incoming = current.filter(node => Boolean(node.pinned) && !incomingKeys.has(identity(node))); |
| 77 | } |
| 78 | const rows = new Map<string, ProjectNode>(); |
| 79 | for (const node of [...base, ...incoming]) rows.set(identity(node), canonical.get(identity(node)) ?? node); |
| 80 | return [...rows.values()]; |
| 81 | } |
| 82 | |
| 83 | // A directory scan commits catalog rows in batches, but an incomplete page is |
| 84 | // not authoritative for replacement, deletion, timestamps, or order. Keep the |
| 85 | // last complete resident rows byte-for-byte and append only newly discovered |
| 86 | // keys until a complete page can replace the canonical first page. |
| 87 | export function mergeIncompleteProjectTopicPage(current: ProjectNode[], incoming: ProjectNode[]): ProjectNode[] { |
| 88 | const identity = projectSessionResolver([...current, ...incoming]); |
| 89 | const residents = new Map(current.map(node => [identity(node), node])); |
| 90 | const discovered = incoming.filter(node => { |
| 91 | const resident = residents.get(identity(node)); |
| 92 | return !resident || Boolean(canonicalProjectSession(node) && !canonicalProjectSession(resident)); |
| 93 | }); |
| 94 | return discovered.length === 0 ? current : mergeProjectTopicPage(current, discovered, true); |
| 95 | } |
| 96 | |
| 97 | // Topic page loads rewrite children, so a signature keyed only on the project |
| 98 | // shells lets the debounced reload effect observe arrivals without re-arming |
| 99 | // itself on its own writes. |
| 100 | export function projectTreeShellSignature(tree: ProjectNode[]): string { |
| 101 | return tree.map((node) => node.key).join("\u001f"); |
| 102 | } |
| 103 | |
| 104 | // After archive, drop that topic immediately so a shell-only refresh cannot |
| 105 | // resurrect it from the previously loaded children. |
| 106 | export function projectTreeWithoutTopic(tree: ProjectNode[], topicId: string): ProjectNode[] { |
| 107 | const id = topicId.trim(); |
| 108 | if (!id) return tree; |
| 109 | return projectTreeWithoutTopics(tree, new Set([id])); |
| 110 | } |
| 111 | |
| 112 | // Post-commit archive IDs are a client-side tombstone overlay. Apply it to |
| 113 | // every incoming page as well as the resident tree so a pre-commit request |
| 114 | // cannot paint a topic back before the canonical reload acquires its sequence. |
| 115 | export function projectTreeWithoutTopics(tree: ProjectNode[], topicIds: ReadonlySet<string>): ProjectNode[] { |
| 116 | if (topicIds.size === 0) return tree; |
| 117 | let changed = false; |
| 118 | const next: ProjectNode[] = []; |
| 119 | for (const node of tree) { |
| 120 | if ((isTopicNode(node) || isRuntimeSessionNode(node)) && |
| 121 | projectSessionExcluded(node, topicIds)) { |
| 122 | changed = true; |
| 123 | continue; |
| 124 | } |
| 125 | const children = asArray(node.children); |
| 126 | const filteredChildren = projectTreeWithoutTopics(children, topicIds); |
| 127 | if (filteredChildren !== children) { |
| 128 | changed = true; |
| 129 | next.push({ ...node, children: filteredChildren }); |
| 130 | } else { |
| 131 | next.push(node); |
| 132 | } |
| 133 | } |
| 134 | return changed ? next : tree; |
| 135 | } |
| 136 | |
| 137 | export function projectTreeWithoutSession(tree: ProjectNode[], target: ProjectNode): ProjectNode[] { |
| 138 | return projectTreeWithoutTopics(tree, new Set([projectSessionIdentity(target)])); |
| 139 | } |
| 140 | |
| 141 | // After a successful rename, paint the new label immediately instead of |
| 142 | // waiting for the catalog event round-trip. |
| 143 | export function projectTreeWithTopicTitle(tree: ProjectNode[], topicId: string, title: string): ProjectNode[] { |
| 144 | const id = topicId.trim(); |
| 145 | if (!id) return tree; |
| 146 | let changed = false; |
| 147 | const next: ProjectNode[] = []; |
| 148 | for (const node of tree) { |
| 149 | if (node.topicId === id && (isTopicNode(node) || isRuntimeSessionNode(node))) { |
| 150 | if (node.label !== title) { |
| 151 | changed = true; |
| 152 | next.push({ ...node, label: title }); |
| 153 | } else { |
| 154 | next.push(node); |
| 155 | } |
| 156 | continue; |
| 157 | } |
| 158 | const children = asArray(node.children); |
| 159 | const renamedChildren = projectTreeWithTopicTitle(children, id, title); |
| 160 | if (renamedChildren !== children) { |
| 161 | changed = true; |
| 162 | next.push({ ...node, children: renamedChildren }); |
| 163 | } else { |
| 164 | next.push(node); |
| 165 | } |
| 166 | } |
| 167 | return changed ? next : tree; |
| 168 | } |
| 169 | |
| 170 | export function projectTreeWithSessionTitle(tree: ProjectNode[], target: ProjectNode, title: string): ProjectNode[] { |
| 171 | const identity = projectSessionIdentity(target); |
| 172 | return tree.map((node) => { |
| 173 | if ((isTopicNode(node) || isRuntimeSessionNode(node)) && projectSessionIdentity(node) === identity) { |
| 174 | return node.label === title ? node : { ...node, label: title }; |
| 175 | } |
| 176 | if (!node.children?.length) return node; |
| 177 | const children = projectTreeWithSessionTitle(node.children, target, title); |
| 178 | return children.every((child, index) => child === node.children?.[index]) ? node : { ...node, children }; |
| 179 | }); |
| 180 | } |
| 181 | |
| 182 | export function projectTreeFolderKeyForTopic(tree: ProjectNode[], topicId: string): string { |
| 183 | const id = topicId.trim(); |
| 184 | if (!id) return ""; |
| 185 | for (const node of tree) { |
| 186 | if (node.kind !== "project" && node.kind !== "global_folder") continue; |
| 187 | if (asArray(node.children).some((child) => child.topicId === id)) return node.key; |
| 188 | } |
| 189 | return ""; |
| 190 | } |
| 191 | |
| 192 | export function projectTreeFolderKeyForSession(tree: ProjectNode[], sessionPath: string): string { |
| 193 | const path = sessionPath.trim(); |
| 194 | if (!path) return ""; |
| 195 | const containsSession = (nodes: ProjectNode[]): boolean => nodes.some((node) => |
| 196 | ((isRuntimeSessionNode(node) || isTopicNode(node)) && node.sessionPath?.trim() === path) |
| 197 | || containsSession(asArray(node.children)), |
| 198 | ); |
| 199 | for (const node of tree) { |
| 200 | if (node.kind !== "project" && node.kind !== "global_folder") continue; |
| 201 | if (containsSession(asArray(node.children))) return node.key; |
| 202 | } |
| 203 | return ""; |
| 204 | } |
| 205 | |
| 206 | export function invalidateProjectTreeTopicLoads(sequences: Record<string, number>, keys: Iterable<string>): void { |
| 207 | for (const key of keys) { |
| 208 | let matched = false; |
| 209 | const prefix = `${key}\u001f`; |
| 210 | for (const sequenceKey of Object.keys(sequences)) { |
| 211 | if (sequenceKey !== key && !sequenceKey.startsWith(prefix)) continue; |
| 212 | sequences[sequenceKey] = (sequences[sequenceKey] ?? 0) + 1; |
| 213 | matched = true; |
| 214 | } |
| 215 | if (!matched) sequences[key] = (sequences[key] ?? 0) + 1; |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | export function projectTreeShellChildren( |
| 220 | previous: ProjectNode[] | undefined, |
| 221 | pinnedShells: ProjectNode[] | undefined = [], |
| 222 | ): ProjectNode[] { |
| 223 | const shells = asArray(pinnedShells).filter((node) => isTopicNode(node) && Boolean(node.pinned)); |
| 224 | if (!previous || previous.length === 0) return shells; |
| 225 | |
| 226 | const shellByKey = new Map(shells.map((node) => [node.key, node])); |
| 227 | const next = asArray(previous).map((node) => { |
| 228 | if (!isTopicNode(node)) return node; |
| 229 | const shell = shellByKey.get(node.key); |
| 230 | if (!shell) return node.pinned ? { ...node, pinned: false } : node; |
| 231 | shellByKey.delete(node.key); |
| 232 | return { ...node, ...shell, children: node.children ?? shell.children }; |
| 233 | }); |
| 234 | return [...next, ...shellByKey.values()]; |
| 235 | } |
| 236 | |
| 237 | export function projectTreeEventAffectsFolder(project: ProjectNode, roots: string[]): boolean { |
| 238 | if (roots.length === 0) return true; |
| 239 | const root = project.kind === "global_folder" ? "" : project.root ?? ""; |
| 240 | return roots.includes(root); |
| 241 | } |
| 242 | |
| 243 | export type ProjectTreeTopicOpenRequest = { |
| 244 | scope: "global" | "project"; |
| 245 | workspaceRoot: string; |
| 246 | topicId: string; |
| 247 | sessionPath?: string; |
| 248 | }; |
| 249 | |
| 250 | export function projectTreeTopicOpenRequest(node: ProjectNode): ProjectTreeTopicOpenRequest | null { |
| 251 | if (!isTopicNode(node) && !isRuntimeSessionNode(node)) return null; |
| 252 | const scope = node.kind === "global_topic" || node.kind === "global_session" ? "global" : "project"; |
| 253 | return { |
| 254 | scope, |
| 255 | workspaceRoot: scope === "global" ? "" : node.root ?? "", |
| 256 | topicId: node.topicId ?? "", |
| 257 | sessionPath: node.session ? `session-id:${node.session.sessionId}` : node.source |
| 258 | ? `session-source:${encodeURIComponent(JSON.stringify({ ...node.source, title: node.label }))}` : node.sessionPath, |
| 259 | }; |
| 260 | } |
| 261 | |
| 262 | export type ProjectTreeTopicClickTarget = { |
| 263 | rowKey: string; |
| 264 | canRename: boolean; |
| 265 | }; |
| 266 | |
| 267 | export type ProjectTreePendingTopicOpen = ProjectTreeTopicClickTarget & { |
| 268 | timer: ReturnType<typeof setTimeout>; |
| 269 | }; |
| 270 | |
| 271 | export function projectTreeShouldSuppressOpenForRename( |
| 272 | pending: ProjectTreeTopicClickTarget | null, |
| 273 | next: ProjectTreeTopicClickTarget, |
| 274 | ): boolean { |
| 275 | return Boolean(pending && pending.rowKey === next.rowKey && pending.canRename && next.canRename); |
| 276 | } |
| 277 | |
| 278 | export type ProjectTreeFolderDisclosure = { |
| 279 | canExpand: boolean; |
| 280 | isOpen: boolean; |
| 281 | ariaExpanded?: boolean; |
| 282 | iconStackClassName: string; |
| 283 | }; |
| 284 | |
| 285 | // allowEmptyExpand lets a project shell open before its first topic page has |
| 286 | // arrived: without it an empty folder is inert, so expanding it could never |
| 287 | // start the load that fills it. |
| 288 | export function projectTreeFolderDisclosure(hasChildren: boolean, isExpanded: boolean, allowEmptyExpand = false): ProjectTreeFolderDisclosure { |
| 289 | const canExpand = hasChildren || allowEmptyExpand; |
| 290 | const isOpen = canExpand && isExpanded; |
| 291 | return { |
| 292 | canExpand, |
| 293 | isOpen, |
| 294 | ariaExpanded: canExpand ? isExpanded : undefined, |
| 295 | iconStackClassName: `project-tree__icon-stack${canExpand ? " project-tree__icon-stack--expandable" : ""}`, |
| 296 | }; |
| 297 | } |
| 298 | |
| 299 | function topicMatchesActiveIdentity(node: ProjectNode, activeScope?: string, activeWorkspaceRoot?: string, activeTopicId?: string): boolean { |
| 300 | if (!node.topicId || !activeTopicId) return false; |
| 301 | const scope = node.kind === "global_topic" || node.kind === "global_session" ? "global" : "project"; |
| 302 | if (scope === "global") return activeScope === "global" && activeTopicId === node.topicId; |
| 303 | return activeScope === "project" && activeTopicId === node.topicId && activeWorkspaceRoot === node.root; |
| 304 | } |
| 305 | |
| 306 | type ActiveRemoteSessionIdentity = { |
| 307 | hostId: string; |
| 308 | workspace: string; |
| 309 | sessionId?: string; |
| 310 | }; |
| 311 | |
| 312 | function remoteTopicMatchesActiveSession(node: ProjectNode, activeRemote?: ActiveRemoteSessionIdentity): boolean { |
| 313 | const remote = node.remoteSession; |
| 314 | const active = activeRemote; |
| 315 | if (!remote || !active || remote.hostId !== active.hostId || remote.workspace !== active.workspace) return false; |
| 316 | const sessionID = active.sessionId?.trim(); |
| 317 | if (!sessionID) return false; |
| 318 | return remote.sessionId?.trim() === sessionID || (!remote.sessionId?.trim() && remote.name.trim() === sessionID); |
| 319 | } |
| 320 | |
| 321 | export function topicIsActive( |
| 322 | node: ProjectNode, |
| 323 | activeScope?: string, |
| 324 | activeWorkspaceRoot?: string, |
| 325 | activeTopicId?: string, |
| 326 | activeSessionPath?: string, |
| 327 | activeRemote?: ActiveRemoteSessionIdentity, |
| 328 | ): boolean { |
| 329 | if (node.source?.headId) return projectTreeTopicOpenRequest(node)?.sessionPath === activeSessionPath; |
| 330 | if (node.session?.sessionId) { |
| 331 | return Boolean(activeSessionPath && (activeSessionPath === `session-id:${node.session.sessionId}` || activeSessionPath === node.sessionPath |
| 332 | || projectSessionKeys(node).includes(`path\u0000${activeSessionPath}`))); |
| 333 | } |
| 334 | if (isRuntimeSessionNode(node)) { |
| 335 | return Boolean(node.sessionPath && activeSessionPath && activeSessionPath === node.sessionPath); |
| 336 | } |
| 337 | if (!isTopicNode(node)) return false; |
| 338 | if (activeSessionPath && asArray(node.children).some(isRuntimeSessionNode)) return false; |
| 339 | // Remote filesystem paths are not globally unique: two hosts can expose the |
| 340 | // same absolute session path. Their synthesized rows already carry a |
| 341 | // host-qualified topicId, so never let the generic path fallback mark a row |
| 342 | // from another host active. |
| 343 | if (node.remoteSession) { |
| 344 | if (remoteTopicMatchesActiveSession(node, activeRemote)) return true; |
| 345 | return topicMatchesActiveIdentity(node, activeScope, activeWorkspaceRoot, activeTopicId); |
| 346 | } |
| 347 | if (node.sessionPath) return Boolean(activeSessionPath && activeSessionPath === node.sessionPath); |
| 348 | if (topicMatchesActiveIdentity(node, activeScope, activeWorkspaceRoot, activeTopicId)) return true; |
| 349 | return Boolean(node.sessionPath && activeSessionPath && activeSessionPath === node.sessionPath); |
| 350 | } |
| 351 | |
| 352 | export function projectTreeTopicMetaLine(node: ProjectNode, t: Translator, compact = false): string { |
| 353 | const parts: string[] = []; |
| 354 | const turns = node.turns ?? 0; |
| 355 | if (node.turnsState === "unknown") parts.push(t("history.indexing")); |
| 356 | else if (turns > 0) parts.push(t(turns === 1 ? "history.turnOne" : "history.turnOther", { n: turns })); |
| 357 | const activityAt = node.lastActivityAt || node.createdAt || 0; |
| 358 | if (activityAt) parts.push(topicActivityLabel(activityAt, t, compact)); |
| 359 | if (parts.length === 0) parts.push(t("projectTree.previously")); |
| 360 | return parts.join(" · "); |
| 361 | } |
| 362 | |
| 363 | // Activity labels older than a week are already the calendar date (always the |
| 364 | // meta line's last part), so callers pairing the two keep a single copy. |
| 365 | export function projectTreeDedupedExactTime(metaLine: string, exactTime: string): string { |
| 366 | return exactTime && metaLine.endsWith(exactTime) ? "" : exactTime; |
| 367 | } |
| 368 | |
| 369 | export function topicUnknownTimeLabel(node: ProjectNode, t: Translator): string { |
| 370 | return topicActivityAt(node) ? "" : t("projectTree.previously"); |
| 371 | } |
| 372 | |
| 373 | const topicStatusLabels: Record<ProjectTopicStatus, DictKey> = { |
| 374 | thinking: "projectTree.status.thinking", |
| 375 | finishing: "runtime.finishing", |
| 376 | unknown: "runtime.unknown", |
| 377 | cancelling: "status.jobStopping", |
| 378 | streaming: "projectTree.status.streaming", |
| 379 | waiting_confirmation: "projectTree.status.waitingConfirmation", |
| 380 | background_job: "projectTree.status.backgroundJob", |
| 381 | paused: "projectTree.status.paused", |
| 382 | awaiting_delivery: "projectTree.status.awaitingDelivery", |
| 383 | error: "projectTree.status.error", |
| 384 | diverged_recovery: "projectTree.status.divergedRecovery", |
| 385 | }; |
| 386 | |
| 387 | export function normalizeTopicStatus(status?: string): ProjectTopicStatus | "" { |
| 388 | if (status === "finishing" || status === "cancelling" || status === "unknown") return status; |
| 389 | if (!status) return ""; |
| 390 | if (status === "thinking" || status === "streaming" || status === "waiting_confirmation" || status === "background_job" || status === "paused" || status === "awaiting_delivery" || status === "error" || status === "diverged_recovery") { |
| 391 | return status; |
| 392 | } |
| 393 | return ""; |
| 394 | } |
| 395 | |
| 396 | export function topicStatus(node: ProjectNode): ProjectTopicStatus | "" { |
| 397 | // Ordinary list never surfaces recovery-branch status. Active runtime states |
| 398 | // only: thinking/streaming/waiting/etc. History owns other saved versions. |
| 399 | const live = node.running ? "streaming" : ""; |
| 400 | const stored = normalizeTopicStatus(node.status); |
| 401 | if (stored && stored !== "diverged_recovery") return stored; |
| 402 | return live; |
| 403 | } |
| 404 | |
| 405 | export function projectTreeTopicArchiveBlocked(node: ProjectNode): boolean { |
| 406 | if (node.status === "finishing" || node.status === "cancelling" || node.status === "unknown") return true; |
| 407 | if (asArray(node.children).some(projectTreeTopicArchiveBlocked)) return true; |
| 408 | const status = normalizeTopicStatus(node.status); |
| 409 | if (status === "thinking" || status === "streaming" || status === "waiting_confirmation" || status === "background_job") return true; |
| 410 | if (status === "paused" || status === "awaiting_delivery" || status === "error" || status === "diverged_recovery") return false; |
| 411 | return Boolean(node.running); |
| 412 | } |
| 413 | |
| 414 | export function topicStatusLabel(node: ProjectNode, t: Translator): string { |
| 415 | const status = topicStatus(node); |
| 416 | return status ? t(topicStatusLabels[status]) : ""; |
| 417 | } |
| 418 | |
| 419 | export function topicActivityAt(node: ProjectNode): number { |
| 420 | return node.lastActivityAt || node.createdAt || 0; |
| 421 | } |
| 422 | |
| 423 | export function topicReadRevision(node: ProjectNode): number { |
| 424 | if (topicUsesResultSequence(node)) return node.resultSequence ?? 0; |
| 425 | return topicActivityAt(node); |
| 426 | } |
| 427 | |
| 428 | // Read activity is shared without changing the remote node's action routing. |
| 429 | // Missing sequence means an older Serve; zero is a valid supported baseline. |
| 430 | export function topicUsesResultSequence(node: ProjectNode): boolean { |
| 431 | return Boolean(node.session || node.remoteSession && node.resultSequence !== undefined); |
| 432 | } |
| 433 | |
| 434 | export function projectTreeReadActivityKey(node: ProjectNode): string | null { |
| 435 | if (node.session?.sessionId) return projectSessionIdentity(node); |
| 436 | if (node.sessionPath || node.source || node.remoteSession) return projectSessionIdentity(node); |
| 437 | const request = projectTreeTopicOpenRequest(node); |
| 438 | if (!request?.topicId) return null; |
| 439 | return [request.scope, request.workspaceRoot, request.topicId].join("\u001f"); |
| 440 | } |
| 441 | |
| 442 | export type ProjectTreeReadActivity = Record<string, number>; |
| 443 | |
| 444 | export function projectTreeMigrateReadActivity(current: ProjectTreeReadActivity, storedVersion: number): ProjectTreeReadActivity { |
| 445 | if (storedVersion >= 2) return current; |
| 446 | let next = current; |
| 447 | for (const [key, revision] of Object.entries(current)) { |
| 448 | if (!key.startsWith("session\u001f") || revision !== 0) continue; |
| 449 | if (next === current) next = { ...current }; |
| 450 | delete next[key]; |
| 451 | } |
| 452 | return next; |
| 453 | } |
| 454 | |
| 455 | export function projectTreeSeedReadActivity(nodes: readonly ProjectNode[], current: ProjectTreeReadActivity): ProjectTreeReadActivity { |
| 456 | let next = current; |
| 457 | const visit = (items: readonly ProjectNode[]) => { |
| 458 | for (const node of items) { |
| 459 | const key = projectTreeReadActivityKey(node); |
| 460 | // A stale catalog cache is exposed as a canonical session with pending |
| 461 | // metadata and resultSequence 0 while its durable log is rebuilt. Do not |
| 462 | // persist that placeholder as the read baseline: once the real sequence |
| 463 | // arrives it would make every historical result look newly unread. |
| 464 | if (topicUsesResultSequence(node) && node.turnsState === "ready" && key |
| 465 | && next[key] === undefined) { |
| 466 | if (next === current) next = { ...current }; |
| 467 | next[key] = topicReadRevision(node); |
| 468 | } |
| 469 | visit(node.children ?? []); |
| 470 | } |
| 471 | }; |
| 472 | visit(nodes); |
| 473 | return next; |
| 474 | } |
| 475 | |
| 476 | export function projectTreeTopicHasUnreadActivity( |
| 477 | node: ProjectNode, |
| 478 | readActivity: ProjectTreeReadActivity, |
| 479 | activeScope?: string, |
| 480 | activeWorkspaceRoot?: string, |
| 481 | activeTopicId?: string, |
| 482 | activeSessionPath?: string, |
| 483 | baselineAt = 0, |
| 484 | activeRemote?: ActiveRemoteSessionIdentity, |
| 485 | ): boolean { |
| 486 | if (!isTopicNode(node) && !isRuntimeSessionNode(node)) return false; |
| 487 | if (topicIsActive(node, activeScope, activeWorkspaceRoot, activeTopicId, activeSessionPath, activeRemote)) return false; |
| 488 | if (topicStatus(node) !== "") return false; |
| 489 | if (node.remoteSession && topicUsesResultSequence(node) && node.turnsState !== "ready") return false; |
| 490 | const key = projectTreeReadActivityKey(node); |
| 491 | const revision = topicReadRevision(node); |
| 492 | if (!key || revision <= 0) return false; |
| 493 | if (topicUsesResultSequence(node)) return readActivity[key] !== undefined && readActivity[key] < revision; |
| 494 | return Math.max(readActivity[key] ?? 0, baselineAt) < revision; |
| 495 | } |
| 496 | |
| 497 | export function projectTreeShouldRenderTopicActions(isSessionNode: boolean, variant: ProjectTreeVariant, unread: boolean): boolean { |
| 498 | return !isSessionNode && variant !== "creation" && !unread; |
| 499 | } |
| 500 | |
| 501 | // Pinning reorders the trees shared with creation mode, so the creation |
| 502 | // context menu keeps its original rename/trash-only entries. |
| 503 | export function projectTreeTopicMenuOffersPin(variant: ProjectTreeVariant): boolean { |
| 504 | return variant !== "creation"; |
| 505 | } |
| 506 | |
| 507 | export function topicActivityLabel(ms: number, t: Translator, compact = false): string { |
| 508 | if (ms <= 0) return ""; |
| 509 | const delta = Date.now() - ms; |
| 510 | const locale = getLocale(); |
| 511 | const minute = 60_000; |
| 512 | const hour = 60 * minute; |
| 513 | const day = 24 * hour; |
| 514 | const month = 30 * day; |
| 515 | const year = 365 * day; |
| 516 | if (delta < minute) return t("projectTree.justNow"); |
| 517 | if (!compact) { |
| 518 | const rtfLocale = locale === "zh" ? "zh-CN" : locale === "zh-TW" ? "zh-TW" : "en"; |
| 519 | const rtf = new Intl.RelativeTimeFormat(rtfLocale, { numeric: "auto" }); |
| 520 | if (delta < hour) return rtf.format(-Math.max(1, Math.round(delta / minute)), "minute"); |
| 521 | if (delta < day) return rtf.format(-Math.round(delta / hour), "hour"); |
| 522 | if (delta < 7 * day) return rtf.format(-Math.round(delta / day), "day"); |
| 523 | return topicActivityDateLabel(ms); |
| 524 | } |
| 525 | if (delta < hour) { |
| 526 | const value = Math.max(1, Math.round(delta / minute)); |
| 527 | return locale === "zh" || locale === "zh-TW" ? `${value} 分钟` : `${value}m`; |
| 528 | } |
| 529 | if (delta < day) { |
| 530 | const value = Math.round(delta / hour); |
| 531 | return locale === "zh" || locale === "zh-TW" ? `${value} 小时` : `${value}h`; |
| 532 | } |
| 533 | if (delta < 7 * day) { |
| 534 | const value = Math.round(delta / day); |
| 535 | return locale === "zh" || locale === "zh-TW" ? `${value} 天` : `${value}d`; |
| 536 | } |
| 537 | if (delta < month) { |
| 538 | const value = Math.round(delta / day); |
| 539 | return locale === "zh" || locale === "zh-TW" ? `${value} 天` : `${value}d`; |
| 540 | } |
| 541 | if (delta < year) { |
| 542 | const value = Math.max(1, Math.round(delta / month)); |
| 543 | return locale === "zh" || locale === "zh-TW" ? `${value} 个月` : `${value}mo`; |
| 544 | } |
| 545 | const value = Math.max(1, Math.round(delta / year)); |
| 546 | return locale === "zh" || locale === "zh-TW" ? `${value} 年` : `${value}y`; |
| 547 | } |
| 548 | |
| 549 | export function topicActivityDateLabel(ms: number): string { |
| 550 | if (ms <= 0) return ""; |
| 551 | const locale = getLocale(); |
| 552 | const dateLocale = locale === "zh" ? "zh-CN" : locale === "zh-TW" ? "zh-TW" : "en"; |
| 553 | return new Date(ms).toLocaleDateString(dateLocale); |
| 554 | } |
| 555 |