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
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
/**
 * Per-scope persistence for Files workspace tabs and pending diffs.
 *
 * Persists to localStorage so the IDE survives a page reload and an
 * agent-switch round trip. To stay under the localStorage quota:
 *
 *   • File contents are NOT persisted — the path list is, and content
 *     is re-fetched via workspaceApi.loadCodeFile on hydrate (which
 *     hits the in-memory codeFileCacheStore + browser HTTP cache).
 *   • For pending diffs, only the `original` (pre-diff baseline) is
 *     persisted, capped at ORIGINAL_DIFF_SIZE_LIMIT. Above the cap,
 *     the diff stays in memory only and is dropped on reload.
 *   • The `modified` side of a diff is null after rehydrate; the
 *     consumer fetches the disk content on mount to fill it in.
 */
import { create } from "zustand";
import {
  createJSONStorage,
  persist,
  type StateStorage,
} from "zustand/middleware";
import type {
  FileSource,
  WorkspaceRoot,
} from "../features/files-workspace/types";
import { isProjectRoot } from "../features/files-workspace/directorySources";

export const ORIGINAL_DIFF_SIZE_LIMIT = 256 * 1024;
export const AGENT_FILES_TABS_STORAGE_KEY = "qwenpaw-agent-files-tabs";
export const SESSION_FILES_TABS_STORAGE_KEY = "qwenpaw-session-files-tabs";

export interface EditorTab {
  /** Internal stable identity used by the tab/diff stores. */
  path: string;
  /** User-facing and filesystem path. Never contains an internal source key. */
  displayPath?: string;
  content: string;
  dirty: boolean;
  source?: FileSource;
  workspaceRoot?: WorkspaceRoot;
  artifactUrl?: string;
  previewKind?: "text" | "image" | "pdf" | "csv" | "binary";
  readOnly?: boolean;
  /** Current disk version. Kept in memory only and refreshed after loading. */
  etag?: string;
}

export interface PendingDiff {
  original: string;
  /** null after rehydrate, populated by consumer's hydrate effect. */
  modified: string | null;
}

interface CodingTabsState {
  tabsByAgent: Record<string, EditorTab[]>;
  activeTabByAgent: Record<string, string>;
  diffsByAgent: Record<string, Record<string, PendingDiff>>;

  openTab: (agentId: string, tab: EditorTab) => void;
  closeTab: (agentId: string, path: string) => void;
  setActiveTab: (agentId: string, path: string) => void;
  setTabContent: (agentId: string, path: string, content: string) => void;
  setTabEtag: (agentId: string, path: string, etag: string) => void;
  setTabDirty: (agentId: string, path: string, dirty: boolean) => void;

  clearAgent: (agentId: string) => void;
  clearProjectTabs: (scopeKey: string) => void;
  migrateScope: (fromScopeKey: string, toScopeKey: string) => void;
  removeScope: (scopeKey: string) => void;

  setDiff: (agentId: string, path: string, diff: PendingDiff) => void;
  removeDiff: (agentId: string, path: string) => void;
  updateDiffModified: (agentId: string, path: string, modified: string) => void;
  updateDiffOriginal: (agentId: string, path: string, original: string) => void;
  resolveDiff: (agentId: string, path: string, content: string) => void;
}

const omitKey = <T extends object>(obj: T, key: string): T => {
  if (!(key in obj)) return obj;
  const next = { ...obj } as Record<string, unknown>;
  delete next[key];
  return next as T;
};

interface PersistedTabsEnvelope {
  state?: {
    tabsByAgent?: Record<string, EditorTab[]>;
    activeTabByAgent?: Record<string, string>;
    diffsByAgent?: Record<string, Record<string, PendingDiff>>;
  };
  version?: number;
}

function filterRecord<T>(
  record: Record<string, T> | undefined,
  prefix: "agent:" | "session:",
): Record<string, T> {
  return Object.fromEntries(
    Object.entries(record ?? {}).filter(([key]) => key.startsWith(prefix)),
  );
}

