Open History to see the last commit
1import type { OrchestrationThreadActivity } from "@t3tools/contracts";
2import { useEffect, useRef } from "react";
3
4const WORKSPACE_MUTATION_ITEM_TYPES = new Set(["command_execution", "file_change"]);
5
6function activityPayload(activity: OrchestrationThreadActivity): Record<string, unknown> | null {
7 return activity.payload !== null && typeof activity.payload === "object"
8 ? (activity.payload as Record<string, unknown>)
9 : null;
10}
11
12/**
13 * The latest provider event after which files on disk may have changed.
14 * File tools are explicit; completed commands are included because a shell
15 * command can mutate the workspace without reporting the paths it touched.
16 */
17export function latestWorkspaceMutationId(
18 activities: ReadonlyArray<OrchestrationThreadActivity>,
19): string | null {
20 for (let index = activities.length - 1; index >= 0; index -= 1) {
21 const activity = activities[index];
22 if (!activity) continue;
23 const payload = activityPayload(activity);
24 const terminalUpdate =
25 activity.kind === "tool.updated" &&
26 typeof payload?.status === "string" &&
27 payload.status !== "inProgress" &&
28 payload.status !== "in_progress";
29 if (activity.kind !== "tool.completed" && !terminalUpdate) continue;
30 const itemType = payload?.itemType;
31 if (typeof itemType === "string" && WORKSPACE_MUTATION_ITEM_TYPES.has(itemType)) {
32 return activity.id;
33 }
34 }
35 return null;
36}
37
38export function workspaceMutationRefreshToken(
39 resourceKey: string,
40 mutationId: string | null,
41): string | null {
42 return mutationId === null ? null : `${resourceKey}\u0000${mutationId}`;
43}
44
45/**
46 * Refreshes once per mutation and resource. Disabled mutations stay pending,
47 * which lets an editable file catch up after its local save finishes.
48 */
49export function useWorkspaceMutationRefresh(input: {
50 readonly enabled?: boolean;
51 readonly mutationId: string | null;
52 readonly refresh: () => void;
53 readonly resourceKey: string;
54}): void {
55 const { enabled = true, mutationId, refresh, resourceKey } = input;
56 const handledTokenRef = useRef<string | null>(null);
57
58 useEffect(() => {
59 if (!enabled) return;
60 const token = workspaceMutationRefreshToken(resourceKey, mutationId);
61 if (token === null || token === handledTokenRef.current) return;
62 handledTokenRef.current = token;
63 refresh();
64 }, [enabled, mutationId, refresh, resourceKey]);
65}