@agimon-ai/po-file-edit 0.0.0-alpha.21 → 0.0.0-alpha.211

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,36 @@
1
- import { defineChannelFile, defineNativePlugin, defineSessionStore } from "@agimon-ai/po-core/native";
1
+ import { createApiClient, defineChannelFile, defineFileLinks, defineFill, defineNativePlugin, defineSessionStore, encodeBase64, nativeApiTransport, sessionApiAddress, t, useLocale, useT } from "@agimon-ai/po-core/native";
2
+ import { View } from "react-native-unistyles/components/native/View";
3
+ import { Text } from "react-native-unistyles/components/native/Text";
4
+ import { ScrollView } from "react-native-unistyles/components/native/ScrollView";
5
+ import { Button, CloseIcon, CodeBlock, CopyButton, DownloadIcon, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, EmptyState, KebabIcon, Label, LockIcon, Markdown, SegmentedControl, Sheet, SheetBody, SheetContent, SheetHeader, SheetTitle, Textarea, fontOf } from "@agimon-ai/po-native-components";
6
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
7
+ import { StyleSheet } from "react-native-unistyles";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
9
  //#region src/types/webFiles.ts
3
10
  /** The frame type the hub publishes and the web plugin claims; declared in the poWeb block too. */
4
11
  const filesChannelType = "file_edits";
5
12
  //#endregion
6
13
  //#region src/extensions/workspaces/sessions/(frontend)/_lib/filesModel.ts