function scopedEnvelope(
  envelope: PersistedTabsEnvelope,
  prefix: "agent:" | "session:",
): PersistedTabsEnvelope {
  return {
    ...envelope,
    state: {
      tabsByAgent: filterRecord(envelope.state?.tabsByAgent, prefix),
      activeTabByAgent: filterRecord(envelope.state?.activeTabByAgent, prefix),
      diffsByAgent: filterRecord(envelope.state?.diffsByAgent, prefix),
    },
  };
}

/**
 * Zustand sees one store at runtime, while persistence is physically split
 * by ownership. The retired shared key is intentionally never read.
 */
const splitTabsStorage: StateStorage = {
  getItem: () => {
    const agentValue = localStorage.getItem(AGENT_FILES_TABS_STORAGE_KEY);
    const sessionValue = localStorage.getItem(SESSION_FILES_TABS_STORAGE_KEY);
    if (!agentValue && !sessionValue) return null;

    const agentEnvelope = agentValue
      ? (JSON.parse(agentValue) as PersistedTabsEnvelope)
      : {};
    const sessionEnvelope = sessionValue
      ? (JSON.parse(sessionValue) as PersistedTabsEnvelope)
      : {};
    return JSON.stringify({
      ...agentEnvelope,
      ...sessionEnvelope,
      state: {
        tabsByAgent: {
          ...agentEnvelope.state?.tabsByAgent,
          ...sessionEnvelope.state?.tabsByAgent,
        },
        activeTabByAgent: {
          ...agentEnvelope.state?.activeTabByAgent,
          ...sessionEnvelope.state?.activeTabByAgent,
        },
        diffsByAgent: {
          ...agentEnvelope.state?.diffsByAgent,
          ...sessionEnvelope.state?.diffsByAgent,
        },
      },
    } satisfies PersistedTabsEnvelope);
  },
  setItem: (_name, value) => {
    const envelope = JSON.parse(value) as PersistedTabsEnvelope;
    localStorage.setItem(
      AGENT_FILES_TABS_STORAGE_KEY,
      JSON.stringify(scopedEnvelope(envelope, "agent:")),
    );
    localStorage.setItem(
      SESSION_FILES_TABS_STORAGE_KEY,
      JSON.stringify(scopedEnvelope(envelope, "session:")),
    );
  },
  removeItem: () => {
    localStorage.removeItem(AGENT_FILES_TABS_STORAGE_KEY);
    localStorage.removeItem(SESSION_FILES_TABS_STORAGE_KEY);
  },
};

export const useCodingTabsStore = create<CodingTabsState>()(
  persist<CodingTabsState>(
    (set) => ({
      tabsByAgent: {},
      activeTabByAgent: {},
      diffsByAgent: {},

      clearAgent: (agentId) =>
        set((state) => ({
          tabsByAgent: { ...state.tabsByAgent, [agentId]: [] },
          activeTabByAgent: { ...state.activeTabByAgent, [agentId]: "" },
          diffsByAgent: { ...state.diffsByAgent, [agentId]: {} },
        })),

      clearProjectTabs: (scopeKey) =>
        set((state) => {
          const tabs = state.tabsByAgent[scopeKey] ?? [];
          const removedPaths = new Set(
            tabs
              // Every project root, not just the primary: rebinding the list
              // can remove or reorder any of them, so a tab left open on an
              // extra root would keep editing a directory this session is no
              // longer bound to.
              .filter(
                (tab) =>
                  (tab.source ?? "workspace") === "workspace" &&
                  isProjectRoot(tab.workspaceRoot),
              )
              .map((tab) => tab.path),
          );
          if (removedPaths.size === 0) return state;
          const nextTabs = tabs.filter((tab) => !removedPaths.has(tab.path));
          const activePath = state.activeTabByAgent[scopeKey] ?? "";
          const diffs = state.diffsByAgent[scopeKey] ?? {};
          return {
            tabsByAgent: {
              ...state.tabsByAgent,
              [scopeKey]: nextTabs,
            },
            activeTabByAgent: {
              ...state.activeTabByAgent,
              [scopeKey]: removedPaths.has(activePath)
                ? nextTabs[0]?.path ?? ""
                : activePath,
            },
            diffsByAgent: {
              ...state.diffsByAgent,
              [scopeKey]: Object.fromEntries(
                Object.entries(diffs).filter(
                  ([path]) => !removedPaths.has(path),
                ),
              ),
            },
          };
        }),

      migrateScope: (fromScopeKey, toScopeKey) =>
        set((state) => {
          if (fromScopeKey === toScopeKey) return state;
          const tabs = state.tabsByAgent[fromScopeKey];
          const activeTab = state.activeTabByAgent[fromScopeKey];
          const diffs = state.diffsByAgent[fromScopeKey];
          if (!tabs && !activeTab && !diffs) return state;
          return {
            tabsByAgent: {
              ...omitKey(state.tabsByAgent, fromScopeKey),
              [toScopeKey]: tabs ?? [],
            },
            activeTabByAgent: {
              ...omitKey(state.activeTabByAgent, fromScopeKey),
              [toScopeKey]: activeTab ?? "",
            },
            diffsByAgent: {
              ...omitKey(state.diffsByAgent, fromScopeKey),
              [toScopeKey]: diffs ?? {},
            },
          };
        }),

      removeScope: (scopeKey) =>
        set((state) => ({
          tabsByAgent: omitKey(state.tabsByAgent, scopeKey),
          activeTabByAgent: omitKey(state.activeTabByAgent, scopeKey),
          diffsByAgent: omitKey(state.diffsByAgent, scopeKey),
        })),

      openTab: (agentId, tab) =>
        set((state) => {
          const existing = state.tabsByAgent[agentId] ?? [];
          if (existing.some((t) => t.path === tab.path)) return state;
          return {
            tabsByAgent: {
              ...state.tabsByAgent,
              [agentId]: [...existing, tab],
            },
          };
        }),

      closeTab: (agentId, path) =>
        set((state) => {
          const tabs = state.tabsByAgent[agentId] ?? [];
          const nextTabs = tabs.filter((t) => t.path !== path);
          const agentDiffs = state.diffsByAgent[agentId] ?? {};
          const nextDiffs =
            path in agentDiffs ? omitKey(agentDiffs, path) : agentDiffs;
          return {
            tabsByAgent: { ...state.tabsByAgent, [agentId]: nextTabs },
            diffsByAgent: { ...state.diffsByAgent, [agentId]: nextDiffs },
          };
        }),

      setActiveTab: (agentId, path) =>
        set((state) => ({
          activeTabByAgent: {
            ...state.activeTabByAgent,
            [agentId]: path,
          },
        })),

      setTabContent: (agentId, path, content) =>
        set((state) => {
          const tabs = state.tabsByAgent[agentId] ?? [];
          if (!tabs.some((t) => t.path === path)) return state;
          return {
            tabsByAgent: {
              ...state.tabsByAgent,
              [agentId]: tabs.map((t) =>
                t.path === path ? { ...t, content } : t,
              ),
            },
          };
        }),

      setTabEtag: (agentId, path, etag) =>
        set((state) => {
          const tabs = state.tabsByAgent[agentId] ?? [];
          if (!tabs.some((t) => t.path === path)) return state;
          return {
            tabsByAgent: {
              ...state.tabsByAgent,
              [agentId]: tabs.map((t) =>
                t.path === path ? { ...t, etag } : t,
              ),
            },
          };
        }),

      setTabDirty: (agentId, path, dirty) =>
        set((state) => {
          const tabs = state.tabsByAgent[agentId] ?? [];
          if (!tabs.some((t) => t.path === path)) return state;
          return {
            tabsByAgent: {
              ...state.tabsByAgent,
              [agentId]: tabs.map((t) =>
                t.path === path ? { ...t, dirty } : t,
              ),
            },
          };
        }),

      setDiff: (agentId, path, diff) =>
        set((state) => ({
          diffsByAgent: {
            ...state.diffsByAgent,
            [agentId]: {
              ...(state.diffsByAgent[agentId] ?? {}),
              [path]: diff,
            },
          },
        })),

      removeDiff: (agentId, path) =>
        set((state) => {
          const agentDiffs = state.diffsByAgent[agentId] ?? {};
          if (!(path in agentDiffs)) return state;
          return {
            diffsByAgent: {
              ...state.diffsByAgent,
              [agentId]: omitKey(agentDiffs, path),
            },
          };
        }),

      updateDiffModified: (agentId, path, modified) =>
        set((state) => {
          const agentDiffs = state.diffsByAgent[agentId] ?? {};
          const existing = agentDiffs[path];
          if (!existing) return state;
          return {
            diffsByAgent: {
              ...state.diffsByAgent,
              [agentId]: {
                ...agentDiffs,
                [path]: { ...existing, modified },
              },
            },
          };
        }),

      updateDiffOriginal: (agentId, path, original) =>
        set((state) => {
          const agentDiffs = state.diffsByAgent[agentId] ?? {};
          const existing = agentDiffs[path];
          if (!existing) return state;
          return {
            diffsByAgent: {
              ...state.diffsByAgent,
              [agentId]: {
                ...agentDiffs,
                [path]: { ...existing, original },
              },
            },
          };
        }),

      resolveDiff: (agentId, path, content) =>
        set((state) => {
          const tabs = state.tabsByAgent[agentId] ?? [];
          const agentDiffs = state.diffsByAgent[agentId] ?? {};
          return {
            tabsByAgent: {
              ...state.tabsByAgent,
              [agentId]: tabs.map((tab) =>
                tab.path === path ? { ...tab, content, dirty: false } : tab,
              ),
            },
            diffsByAgent: {
              ...state.diffsByAgent,
              [agentId]: omitKey(agentDiffs, path),
            },
          };
        }),
    }),
    {
      name: "qwenpaw-split-files-workbench",
      storage: createJSONStorage(() => splitTabsStorage),
      // Persist only the path list (no content/dirty) and small `original`s.
      partialize: ((state: CodingTabsState) => ({
        tabsByAgent: Object.fromEntries(
          Object.entries(state.tabsByAgent).map(([agent, tabs]) => [
            agent,
            tabs.map((t) => ({
              path: t.path,
              displayPath: t.displayPath,
              content: "",
              dirty: false,
              source: t.source,
              workspaceRoot: t.workspaceRoot,
              artifactUrl: t.artifactUrl,
              previewKind: t.previewKind,
              readOnly: t.readOnly,
            })),
          ]),
        ),
        activeTabByAgent: state.activeTabByAgent,
        diffsByAgent: Object.fromEntries(
          Object.entries(state.diffsByAgent).map(([agent, diffs]) => [
            agent,
            Object.fromEntries(
              Object.entries(diffs)
                .filter(
                  ([, d]) => d.original.length <= ORIGINAL_DIFF_SIZE_LIMIT,
                )
                .map(([p, d]) => [p, { original: d.original, modified: null }]),
            ),
          ]),
        ),
      })) as unknown as (state: CodingTabsState) => CodingTabsState,
    },
  ),
);

// Stable empty references — selectors must return the SAME reference when
// the slice is missing, otherwise React will re-render forever.
const EMPTY_TABS: EditorTab[] = [];
const EMPTY_DIFFS: Record<string, PendingDiff> = {};

export function useTabsForScope(scopeKey: string): EditorTab[] {
  return useCodingTabsStore((s) => s.tabsByAgent[scopeKey] ?? EMPTY_TABS);
}

export function useActiveTabPathForScope(scopeKey: string): string {
  return useCodingTabsStore((s) => s.activeTabByAgent[scopeKey] ?? "");
}

export function useDiffsForScope(
  scopeKey: string,
): Record<string, PendingDiff> {
  return useCodingTabsStore((s) => s.diffsByAgent[scopeKey] ?? EMPTY_DIFFS);
}