7
- function isRecord(value) {
14
+ function isRecord$1(value) {
8
15
  return typeof value === "object" && value !== null && !Array.isArray(value);
9
16
  }
10
17
  function isItem(value) {
11
- return isRecord(value) && typeof value.path === "string" && typeof value.relPath === "string" && typeof value.tool === "string" && typeof value.at === "number" && typeof value.count === "number";
18
+ return isRecord$1(value) && typeof value.path === "string" && typeof value.relPath === "string" && typeof value.tool === "string" && typeof value.at === "number" && typeof value.count === "number";
12
19
  }
13
20
  /** The shared wire gate for browser and native stores. */
14
21
  function parseFilesPayload(input) {
15
- if (!isRecord(input) || !Array.isArray(input.items)) return null;
22
+ if (!isRecord$1(input) || !Array.isArray(input.items)) return null;
16
23
  return { items: input.items.filter(isItem) };
17
24
  }
18
- /** The plugin's session data channel: 'file_edits' payloads into the store. */
19
- const filesChannel = defineSessionStore({
25
+ const files = defineSessionStore({
20
26
  items: [],
21
27
  detail: {},
22
28
  loading: [],
23
29
  errors: {},
24
30
  comments: []
25
- }).channel({
31
+ });
32
+ /** The plugin's session data channel: 'file_edits' payloads into the store. */
33
+ const filesChannel = files.channel({
26
34
  channel: filesChannelType,
27
35
  parse: parseFilesPayload,
28
36
  reduce: (current, { items }) => ({
@@ -30,20 +38,1430 @@ const filesChannel = defineSessionStore({
30
38
  items
31
39
  })
32
40
  });
41
+ function markLoading(sessionId, filePath) {
42
+ files.update(sessionId, (current) => current.loading.includes(filePath) ? current : {
43
+ ...current,
44
+ loading: [...current.loading, filePath],
45
+ errors: withoutKey(current.errors, filePath)
46
+ });
47
+ }
48
+ function storeDetail(sessionId, detail) {
49
+ files.update(sessionId, (current) => ({
50
+ ...current,
51
+ detail: {
52
+ ...current.detail,
53
+ [detail.path]: detail
54
+ },
55
+ loading: current.loading.filter((path) => path !== detail.path),
56
+ errors: withoutKey(current.errors, detail.path)
57
+ }));
58
+ }
59
+ function storeError(sessionId, filePath, message) {
60
+ files.update(sessionId, (current) => ({
61
+ ...current,
62
+ loading: current.loading.filter((path) => path !== filePath),
63
+ errors: {
64
+ ...current.errors,
65
+ [filePath]: message
66
+ }
67
+ }));
68
+ }
69
+ function addComment(sessionId, comment) {
70
+ files.update(sessionId, (current) => ({
71
+ ...current,
72
+ comments: [...current.comments, comment]
73
+ }));
74
+ }
75
+ function removeComment(sessionId, id) {
76
+ files.update(sessionId, (current) => ({
77
+ ...current,
78
+ comments: current.comments.filter((comment) => comment.id !== id)
79
+ }));
80
+ }
81
+ function clearComments(sessionId, filePath) {
82
+ files.update(sessionId, (current) => ({
83
+ ...current,
84
+ comments: current.comments.filter((comment) => comment.path !== filePath)
85
+ }));
86
+ }
87
+ function withoutKey(source, key) {
88
+ return Object.fromEntries(Object.entries(source).filter(([entry]) => entry !== key));
89
+ }
33
90
  //#endregion
34
91
  //#region src/extensions/workspaces/sessions/(frontend)/channel/file-edits.native.ts
35
92
  var file_edits_native_default = defineChannelFile(filesChannel);
36
93
  //#endregion
94
+ //#region src/extensions/workspaces/sessions/(frontend)/_lib/fileIdentity.ts
95
+ /** A short, stable fingerprint of a string; enough to separate two paths in an id. */
96
+ function fingerprint(value) {
97
+ let hash = 2166136261;
98
+ for (let index = 0; index < value.length; index += 1) {
99
+ hash ^= value.charCodeAt(index);
100
+ hash = Math.imul(hash, 16777619);
101
+ }
102
+ return (hash >>> 0).toString(36);
103
+ }
104
+ /** The transient tab id for one file; stable, so reopening focuses rather than duplicates. */
105
+ function fileTabId(filePath) {
106
+ const slug = filePath.replaceAll(/[^a-zA-Z0-9]+/gu, "-").replace(/^-|-$/gu, "");
107
+ return `files-file-${fingerprint(filePath)}-${slug.slice(-40)}`;
108
+ }
109
+ const api = createApiClient({
110
+ detail: {
111
+ method: "GET",
112
+ path: "/detail",
113
+ query: ["path"],
114
+ response: void 0
115
+ },
116
+ preview: {
117
+ method: "GET",
118
+ path: "/preview",
119
+ query: ["path"],
120
+ response: void 0
121
+ },
122
+ save: {
123
+ method: "PUT",
124
+ path: "/content",
125
+ response: void 0
126
+ },
127
+ /** The same path as `save`; the method is the whole of the difference. */
128
+ remove: {
129
+ method: "DELETE",
130
+ path: "/content",
131
+ query: ["path"]
132
+ },
133
+ /**
134
+ * The host's own bytes route, not this package's.
135
+ *
136
+ * `host: true` hangs it off the session root rather than under `/plugins`,
137
+ * which is how the cockpit already serves it. Declaring it here is the first
138
+ * time anything records that this package's previews depend on it.
139
+ */
140
+ file: {
141
+ method: "GET",
142
+ path: "/file",
143
+ raw: true,
144
+ query: ["path"],
145
+ host: true
146
+ }
147
+ }, {
148
+ scopes: ["session"],
149
+ basePath: "file-edits",
150
+ transport: nativeApiTransport,
151
+ sessionAddress: sessionApiAddress
152
+ });
153
+ //#endregion
154
+ //#region src/types/fileEditsApi.ts
155
+ /** Query parameter naming the file a request is about. */
156
+ const PATH_QUERY_PARAM = "path";
157
+ //#endregion
158
+ //#region src/extensions/workspaces/sessions/(frontend)/_lib/filesApi.native.ts
159
+ /**
160
+ * The page's half of this package's session API: one file's history, the
161
+ * manual save, and the deletion.
162
+ *
163
+ * These are adapters now, not a transport. The generated client owns the URL
164
+ * and the sealed transport with it, so nothing here spells a route or reaches
165
+ * for `fetch`. What stays is this package's own vocabulary: which refusals the
166
+ * reader is shown, and the stale-save contract the editor depends on.
167
+ *
168
+ * Sealing still matters and still happens, one layer down. What travels here is
169
+ * file contents in both directions, which is the worst thing in the cockpit to
170
+ * hand a tunnel's relay in the clear.
171
+ */
172
+ function isRecord(value) {
173
+ return typeof value === "object" && value !== null && !Array.isArray(value);
174
+ }
175
+ /** The message a reader is shown: the route's own words, or why there were none. */
176
+ function messageOf(result) {
177
+ if (result.status === 0) return t("fileEdit.error.unreachable", "The session is unreachable.");
178
+ return result.error === "" ? t("fileEdit.error.status", "The session answered {status}.", { status: result.status }) : result.error;
179
+ }
180
+ async function fetchFileDetail(sessionId, filePath) {
181
+ const result = await api.session(sessionId).detail({ query: { [PATH_QUERY_PARAM]: filePath } });
182
+ if (!result.ok) return {
183
+ ok: false,
184
+ error: messageOf(result)
185
+ };
186
+ if (!isRecord(result.data)) return {
187
+ ok: false,
188
+ error: t("fileEdit.error.noDetail", "The session answered with no detail.")
189
+ };
190
+ return {
191
+ ok: true,
192
+ detail: result.data
193
+ };
194
+ }
195
+ /** One file the session never changed, read only; the route bounds it to the working directory. */
196
+ async function fetchFilePreview(sessionId, filePath) {
197
+ const result = await api.session(sessionId).preview({ query: { [PATH_QUERY_PARAM]: filePath } });
198
+ if (!result.ok) return {
199
+ ok: false,
200
+ error: messageOf(result),
201
+ status: result.status
202
+ };
203
+ if (!isRecord(result.data)) return {
204
+ ok: false,
205
+ error: t("fileEdit.error.noFile", "The session answered with no file.")
206
+ };
207
+ return {
208
+ ok: true,
209
+ preview: result.data
210
+ };
211
+ }
212
+ async function saveFileContent(sessionId, filePath, expectedHash, content) {
213
+ const result = await api.session(sessionId).save({ body: {
214
+ path: filePath,
215
+ expectedHash,
216
+ content
217
+ } });
218
+ if (result.status === 409) {
219
+ const data = result.ok ? void 0 : result.data;
220
+ const hash = isRecord(data) && typeof data.hash === "string" ? data.hash : void 0;
221
+ return {
222
+ ok: false,
223
+ stale: true,
224
+ error: result.ok ? t("fileEdit.error.changed", "The file changed since it was opened.") : messageOf(result),
225
+ ...hash === void 0 ? {} : { hash }
226
+ };
227
+ }
228
+ if (!result.ok) return {
229
+ ok: false,
230
+ stale: false,
231
+ error: messageOf(result)
232
+ };
233
+ return {
234
+ ok: true,
235
+ hash: isRecord(result.data) && typeof result.data.hash === "string" ? result.data.hash : ""
236
+ };
237
+ }
238
+ /**
239
+ * Removes the file from disk.
240
+ *
241
+ * The route takes only a path, with no hash to prove the reader saw what is
242
+ * there now: a deletion discards the file whatever it holds, so a staleness
243
+ * check would guard nothing. The confirmation in front of it is the guard.
244
+ */
245
+ async function deleteFile(sessionId, filePath) {
246
+ const result = await api.session(sessionId).remove({ query: { [PATH_QUERY_PARAM]: filePath } });
247
+ return result.ok ? { ok: true } : {
248
+ ok: false,
249
+ error: messageOf(result)
250
+ };
251
+ }
252
+ /** Binds a save to this package's guarded sealed route and one file version. */
253
+ async function prepareFileSave(sessionId, path, signal) {
254
+ const load = async (headers, signal) => {
255
+ if (signal.aborted) throw new Error(t("fileEdit.error.cancelled", "Download cancelled."));
256
+ const result = await api.session(sessionId).file({
257
+ query: { path },
258
+ headers,
259
+ signal
260
+ });
261
+ if (!result.ok && result.status !== 416) throw new Error(result.error || t("fileEdit.error.read", "File could not be read."));
262
+ if (!result.response) throw new Error(t("fileEdit.error.read", "File could not be read."));
263
+ return result.response;
264
+ };
265
+ const probe = await load({ Range: "bytes=0-0" }, signal);
266
+ if (signal.aborted) throw new Error(t("fileEdit.error.cancelled", "Download cancelled."));
267
+ const range = /^bytes 0-0\/(\d+)$/u.exec(probe.headers.get("content-range") ?? "");
268
+ const empty = probe.status === 416 && probe.headers.get("content-range") === "bytes */0" || probe.status === 200 && probe.headers.get("content-length") === "0";
269
+ if (!empty && (probe.status !== 206 || !range)) throw new Error(t("fileEdit.error.bounded", "The file does not support bounded downloads."));
270
+ const size = empty ? 0 : Number(range[1]);
271
+ if (!Number.isSafeInteger(size) || size < 0) throw new Error(t("fileEdit.error.size", "Invalid file size."));
272
+ if ((await probe.arrayBuffer()).byteLength !== (empty ? 0 : 1)) throw new Error(t("fileEdit.error.response", "Invalid file response."));
273
+ const version = probe.headers.get("etag");
274
+ if (!version) throw new Error(t("fileEdit.error.validator", "The file has no version validator."));
275
+ return {
276
+ name: path.split(/[\\/]/u).at(-1) ?? "",
277
+ mimeType: probe.headers.get("content-type")?.split(";")[0]?.trim() || "application/octet-stream",
278
+ size,
279
+ signal,
280
+ read: async (offset, count, signal) => {
281
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(count) || offset < 0 || count < 1 || count > 1048576 || offset + count > size) throw new Error(t("fileEdit.error.range", "Invalid download range."));
282
+ const end = offset + count - 1;
283
+ const response = await load({
284
+ Range: `bytes=${offset}-${end}`,
285
+ "If-Match": version
286
+ }, signal);
287
+ if (signal.aborted) throw new Error(t("fileEdit.error.cancelled", "Download cancelled."));
288
+ if (response.status !== 206 || response.headers.get("etag") !== version || response.headers.get("content-range") !== `bytes ${offset}-${end}/${size}`) throw new Error(t("fileEdit.error.rangeChanged", "The file changed or its range response is invalid."));
289
+ const bytes = new Uint8Array(await response.arrayBuffer());
290
+ if (signal.aborted) throw new Error(t("fileEdit.error.cancelled", "Download cancelled."));
291
+ if (bytes.byteLength !== count) throw new Error(t("fileEdit.error.incomplete", "The file response is incomplete."));
292
+ return bytes;
293
+ }
294
+ };
295
+ }
296
+ //#endregion
297
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/FileDiff.native.tsx
298
+ const ROW_STEP = 200;
299
+ /** Mount only the disclosed prefix; source line numbers and single-line comment anchors stay intact. */
300
+ function FileDiff({ hunks, comment, initialRows = ROW_STEP, label = "file-diff" }) {
301
+ const t = useT();
302
+ const locale = useLocale();
303
+ const [limit, setLimit] = useState(initialRows);
304
+ const total = useMemo(() => hunks.reduce((count, hunk) => count + hunk.rows.length, 0), [hunks]);
305
+ const visible = useMemo(() => {
306
+ const result = [];
307
+ let remaining = limit;
308
+ for (const hunk of hunks) {
309
+ if (remaining <= 0) break;
310
+ result.push({
311
+ ...hunk,
312
+ rows: hunk.rows.slice(0, remaining)
313
+ });
314
+ remaining -= hunk.rows.length;
315
+ }
316
+ return result;
317
+ }, [hunks, limit]);
318
+ return /* @__PURE__ */ jsxs(View, {
319
+ style: styles$3.diff,
320
+ testID: label,
321
+ children: [visible.map((hunk, index) => {
322
+ return hunk.rows.length ? /* @__PURE__ */ jsxs(View, { children: [/* @__PURE__ */ jsx(Text, {
323
+ style: styles$3.meta,
324
+ children: t("fileEdit.ui.lineValue1", "line {value1}", { value1: hunk.start })
325
+ }), hunk.rows.map((row, position) => /* @__PURE__ */ jsx(Button, {
326
+ variant: "ghost",
327
+ accessibilityLabel: t("fileEdit.ui.commentOnValue1LineValue2", "comment on {value1} line {value2}", {
328
+ value1: row.marker === "-" ? t("fileEdit.ui.removed", "removed") : t("fileEdit.ui.new", "new"),
329
+ value2: row.line
330
+ }),
331
+ onPress: () => comment({
332
+ snippet: row.content,
333
+ side: row.marker === "-" ? "old" : "new",
334
+ startLine: row.line,
335
+ endLine: row.line
336
+ }),
337
+ children: /* @__PURE__ */ jsxs(Text, {
338
+ selectable: true,
339
+ style: row.marker === "+" ? styles$3.added : row.marker === "-" ? styles$3.removed : styles$3.code,
340
+ children: [
341
+ row.marker,
342
+ " ",
343
+ row.line,
344
+ " ",
345
+ row.content
346
+ ]
347
+ })
348
+ }, `${row.line}-${position}`))] }, `${hunk.start}-${index}`) : null;
349
+ }), total ? /* @__PURE__ */ jsxs(View, {
350
+ style: styles$3.diff,
351
+ children: [/* @__PURE__ */ jsx(Text, {
352
+ accessibilityLiveRegion: "polite",
353
+ style: styles$3.meta,
354
+ children: t("fileEdit.ui.showingValue1OfValue2Rows", "Showing {value1} of {value2} rows", {
355
+ value1: Math.min(limit, total).toLocaleString(locale),
356
+ value2: total.toLocaleString(locale)
357
+ })
358
+ }), limit < total ? /* @__PURE__ */ jsx(Button, {
359
+ variant: "outline",
360
+ onPress: () => setLimit((value) => Math.min(total, value + ROW_STEP)),
361
+ children: t("fileEdit.ui.showValue1MoreRows", "Show {value1} more rows", { value1: Math.min(ROW_STEP, total - limit) })
362
+ }) : null]
363
+ }) : null]
364
+ });
365
+ }
366
+ const styles$3 = StyleSheet.create((theme) => ({
367
+ diff: {
368
+ gap: theme.spacing(2),
369
+ uni__dependencies: [0]
370
+ },
371
+ code: {
372
+ fontFamily: fontOf(theme.fontFamily.mono),
373
+ fontSize: theme.fontSize.sm,
374
+ color: theme.colors.text,
375
+ uni__dependencies: [0]
376
+ },
377
+ added: {
378
+ fontFamily: fontOf(theme.fontFamily.mono),
379
+ fontSize: theme.fontSize.sm,
380
+ color: theme.colors.green,
381
+ uni__dependencies: [0]
382
+ },
383
+ removed: {
384
+ fontFamily: fontOf(theme.fontFamily.mono),
385
+ fontSize: theme.fontSize.sm,
386
+ color: theme.colors.red,
387
+ uni__dependencies: [0]
388
+ },
389
+ meta: {
390
+ fontSize: theme.fontSize.sm,
391
+ color: theme.colors.dim,
392
+ uni__dependencies: [0]
393
+ }
394
+ }));
395
+ //#endregion
396
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/FilePreview.native.tsx
397
+ const MEDIA = /\.(?:png|jpe?g|gif|webp|bmp|svg|ico|mp3|wav|m4a|ogg|mp4|mov|webm|pdf)$/iu;
398
+ const MAX_MEDIA_BYTES = 5242880;
399
+ const URL_OR_ANCHOR = /^(?:[a-z][a-z\d+.-]*:|\/\/|#|\?)/iu;
400
+ function isMediaPath(path) {
401
+ return MEDIA.test(path);
402
+ }
403
+ /** One media file's bytes through the package's guarded file route, as base64 with its content type. */
404
+ async function fetchMedia(sessionId, path, signal) {
405
+ const result = await api.session(sessionId).file({
406
+ query: { path },
407
+ signal
408
+ });
409
+ if (!result.ok) throw new Error(result.error || t("fileEdit.ui.mediaCouldNotBeLoadedValue1", "Media could not be loaded ({value1}).", { value1: result.status }));
410
+ if (Number(result.response.headers.get("content-length")) > MAX_MEDIA_BYTES) throw new Error(t("fileEdit.ui.thisMediaIsTooLargeToPreview", "This media is too large to preview."));
411
+ const bytes = new Uint8Array(await result.response.arrayBuffer());
412
+ if (bytes.length > MAX_MEDIA_BYTES) throw new Error(t("fileEdit.ui.thisMediaIsTooLargeToPreview", "This media is too large to preview."));
413
+ const type = result.response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() ?? "";
414
+ if (!/^(?:image\/[a-z0-9.+-]+|audio\/[a-z0-9.+-]+|video\/[a-z0-9.+-]+|application\/pdf)$/u.test(type)) throw new Error(t("fileEdit.ui.thisMediaTypeCannotBePreviewed", "This media type cannot be previewed."));
415
+ return {
416
+ data: encodeBase64(bytes),
417
+ type
418
+ };
419
+ }
420
+ /** A Markdown image path, read against the document's own folder as GitHub reads it. */
421
+ function documentRelative(documentPath, source) {
422
+ if (source.startsWith("/")) return source;
423
+ const parts = documentPath.split("/").slice(0, -1);
424
+ for (const segment of source.split("/")) if (segment === "..") parts.pop();
425
+ else if (segment !== "." && segment !== "") parts.push(segment);
426
+ return parts.join("/");
427
+ }
428
+ function SessionMedia({ sessionId, path, renderMediaPreview }) {
429
+ const t = useT();
430
+ const [loaded, setLoaded] = useState();
431
+ useEffect(() => {
432
+ if (sessionId === null) return;
433
+ const controller = new AbortController();
434
+ (async () => {
435
+ const { data, type } = await fetchMedia(sessionId, path, controller.signal);
436
+ if (!controller.signal.aborted) setLoaded({
437
+ sessionId,
438
+ path,
439
+ type,
440
+ data
441
+ });
442
+ })().catch((failure) => {
443
+ if (!controller.signal.aborted) setLoaded({
444
+ sessionId,
445
+ path,
446
+ error: failure instanceof Error ? failure.message : String(failure)
447
+ });
448
+ });
449
+ return () => controller.abort();
450
+ }, [sessionId, path]);
451
+ const current = loaded?.sessionId === sessionId && loaded.path === path ? loaded : void 0;
452
+ if (!current?.data) return /* @__PURE__ */ jsx(Text, {
453
+ accessibilityRole: current?.error ? "alert" : "text",
454
+ style: current?.error ? styles$2.error : styles$2.meta,
455
+ children: current?.error ?? t("fileEdit.ui.loadingMedia", "Loading media...")
456
+ });
457
+ return renderMediaPreview ? /* @__PURE__ */ jsx(Fragment, { children: renderMediaPreview({
458
+ key: `file-media-${sessionId}-${path}`,
459
+ data: current.data,
460
+ mimeType: current.type,
461
+ title: path,
462
+ path
463
+ }) }) : /* @__PURE__ */ jsx(Text, {
464
+ style: styles$2.error,
465
+ children: t("fileEdit.ui.thisHostCannotDisplayThisMediaPreview", "This host cannot display this media preview.")
466
+ });
467
+ }
468
+ /** One document's requested images, invalidated only by their own file revisions. */
469
+ function markdownImages(sessionId, documentPath) {
470
+ const loaded = /* @__PURE__ */ new Map();
471
+ const stamp = (imagePath) => {
472
+ const session = files.select(files.store.state, sessionId);
473
+ const item = session.items.find((entry) => entry.path === imagePath || entry.relPath === imagePath);
474
+ return JSON.stringify([
475
+ item?.count,
476
+ item?.at,
477
+ session.detail[imagePath]?.working.hash
478
+ ]);
479
+ };
480
+ const load = async (source) => {
481
+ if (sessionId === null || URL_OR_ANCHOR.test(source)) throw new Error(t("fileEdit.ui.thisImageCannotBeLoaded", "This image cannot be loaded."));
482
+ const imagePath = documentRelative(documentPath, source);
483
+ let image = loaded.get(imagePath);
484
+ if (!image) {
485
+ image = { stamp: stamp(imagePath) };
486
+ loaded.set(imagePath, image);
487
+ }
488
+ const cached = image;
489
+ cached.asset ??= fetchMedia(sessionId, imagePath, new AbortController().signal).then((media) => {
490
+ if (!media.type.startsWith("image/")) throw new Error(t("fileEdit.ui.thisFileIsNotAnImage", "This file is not an image."));
491
+ return {
492
+ url: `data:${media.type};base64,${media.data}`,
493
+ dispose: () => {}
494
+ };
495
+ }).catch((error) => {
496
+ cached.asset = void 0;
497
+ throw error;
498
+ });
499
+ return cached.asset;
500
+ };
501
+ let snapshot = load;
502
+ const subscribe = (listener) => {
503
+ const subscription = files.store.subscribe(() => {
504
+ let changed = false;
505
+ for (const [imagePath, image] of loaded) {
506
+ const next = stamp(imagePath);
507
+ if (next === image.stamp) continue;
508
+ loaded.set(imagePath, { stamp: next });
509
+ changed = true;
510
+ }
511
+ if (changed) {
512
+ snapshot = (source) => load(source);
513
+ listener();
514
+ }
515
+ });
516
+ return () => subscription.unsubscribe();
517
+ };
518
+ return {
519
+ subscribe,
520
+ snapshot: () => snapshot
521
+ };
522
+ }
523
+ function MarkdownPreview({ path, working, sessionId, fileTabFor, openTransientTab }) {
524
+ const images = useMemo(() => markdownImages(sessionId, path), [sessionId, path]);
525
+ const loadImage = useSyncExternalStore(images.subscribe, images.snapshot);
526
+ return /* @__PURE__ */ jsx(Markdown, {
527
+ text: working.content,
528
+ onFileLink: (file) => {
529
+ const tab = fileTabFor(file);
530
+ return tab ? () => openTransientTab(tab) : void 0;
531
+ },
532
+ loadImage
533
+ });
534
+ }
535
+ /** Rendering is separate from reading: only the guarded package API supplies file content or bytes. */
536
+ function FilePreview({ path, working, ...props }) {
537
+ const t = useT();
538
+ if (MEDIA.test(path)) return /* @__PURE__ */ jsx(SessionMedia, {
539
+ sessionId: props.sessionId,
540
+ path,
541
+ renderMediaPreview: props.renderMediaPreview
542
+ });
543
+ if (working.unavailable) return /* @__PURE__ */ jsx(Text, {
544
+ style: styles$2.meta,
545
+ children: working.reason ?? t("fileEdit.ui.thisFileCannotBeShown", "this file cannot be shown")
546
+ });
547
+ if (/\.html?$/iu.test(path)) return props.renderFilePreview ? /* @__PURE__ */ jsx(View, {
548
+ style: styles$2.html,
549
+ children: props.renderFilePreview({
550
+ key: `file-html-${props.sessionId}-${path}`,
551
+ html: working.content,
552
+ title: path
553
+ })
554
+ }) : /* @__PURE__ */ jsx(Text, {
555
+ style: styles$2.error,
556
+ children: t("fileEdit.ui.thisHostCannotDisplayHTMLPreviews", "This host cannot display HTML previews.")
557
+ });
558
+ if (/\.(?:md|markdown)$/iu.test(path)) return /* @__PURE__ */ jsx(MarkdownPreview, {
559
+ ...props,
560
+ path,
561
+ working
562
+ }, working.hash);
563
+ return /* @__PURE__ */ jsx(CodeBlock, {
564
+ text: working.content,
565
+ language: path.split(".").at(-1)
566
+ });
567
+ }
568
+ const styles$2 = StyleSheet.create((theme) => ({
569
+ html: {
570
+ minHeight: theme.spacing(90),
571
+ uni__dependencies: [0]
572
+ },
573
+ meta: {
574
+ fontSize: theme.fontSize.sm,
575
+ color: theme.colors.dim,
576
+ uni__dependencies: [0]
577
+ },
578
+ error: {
579
+ fontSize: theme.fontSize.sm,
580
+ color: theme.colors.red,
581
+ uni__dependencies: [0]
582
+ }
583
+ }));
584
+ //#endregion
585
+ //#region src/extensions/workspaces/sessions/(frontend)/_components/FilePanel.native.tsx
586
+ function ReviewSheet({ selection, close, submit }) {
587
+ const t = useT();
588
+ const [body, setBody] = useState("");
589
+ const [snippet, setSnippet] = useState(selection.snippet);
590
+ return /* @__PURE__ */ jsx(Sheet, {
591
+ open: true,
592
+ onOpenChange: (open) => {
593
+ if (!open) close();
594
+ },
595
+ children: /* @__PURE__ */ jsxs(SheetContent, { children: [/* @__PURE__ */ jsx(SheetHeader, { children: /* @__PURE__ */ jsx(SheetTitle, { children: t("fileEdit.ui.reviewComment", "review comment") }) }), /* @__PURE__ */ jsxs(SheetBody, { children: [
596
+ /* @__PURE__ */ jsx(Label, { children: t("fileEdit.ui.quotation", "quotation") }),
597
+ /* @__PURE__ */ jsx(Textarea, {
598
+ accessibilityLabel: t("fileEdit.ui.quotation", "quotation"),
599
+ value: snippet,
600
+ onChangeText: setSnippet,
601
+ rows: 3
602
+ }),
603
+ /* @__PURE__ */ jsx(Label, { children: t("fileEdit.ui.comment", "comment") }),
604
+ /* @__PURE__ */ jsx(Textarea, {
605
+ accessibilityLabel: t("fileEdit.ui.comment", "comment"),
606
+ value: body,
607
+ onChangeText: setBody,
608
+ rows: 3
609
+ }),
610
+ /* @__PURE__ */ jsxs(View, {
611
+ style: styles$1.actions,
612
+ children: [/* @__PURE__ */ jsx(Button, {
613
+ variant: "ghost",
614
+ onPress: close,
615
+ children: t("fileEdit.ui.cancel", "cancel")
616
+ }), /* @__PURE__ */ jsx(Button, {
617
+ variant: "primary",
618
+ disabled: !body.trim(),
619
+ onPress: () => submit(body.trim(), snippet),
620
+ children: t("fileEdit.ui.addComment", "add comment")
621
+ })]
622
+ })
623
+ ] })] })
624
+ });
625
+ }
626
+ /** Cache the selected file snapshot, not the session record or a freshly filtered comments array. */
627
+ function fileSnapshot(sessionId, filePath) {
628
+ let previous;
629
+ return () => {
630
+ const session = files.select(files.store.state, sessionId);
631
+ const next = {
632
+ detail: session.detail[filePath],
633
+ loading: session.loading.includes(filePath),
634
+ error: session.errors[filePath],
635
+ revision: session.items.find((item) => item.path === filePath)?.count ?? 0,
636
+ comments: session.comments.filter((comment) => comment.path === filePath)
637
+ };
638
+ if (previous && previous.detail === next.detail && previous.loading === next.loading && previous.error === next.error && previous.revision === next.revision && previous.comments.length === next.comments.length && previous.comments.every((comment, index) => comment === next.comments[index])) return previous;
639
+ previous = next;
640
+ return next;
641
+ };
642
+ }
643
+ /** File writes retain the existing containment and stale-hash guards; deletion always asks first. */
644
+ function FilePanel({ filePath, relPath, ...props }) {
645
+ const t = useT();
646
+ const { sessionId, sendSessionFrame, closeTransientTab } = props;
647
+ const subscribe = useCallback((listener) => {
648
+ const subscription = files.store.subscribe(listener);
649
+ return () => subscription.unsubscribe();
650
+ }, []);
651
+ const snapshot = useMemo(() => fileSnapshot(sessionId, filePath), [sessionId, filePath]);
652
+ const { detail, loading, error, revision, comments } = useSyncExternalStore(subscribe, snapshot);
653
+ const working = detail?.working;
654
+ const [view, setView] = useState("preview");
655
+ const [source, setSource] = useState();
656
+ const [expanded, setExpanded] = useState();
657
+ const [selection, setSelection] = useState();
658
+ const [draft, setDraft] = useState();
659
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
660
+ const [busy, setBusy] = useState(false);
661
+ const [note, setNote] = useState();
662
+ const [failure, setFailure] = useState();
663
+ const [reviewError, setReviewError] = useState();
664
+ const [attempt, setAttempt] = useState(0);
665
+ const outside = relPath === ".." || relPath.startsWith("../") || relPath.startsWith("/") || relPath.startsWith("..\\") || /^[a-z]:[\\/]/iu.test(relPath);
666
+ const writable = sessionId !== null && !outside && working !== void 0 && !working.unavailable;
667
+ useEffect(() => {
668
+ if (sessionId === null) return;
669
+ let cancelled = false;
670
+ markLoading(sessionId, filePath);
671
+ fetchFileDetail(sessionId, filePath).then((result) => {
672
+ if (cancelled) return;
673
+ if (result.ok) {
674
+ storeDetail(sessionId, result.detail);
675
+ setSource(void 0);
676
+ setNote(void 0);
677
+ setFailure(void 0);
678
+ } else storeError(sessionId, filePath, result.error);
679
+ }).catch((failure) => {
680
+ if (!cancelled) storeError(sessionId, filePath, failure instanceof Error ? failure.message : String(failure));
681
+ });
682
+ return () => {
683
+ cancelled = true;
684
+ };
685
+ }, [
686
+ sessionId,
687
+ filePath,
688
+ revision,
689
+ attempt
690
+ ]);
691
+ const failed = (title, retry) => (error) => {
692
+ setNote(void 0);
693
+ setFailure({
694
+ title,
695
+ message: error instanceof Error ? error.message : String(error),
696
+ retry
697
+ });
698
+ };
699
+ const downloadController = useRef(void 0);
700
+ useEffect(() => () => downloadController.current?.abort(), [sessionId, relPath]);
701
+ const download = async () => {
702
+ if (sessionId === null || outside || busy || !props.nativeSaveFile) return;
703
+ const controller = new AbortController();
704
+ downloadController.current = controller;
705
+ setBusy(true);
706
+ setFailure(void 0);
707
+ try {
708
+ await props.nativeSaveFile(await prepareFileSave(sessionId, relPath, controller.signal));
709
+ if (!controller.signal.aborted) setNote("saved");
710
+ } catch (error) {
711
+ if (!controller.signal.aborted) failed(t("fileEdit.ui.downloadFailed", "Couldn't download this file"), () => void download())(error);
712
+ } finally {
713
+ setBusy(false);
714
+ }
715
+ };
716
+ const save = async () => {
717
+ if (!writable || sessionId === null || !working || source === void 0 || busy) return;
718
+ setBusy(true);
719
+ setFailure(void 0);
720
+ const saveFailed = failed(t("fileEdit.ui.saveFailed", "Couldn't save this file"), () => void save());
721
+ try {
722
+ const result = await saveFileContent(sessionId, filePath, working.hash, source);
723
+ if (!result.ok) {
724
+ saveFailed(result.error);
725
+ return;
726
+ }
727
+ setNote("saved");
728
+ const refreshed = await fetchFileDetail(sessionId, filePath);
729
+ if (refreshed.ok) {
730
+ storeDetail(sessionId, refreshed.detail);
731
+ setSource(void 0);
732
+ } else storeError(sessionId, filePath, refreshed.error);
733
+ } catch (failure) {
734
+ saveFailed(failure);
735
+ } finally {
736
+ setBusy(false);
737
+ }
738
+ };
739
+ const remove = async () => {
740
+ if (!writable || sessionId === null || busy) return;
741
+ setBusy(true);
742
+ setFailure(void 0);
743
+ const deleteFailed = failed(t("fileEdit.ui.deleteFailed", "Couldn't delete this file"), () => void remove());
744
+ try {
745
+ const result = await deleteFile(sessionId, filePath);
746
+ if (!result.ok) {
747
+ deleteFailed(result.error);
748
+ setConfirmingDelete(false);
749
+ } else {
750
+ setConfirmingDelete(false);
751
+ closeTransientTab(fileTabId(filePath));
752
+ }
753
+ } catch (failure) {
754
+ deleteFailed(failure);
755
+ setConfirmingDelete(false);
756
+ } finally {
757
+ setBusy(false);
758
+ }
759
+ };
760
+ const sendReview = () => {
761
+ if (sessionId === null || comments.length === 0) return;
762
+ const message = `I left ${comments.length} review ${comments.length === 1 ? "comment" : "comments"} on files you changed. Please address them.\n\n` + comments.map((comment) => {
763
+ return `### ${comment.startLine === void 0 ? comment.relPath : comment.side === "old" ? `${comment.relPath} (removed line ${comment.startLine})` : `${comment.relPath}:${comment.startLine}`}\n\n${comment.snippet.split("\n").slice(0, 20).join("\n").slice(0, 2e3).split("\n").map((line) => `> ${line}`).join("\n")}\n\n${comment.body.trim()}`;
764
+ }).join("\n\n");
765
+ try {
766
+ sendSessionFrame(sessionId, {
767
+ type: "follow_up",
768
+ message
769
+ });
770
+ clearComments(sessionId, filePath);
771
+ setReviewError(void 0);
772
+ } catch (failure) {
773
+ setReviewError(failure instanceof Error ? failure.message : String(failure));
774
+ }
775
+ };
776
+ return /* @__PURE__ */ jsxs(ScrollView, {
777
+ testID: "files-file-panel",
778
+ contentContainerStyle: styles$1.panel,
779
+ children: [
780
+ /* @__PURE__ */ jsxs(View, {
781
+ style: styles$1.header,
782
+ children: [/* @__PURE__ */ jsx(Text, {
783
+ selectable: true,
784
+ style: styles$1.path,
785
+ children: relPath
786
+ }), /* @__PURE__ */ jsxs(DropdownMenu, { children: [/* @__PURE__ */ jsx(DropdownMenuTrigger, {
787
+ variant: "ghost",
788
+ size: "icon",
789
+ accessibilityLabel: t("fileEdit.ui.fileActions", "file actions"),
790
+ children: /* @__PURE__ */ jsx(KebabIcon, {})
791
+ }), /* @__PURE__ */ jsxs(DropdownMenuContent, { children: [
792
+ /* @__PURE__ */ jsx(DropdownMenuItem, {
793
+ disabled: sessionId === null || outside || busy || !props.nativeSaveFile,
794
+ onSelect: () => void download(),
795
+ children: t("fileEdit.ui.download", "download")
796
+ }),
797
+ busy ? /* @__PURE__ */ jsx(DropdownMenuItem, {
798
+ onSelect: () => downloadController.current?.abort(),
799
+ children: t("fileEdit.ui.cancelDownload", "cancel download")
800
+ }) : null,
801
+ /* @__PURE__ */ jsx(DropdownMenuItem, {
802
+ disabled: !writable,
803
+ onSelect: () => setView("edit"),
804
+ children: t("fileEdit.ui.edit", "edit")
805
+ }),
806
+ /* @__PURE__ */ jsx(DropdownMenuItem, {
807
+ variant: "destructive",
808
+ disabled: !writable,
809
+ onSelect: () => setConfirmingDelete(true),
810
+ children: t("fileEdit.ui.delete", "delete")
811
+ }),
812
+ /* @__PURE__ */ jsx(DropdownMenuItem, {
813
+ onSelect: () => closeTransientTab(fileTabId(filePath)),
814
+ children: t("fileEdit.ui.close", "close")
815
+ })
816
+ ] })] })]
817
+ }),
818
+ failure ? /* @__PURE__ */ jsx(EmptyState, {
819
+ size: "compact",
820
+ surface: "plain",
821
+ tone: "error",
822
+ title: failure.title,
823
+ description: failure.message,
824
+ action: {
825
+ label: t("fileEdit.ui.tryAgain", "Try again"),
826
+ onAction: failure.retry,
827
+ loading: busy
828
+ }
829
+ }) : view !== "edit" && note === "saved" ? /* @__PURE__ */ jsx(Text, {
830
+ style: styles$1.success,
831
+ children: t("fileEdit.ui.saved", "saved")
832
+ }) : null,
833
+ /* @__PURE__ */ jsx(SegmentedControl, {
834
+ accessibilityLabel: t("fileEdit.ui.fileView", "file view"),
835
+ options: [{
836
+ value: "preview",
837
+ get label() {
838
+ return t("fileEdit.ui.preview", "preview");
839
+ }
840
+ }, {
841
+ value: "diff",
842
+ get label() {
843
+ return t("fileEdit.ui.diff", "diff");
844
+ }
845
+ }],
846
+ value: view,
847
+ onValueChange: setView
848
+ }),
849
+ view === "edit" ? /* @__PURE__ */ jsx(Text, {
850
+ style: styles$1.meta,
851
+ children: t("fileEdit.ui.editing", "editing")
852
+ }) : null,
853
+ loading && !detail ? /* @__PURE__ */ jsx(Text, {
854
+ style: styles$1.meta,
855
+ children: t("fileEdit.ui.readingThisFileSHistory", "reading this file's history…")
856
+ }) : null,
857
+ error ? /* @__PURE__ */ jsx(EmptyState, {
858
+ tone: "error",
859
+ title: t("fileEdit.ui.historyFailed", "Couldn't load this file"),
860
+ description: error,
861
+ action: {
862
+ label: t("fileEdit.ui.tryAgain", "Try again"),
863
+ onAction: () => setAttempt((value) => value + 1),
864
+ loading
865
+ }
866
+ }) : null,
867
+ detail ? view === "diff" ? /* @__PURE__ */ jsxs(Fragment, { children: [
868
+ /* @__PURE__ */ jsxs(Text, {
869
+ style: styles$1.meta,
870
+ children: [
871
+ "+",
872
+ detail.cumulative.additions,
873
+ " -",
874
+ detail.cumulative.removals
875
+ ]
876
+ }),
877
+ detail.cumulative.note ? /* @__PURE__ */ jsx(Text, {
878
+ style: styles$1.meta,
879
+ children: detail.cumulative.note
880
+ }) : null,
881
+ detail.cumulative.hunks ? /* @__PURE__ */ jsx(FileDiff, {
882
+ hunks: detail.cumulative.hunks,
883
+ comment: setDraft
884
+ }, `${sessionId}:${filePath}`) : null,
885
+ /* @__PURE__ */ jsx(Text, {
886
+ style: styles$1.title,
887
+ children: t("fileEdit.ui.value1ChangesThisSession", "{value1} changes this session", { value1: detail.versions.length })
888
+ }),
889
+ detail.versions.map((version) => /* @__PURE__ */ jsxs(View, { children: [/* @__PURE__ */ jsxs(Button, {
890
+ variant: "ghost",
891
+ accessibilityState: { expanded: expanded === version.index },
892
+ onPress: () => setExpanded(expanded === version.index ? void 0 : version.index),
893
+ children: [
894
+ "#",
895
+ version.index,
896
+ " ",
897
+ t(`fileEdit.ui.tool.${version.tool}`, version.tool),
898
+ " +",
899
+ version.additions,
900
+ " -",
901
+ version.removals,
902
+ version.origin === "scan" ? ` · ${t("fileEdit.ui.noBaseline", "no baseline")}` : ""
903
+ ]
904
+ }), expanded === version.index ? version.hunks ? /* @__PURE__ */ jsx(FileDiff, {
905
+ hunks: version.hunks,
906
+ comment: setDraft
907
+ }, `${sessionId}:${filePath}`) : /* @__PURE__ */ jsx(Text, {
908
+ style: styles$1.meta,
909
+ children: version.note ?? t("fileEdit.ui.nothingToShow", "nothing to show")
910
+ }) : null] }, version.index))
911
+ ] }) : view === "edit" ? /* @__PURE__ */ jsxs(Fragment, { children: [writable ? /* @__PURE__ */ jsxs(Fragment, { children: [
912
+ /* @__PURE__ */ jsx(Textarea, {
913
+ accessibilityLabel: t("fileEdit.ui.fileSource", "file source"),
914
+ value: source ?? working?.content ?? "",
915
+ onChangeText: setSource,
916
+ rows: 12,
917
+ onSelectionChange: (event) => {
918
+ const content = source ?? working?.content ?? "";
919
+ const { start, end } = event.nativeEvent.selection;
920
+ setSelection(end > start ? {
921
+ snippet: content.slice(start, end),
922
+ startLine: content.slice(0, start).split("\n").length,
923
+ endLine: content.slice(0, end).split("\n").length
924
+ } : void 0);
925
+ }
926
+ }),
927
+ /* @__PURE__ */ jsxs(View, {
928
+ style: styles$1.actions,
929
+ children: [/* @__PURE__ */ jsx(Button, {
930
+ variant: "primary",
931
+ disabled: source === void 0 || busy,
932
+ onPress: () => void save(),
933
+ children: t("fileEdit.ui.saveToDisk", "save to disk")
934
+ }), /* @__PURE__ */ jsx(Button, {
935
+ variant: "ghost",
936
+ disabled: source === void 0,
937
+ onPress: () => setSource(void 0),
938
+ children: t("fileEdit.ui.discardEdits", "discard edits")
939
+ })]
940
+ }),
941
+ /* @__PURE__ */ jsx(Button, {
942
+ variant: "ghost",
943
+ disabled: !selection,
944
+ onPress: () => setDraft(selection),
945
+ children: t("fileEdit.ui.commentOnSelection", "comment on selection")
946
+ })
947
+ ] }) : /* @__PURE__ */ jsx(Text, {
948
+ style: styles$1.meta,
949
+ children: working?.reason ?? t("fileEdit.ui.thisFileCannotBeEdited", "this file cannot be edited")
950
+ }), note === "saved" ? /* @__PURE__ */ jsx(Text, {
951
+ style: styles$1.success,
952
+ children: t("fileEdit.ui.saved", "saved")
953
+ }) : null] }) : working ? /* @__PURE__ */ jsx(FilePreview, {
954
+ ...props,
955
+ path: relPath,
956
+ working: {
957
+ ...working,
958
+ content: source ?? working.content
959
+ }
960
+ }) : null : null,
961
+ detail && sessionId !== null ? /* @__PURE__ */ jsx(Button, {
962
+ variant: "ghost",
963
+ onPress: () => setDraft({ snippet: "" }),
964
+ children: t("fileEdit.ui.addReviewComment", "add review comment")
965
+ }) : null,
966
+ comments.length ? /* @__PURE__ */ jsxs(View, {
967
+ style: styles$1.diff,
968
+ children: [
969
+ /* @__PURE__ */ jsx(Button, {
970
+ variant: "outline",
971
+ disabled: sessionId === null,
972
+ onPress: sendReview,
973
+ children: t("fileEdit.ui.sendReviewValue1", "send review ({value1})", { value1: comments.length })
974
+ }),
975
+ reviewError ? /* @__PURE__ */ jsx(EmptyState, {
976
+ size: "compact",
977
+ surface: "plain",
978
+ tone: "error",
979
+ title: t("fileEdit.ui.reviewNotSent", "Couldn't send the review"),
980
+ description: reviewError,
981
+ action: {
982
+ label: t("fileEdit.ui.tryAgain", "Try again"),
983
+ onAction: sendReview
984
+ }
985
+ }) : null,
986
+ comments.map((comment) => /* @__PURE__ */ jsxs(View, { children: [/* @__PURE__ */ jsxs(Text, {
987
+ style: styles$1.meta,
988
+ children: [
989
+ comment.relPath,
990
+ comment.startLine === void 0 ? "" : `:${comment.startLine}`,
991
+ " · ",
992
+ comment.body
993
+ ]
994
+ }), /* @__PURE__ */ jsx(Button, {
995
+ variant: "ghost",
996
+ onPress: () => {
997
+ if (sessionId !== null) removeComment(sessionId, comment.id);
998
+ },
999
+ children: t("fileEdit.ui.removeComment", "remove comment")
1000
+ })] }, comment.id))
1001
+ ]
1002
+ }) : null,
1003
+ draft ? /* @__PURE__ */ jsx(ReviewSheet, {
1004
+ selection: draft,
1005
+ close: () => setDraft(void 0),
1006
+ submit: (body, snippet) => {
1007
+ if (sessionId !== null) addComment(sessionId, {
1008
+ id: `${filePath}:${draft.side ?? "new"}:${draft.startLine ?? 0}:${comments.length}:${body.length}`,
1009
+ path: filePath,
1010
+ relPath,
1011
+ ...draft,
1012
+ snippet,
1013
+ body
1014
+ });
1015
+ setDraft(void 0);
1016
+ }
1017
+ }) : null,
1018
+ confirmingDelete ? /* @__PURE__ */ jsx(Sheet, {
1019
+ open: true,
1020
+ onOpenChange: (open) => {
1021
+ if (!open) setConfirmingDelete(false);
1022
+ },
1023
+ children: /* @__PURE__ */ jsxs(SheetContent, { children: [/* @__PURE__ */ jsx(SheetHeader, { children: /* @__PURE__ */ jsx(SheetTitle, { children: t("fileEdit.ui.deleteFile", "delete file") }) }), /* @__PURE__ */ jsxs(SheetBody, { children: [/* @__PURE__ */ jsx(Text, {
1024
+ style: styles$1.meta,
1025
+ children: t("fileEdit.ui.thisRemovesValue1FromDiskItCannotBeUndoneHere", "This removes {value1} from disk. It cannot be undone here.", { value1: relPath })
1026
+ }), /* @__PURE__ */ jsxs(View, {
1027
+ style: styles$1.actions,
1028
+ children: [/* @__PURE__ */ jsx(Button, {
1029
+ variant: "ghost",
1030
+ onPress: () => setConfirmingDelete(false),
1031
+ children: t("fileEdit.ui.cancel", "cancel")
1032
+ }), /* @__PURE__ */ jsx(Button, {
1033
+ variant: "danger",
1034
+ disabled: !writable || busy,
1035
+ onPress: () => void remove(),
1036
+ children: t("fileEdit.ui.delete", "delete")
1037
+ })]
1038
+ })] })] })
1039
+ }) : null
1040
+ ]
1041
+ });
1042
+ }
1043
+ function fileTab(filePath, relPath) {
1044
+ return {
1045
+ id: fileTabId(filePath),
1046
+ label: relPath.split("/").at(-1) ?? relPath,
1047
+ panel: (props) => /* @__PURE__ */ jsx(FilePanel, {
1048
+ ...props,
1049
+ filePath,
1050
+ relPath
1051
+ })
1052
+ };
1053
+ }
1054
+ const styles$1 = StyleSheet.create((theme) => ({
1055
+ panel: {
1056
+ padding: theme.spacing(4),
1057
+ gap: theme.spacing(3),
1058
+ uni__dependencies: [0]
1059
+ },
1060
+ header: {
1061
+ flexDirection: "row",
1062
+ alignItems: "center",
1063
+ gap: theme.spacing(2),
1064
+ uni__dependencies: [0]
1065
+ },
1066
+ actions: {
1067
+ flexDirection: "row",
1068
+ flexWrap: "wrap",
1069
+ gap: theme.spacing(2),
1070
+ uni__dependencies: [0]
1071
+ },
1072
+ diff: {
1073
+ gap: theme.spacing(2),
1074
+ uni__dependencies: [0]
1075
+ },
1076
+ title: {
1077
+ fontSize: theme.fontSize.base,
1078
+ fontWeight: "600",
1079
+ color: theme.colors.hi,
1080
+ uni__dependencies: [0]
1081
+ },
1082
+ path: {
1083
+ flex: 1,
1084
+ fontFamily: fontOf(theme.fontFamily.mono),
1085
+ fontSize: theme.fontSize.base,
1086
+ color: theme.colors.hi,
1087
+ uni__dependencies: [0]
1088
+ },
1089
+ meta: {
1090
+ fontSize: theme.fontSize.sm,
1091
+ color: theme.colors.dim,
1092
+ uni__dependencies: [0]
1093
+ },
1094
+ success: {
1095
+ fontSize: theme.fontSize.sm,
1096
+ color: theme.colors.green,
1097
+ uni__dependencies: [0]
1098
+ }
1099
+ }));
1100
+ //#endregion
1101
+ //#region src/extensions/workspaces/sessions/(frontend)/file-links/_components/FilePreviewPanel.native.tsx
1102
+ const HostCopyButton = CopyButton;
1103
+ /** What the subtitle calls a file, from its extension; the same words as the artifacts preview. */
1104
+ function fileKind(path) {
1105
+ const extension = path.split(".").at(-1)?.toLowerCase() ?? "";
1106
+ if (extension === "md" || extension === "markdown") return "Markdown";
1107
+ if (extension === "html" || extension === "htm") return "HTML";
1108
+ if (isMediaPath(path)) return "Media";
1109
+ return extension === "" || extension === path.toLowerCase() ? "Text" : extension.toUpperCase();
1110
+ }
1111
+ /**
1112
+ * An unchanged file, read-only, laid out as the artifacts preview: what it is and its one action in
1113
+ * the top bar, the content padded below, and where it lives pinned at the bottom. Unchanged files are
1114
+ * admitted only by the package's guarded preview route.
1115
+ */
1116
+ function FilePreviewPanel({ filePath, ...props }) {
1117
+ const t = useT();
1118
+ const [loaded, setLoaded] = useState();
1119
+ const [attempt, setAttempt] = useState(0);
1120
+ useEffect(() => {
1121
+ if (props.sessionId === null) return;
1122
+ const sessionId = props.sessionId;
1123
+ let cancelled = false;
1124
+ fetchFilePreview(sessionId, filePath).then((result) => {
1125
+ if (!cancelled) setLoaded(result.ok ? {
1126
+ sessionId,
1127
+ path: filePath,
1128
+ preview: result.preview,
1129
+ attempt
1130
+ } : {
1131
+ sessionId,
1132
+ path: filePath,
1133
+ error: result.error,
1134
+ denied: result.status === 403,
1135
+ attempt
1136
+ });
1137
+ }).catch((failure) => {
1138
+ if (!cancelled) setLoaded({
1139
+ sessionId,
1140
+ path: filePath,
1141
+ error: failure instanceof Error ? failure.message : String(failure),
1142
+ attempt
1143
+ });
1144
+ });
1145
+ return () => {
1146
+ cancelled = true;
1147
+ };
1148
+ }, [
1149
+ props.sessionId,
1150
+ filePath,
1151
+ attempt
1152
+ ]);
1153
+ const current = loaded?.path === filePath && loaded.sessionId === props.sessionId ? loaded : void 0;
1154
+ const controller = useRef(void 0);
1155
+ const [saving, setSaving] = useState(false);
1156
+ const [note, setNote] = useState();
1157
+ const [saveFailed, setSaveFailed] = useState();
1158
+ useEffect(() => () => controller.current?.abort(), [props.sessionId, filePath]);
1159
+ const save = async () => {
1160
+ if (props.sessionId === null || !props.nativeSaveFile || controller.current) return;
1161
+ const active = new AbortController();
1162
+ controller.current = active;
1163
+ setSaving(true);
1164
+ setNote(void 0);
1165
+ try {
1166
+ await props.nativeSaveFile(await prepareFileSave(props.sessionId, filePath, active.signal));
1167
+ if (!active.signal.aborted) {
1168
+ setSaveFailed(void 0);
1169
+ setNote(t("fileEdit.ui.downloadSaved", "Saved."));
1170
+ }
1171
+ } catch (error) {
1172
+ if (!active.signal.aborted) setSaveFailed(error instanceof Error ? error.message : String(error));
1173
+ } finally {
1174
+ if (controller.current === active) controller.current = void 0;
1175
+ setSaving(false);
1176
+ }
1177
+ };
1178
+ const cancel = () => {
1179
+ controller.current?.abort();
1180
+ controller.current = void 0;
1181
+ setSaving(false);
1182
+ setSaveFailed(void 0);
1183
+ setNote(t("fileEdit.ui.downloadCancelled", "Download cancelled."));
1184
+ };
1185
+ const handlers = useRef({
1186
+ save,
1187
+ cancel
1188
+ });
1189
+ useEffect(() => {
1190
+ handlers.current = {
1191
+ save,
1192
+ cancel
1193
+ };
1194
+ });
1195
+ const { setTabHeader } = props;
1196
+ const canSave = props.nativeSaveFile !== void 0;
1197
+ const offline = props.sessionId === null;
1198
+ const media = isMediaPath(filePath) && props.renderMediaPreview !== void 0;
1199
+ const subtitle = `${fileKind(filePath)} · Unchanged`;
1200
+ useEffect(() => {
1201
+ if (!setTabHeader || media) return;
1202
+ setTabHeader({
1203
+ subtitle,
1204
+ action: canSave ? /* @__PURE__ */ jsx(Button, {
1205
+ variant: "ghost",
1206
+ size: "icon",
1207
+ disabled: offline,
1208
+ accessibilityLabel: saving ? t("fileEdit.ui.cancelDownloadAction", "Cancel download") : t("fileEdit.ui.downloadAction", "Download"),
1209
+ onPress: () => saving ? handlers.current.cancel() : void handlers.current.save(),
1210
+ children: saving ? /* @__PURE__ */ jsx(CloseIcon, { color: "hi" }) : /* @__PURE__ */ jsx(DownloadIcon, { color: "hi" })
1211
+ }) : void 0
1212
+ });
1213
+ }, [
1214
+ setTabHeader,
1215
+ media,
1216
+ subtitle,
1217
+ canSave,
1218
+ saving,
1219
+ offline,
1220
+ t
1221
+ ]);
1222
+ const relPath = current?.preview?.relPath ?? filePath;
1223
+ const retrying = current !== void 0 && current.attempt !== attempt;
1224
+ const body = offline ? /* @__PURE__ */ jsx(EmptyState, { title: t("fileEdit.ui.theSessionIsUnavailable", "The session is unavailable.") }) : current?.error && current.denied ? /* @__PURE__ */ jsx(EmptyState, {
1225
+ icon: /* @__PURE__ */ jsx(LockIcon, { size: 20 }),
1226
+ title: t("fileEdit.ui.previewDenied", "This file can't be opened here"),
1227
+ description: current.error
1228
+ }) : current?.error ? /* @__PURE__ */ jsx(EmptyState, {
1229
+ tone: "error",
1230
+ title: t("fileEdit.ui.previewFailed", "Couldn't load this file"),
1231
+ description: current.error,
1232
+ action: {
1233
+ label: t("fileEdit.ui.tryAgain", "Try again"),
1234
+ onAction: () => setAttempt((value) => value + 1),
1235
+ loading: retrying
1236
+ }
1237
+ }) : current?.preview ? /* @__PURE__ */ jsx(FilePreview, {
1238
+ ...props,
1239
+ path: current.preview.relPath,
1240
+ working: current.preview.working
1241
+ }) : /* @__PURE__ */ jsx(Text, {
1242
+ style: styles.meta,
1243
+ children: t("fileEdit.ui.readingThisFilePreview", "Reading this file...")
1244
+ });
1245
+ return /* @__PURE__ */ jsxs(View, {
1246
+ style: styles.screen,
1247
+ children: [media ? /* @__PURE__ */ jsx(View, {
1248
+ style: styles.stage,
1249
+ children: body
1250
+ }) : /* @__PURE__ */ jsxs(ScrollView, {
1251
+ style: styles.stage,
1252
+ contentContainerStyle: styles.content,
1253
+ children: [
1254
+ setTabHeader ? null : /* @__PURE__ */ jsxs(View, {
1255
+ style: styles.header,
1256
+ children: [
1257
+ /* @__PURE__ */ jsx(Text, {
1258
+ style: [styles.meta, styles.headerLabel],
1259
+ children: subtitle
1260
+ }),
1261
+ canSave && saving ? /* @__PURE__ */ jsx(Button, {
1262
+ variant: "ghost",
1263
+ size: "sm",
1264
+ onPress: cancel,
1265
+ children: t("fileEdit.ui.cancelAction", "Cancel")
1266
+ }) : null,
1267
+ canSave ? /* @__PURE__ */ jsx(Button, {
1268
+ variant: "outline",
1269
+ size: "sm",
1270
+ disabled: saving || offline,
1271
+ onPress: () => void save(),
1272
+ children: t("fileEdit.ui.downloadAction", "Download")
1273
+ }) : null
1274
+ ]
1275
+ }),
1276
+ saveFailed ? /* @__PURE__ */ jsx(EmptyState, {
1277
+ size: "compact",
1278
+ surface: "plain",
1279
+ tone: "error",
1280
+ title: t("fileEdit.ui.saveFailed", "Couldn't save this file"),
1281
+ description: saveFailed,
1282
+ action: {
1283
+ label: t("fileEdit.ui.tryAgain", "Try again"),
1284
+ onAction: () => void save(),
1285
+ loading: saving
1286
+ }
1287
+ }) : note ? /* @__PURE__ */ jsx(Text, {
1288
+ accessibilityLiveRegion: "polite",
1289
+ style: styles.meta,
1290
+ children: note
1291
+ }) : null,
1292
+ body
1293
+ ]
1294
+ }), /* @__PURE__ */ jsxs(View, {
1295
+ style: styles.strip,
1296
+ children: [/* @__PURE__ */ jsx(Text, {
1297
+ selectable: true,
1298
+ numberOfLines: 1,
1299
+ ellipsizeMode: "middle",
1300
+ style: [styles.path, styles.stripPath],
1301
+ children: relPath
1302
+ }), HostCopyButton ? /* @__PURE__ */ jsx(HostCopyButton, {
1303
+ text: relPath,
1304
+ label: t("fileEdit.ui.path", "path")
1305
+ }) : null]
1306
+ })]
1307
+ });
1308
+ }
1309
+ function filePreviewTab(filePath) {
1310
+ return {
1311
+ id: `${fileTabId(filePath)}-preview`,
1312
+ label: filePath.split("/").at(-1) ?? filePath,
1313
+ panel: (props) => /* @__PURE__ */ jsx(FilePreviewPanel, {
1314
+ ...props,
1315
+ filePath
1316
+ })
1317
+ };
1318
+ }
1319
+ const styles = StyleSheet.create((theme, rt) => ({
1320
+ screen: { flex: 1 },
1321
+ stage: { flex: 1 },
1322
+ content: {
1323
+ padding: theme.spacing(4),
1324
+ gap: theme.spacing(3),
1325
+ uni__dependencies: [0]
1326
+ },
1327
+ header: {
1328
+ flexDirection: "row",
1329
+ alignItems: "center",
1330
+ gap: theme.spacing(2),
1331
+ paddingBottom: theme.spacing(3),
1332
+ borderBottomWidth: 1,
1333
+ borderBottomColor: theme.colors["border-soft"],
1334
+ uni__dependencies: [0]
1335
+ },
1336
+ headerLabel: { flex: 1 },
1337
+ strip: {
1338
+ flexDirection: "row",
1339
+ alignItems: "center",
1340
+ gap: theme.spacing(2),
1341
+ paddingHorizontal: theme.spacing(4),
1342
+ paddingTop: theme.spacing(2),
1343
+ paddingBottom: theme.spacing(2) + rt.insets.bottom,
1344
+ borderTopWidth: 1,
1345
+ borderTopColor: theme.colors["border-soft"],
1346
+ backgroundColor: theme.colors.bg,
1347
+ uni__dependencies: [0, 9]
1348
+ },
1349
+ stripPath: { flexShrink: 1 },
1350
+ path: {
1351
+ fontFamily: fontOf(theme.fontFamily.mono),
1352
+ fontSize: theme.fontSize.sm,
1353
+ color: theme.colors.dim,
1354
+ uni__dependencies: [0]
1355
+ },
1356
+ meta: {
1357
+ fontFamily: fontOf(theme.fontFamily.sans),
1358
+ fontSize: theme.fontSize.sm,
1359
+ color: theme.colors.dim,
1360
+ uni__dependencies: [0]
1361
+ }
1362
+ }));
1363
+ //#endregion
1364
+ //#region src/extensions/workspaces/sessions/(frontend)/file-links/_lib/fileLinks.native.ts
1365
+ /**
1366
+ * The files a message names, as links into the same tab the activity dock
1367
+ * opens.
1368
+ *
1369
+ * Only files this session recorded a change to are claimed. A message quotes a
1370
+ * great deal that is shaped like nothing in particular, class names and globs
1371
+ * and flags among it, and guessing at what is a path produces links that open
1372
+ * an error. The recorded set is the one thing the page knows for certain, and
1373
+ * it is also the set a reader is most likely to want open.
1374
+ */
1375
+ /** A reference the way a message writes one: 'src/app.ts:42' or 'src/app.ts:42:9'. */
1376
+ const LINE_SUFFIX = /:\d+(?::\d+)?$/;
1377
+ function itemsFor(sessionId) {
1378
+ return files.select(files.store.state, sessionId).items;
1379
+ }
1380
+ function match(sessionId, path) {
1381
+ const candidate = path.trim().replace(LINE_SUFFIX, "");
1382
+ if (candidate === "") return void 0;
1383
+ return itemsFor(sessionId).find((item) => item.relPath === candidate || item.path === candidate);
1384
+ }
1385
+ //#endregion
1386
+ //#region src/extensions/workspaces/sessions/(frontend)/file-links/files.native.ts
1387
+ var files_native_default = defineFileLinks({
1388
+ subscribe(listener) {
1389
+ const subscription = files.store.subscribe(listener);
1390
+ return () => subscription.unsubscribe();
1391
+ },
1392
+ fingerprint: (sessionId) => itemsFor(sessionId).map((item) => item.relPath).join("\n"),
1393
+ resolve: (sessionId, path) => {
1394
+ const item = match(sessionId, path);
1395
+ return item === void 0 ? void 0 : fileTab(item.path, item.relPath);
1396
+ },
1397
+ openPath: (sessionId, path) => {
1398
+ const item = match(sessionId, path);
1399
+ if (item !== void 0) return fileTab(item.path, item.relPath);
1400
+ const candidate = path.trim();
1401
+ return candidate === "" ? void 0 : filePreviewTab(candidate);
1402
+ }
1403
+ });
1404
+ //#endregion
1405
+ //#region src/extensions/workspaces/sessions/(frontend)/fill/Filechanges.help.guides.native.ts
1406
+ var Filechanges_help_guides_native_default = defineFill({
1407
+ slot: "help.guides",
1408
+ id: "Filechanges",
1409
+ order: 120,
1410
+ data: {
1411
+ version: 1,
1412
+ category: "files",
1413
+ labelKey: "fileEdit.guides.fileChanges",
1414
+ label: "File changes",
1415
+ guides: [{
1416
+ id: "about",
1417
+ questionKey: "fileEdit.guides.whatFileChangesAreTracked",
1418
+ question: "What file changes are tracked?",
1419
+ order: 0,
1420
+ answerKey: "fileEdit.guides.fileChangesRecordsFilesChangedThroughSessionToolsAndCapturesContentForDiffsWithoutRequiringGitBinaryFilesAndContentAbove1MiBAreListedWithoutCapturedContent",
1421
+ answer: "File changes records files changed through session tools and captures content for diffs without requiring Git. Binary files and content above 1 MiB are listed without captured content.",
1422
+ keywords: ["diff", "tracking"]
1423
+ }, {
1424
+ id: "use",
1425
+ questionKey: "fileEdit.guides.howDoIReviewFileChanges",
1426
+ question: "How do I review file changes?",
1427
+ order: 1,
1428
+ answerKey: "fileEdit.guides.selectAFileInTheActivityDockToOpenItsTabAndInspectTheDiffOrPreviewSelectTextToAddCommentsThenChooseSendReviewToSendTheQueuedCommentsTogether",
1429
+ answer: "Select a file in the activity dock to open its tab and inspect the diff or preview. Select text to add comments, then choose send review to send the queued comments together.",
1430
+ keywords: ["comments", "review"]
1431
+ }]
1432
+ }
1433
+ });
1434
+ //#endregion
37
1435
  //#region generated/native.ts
38
- const via = (identity, value) => value === void 0 ? void 0 : {
39
- ...identity,
40
- ...value
1436
+ const via = (identity, value) => {
1437
+ if (value === void 0) return void 0;
1438
+ const declaration = value;
1439
+ return {
1440
+ ...identity,
1441
+ ...declaration,
1442
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
1443
+ evidence: "declared",
1444
+ ...relation
1445
+ })) }
1446
+ };
41
1447
  };
42
1448
  const nativePlugin = defineNativePlugin({
43
1449
  id: "files",
44
- session: { get channels() {
45
- return [via({ channel: "file_edits" }, file_edits_native_default)];
46
- } }
1450
+ packageName: "@agimon-ai/po-file-edit",
1451
+ session: {
1452
+ get channels() {
1453
+ return [via({ channel: "file_edits" }, file_edits_native_default)];
1454
+ },
1455
+ get fileLinks() {
1456
+ return files_native_default;
1457
+ },
1458
+ get fills() {
1459
+ return [via({
1460
+ slot: "help.guides",
1461
+ id: "filechanges"
1462
+ }, Filechanges_help_guides_native_default)];
1463
+ }
1464
+ }
47
1465
  });
48
1466
  //#endregion
49
1467
  export { nativePlugin };