返回 DeepSeek-Reasonix
attachmentSubmit.ts
根目录 / desktop / frontend / src / lib / attachmentSubmit.ts
1 import type { AppBindings } from "./bridge";
2 import type { StructuredInvocationSubmit } from "./invocationDisplay";
3 import type { ComposerTarget } from "../generated/desktopContract.generated";
4 import type { WorkspaceReference } from "./composerDraftTypes";
5
6 export async function restoreExternalFolderReferences(app: AppBindings, target: ComposerTarget, refs: WorkspaceReference[]) {
7 const external = refs.filter(isExternalWorkspaceReference);
8 if (!external.length) return;
9 const token = await captureAttachmentTarget(app, target, ["AttachDroppedForTarget"]);
10 try {
11 for (const ref of external) {
12 if (!ref.displayPath) throw new Error("External folder source is unavailable; reattach the folder before sending");
13 const restored = await app.AttachDroppedForTarget!(token, ref.displayPath);
14 if (restored.kind !== "workspace" || Boolean(restored.isDir) !== Boolean(ref.isDir) || restored.path !== ref.path) {
15 throw new Error("External folder changed; reattach the folder before sending");
16 }
17 }
18 } finally { await app.ReleaseAttachmentTarget?.(token); }
19 }
20
21 export function isExternalWorkspaceReference(ref: WorkspaceReference): boolean {
22 return ref.path.startsWith("__reasonix_external_folder/") || Boolean(!ref.isDir && ref.displayPath && /^(?:\/|[a-zA-Z]:[\\/]|\\\\)/.test(ref.path));
23 }
24
25 const pendingImageSubmissions = new Map<string, { fingerprint: string; id: string }>();
26
27 // Native files remain path references; pathless files send a raw HTTP body.
28 export function attachmentUploadFailure(error: unknown, fallback: string, formatLimit?: (bytes: number) => string): string {
29 return isAttachmentUploadLimitError(error) ? formatLimit?.(error.limit_bytes) ?? error.message : fallback;
30 }
31
32 export function isAttachmentUploadLimitError(error: unknown): error is Error & { code: "attachment.too_large"; limit_bytes: number } {
33 return error instanceof Error && "code" in error && error.code === "attachment.too_large"
34 && "limit_bytes" in error && typeof error.limit_bytes === "number" && Number.isFinite(error.limit_bytes) && error.limit_bytes > 0;
35 }
36
37 export async function attachOrdinaryFile(
38 app: AppBindings, token: string, file: File,
39 getPathForFile?: (file: File) => string, fetcher: typeof fetch = fetch,
40 ): Promise<{ kind: string; path: string; isDir?: boolean; displayPath?: string }> {
41 const nativePath = getPathForFile?.(file);
42 if (nativePath) {
43 if (!app.AttachDroppedForTarget) throw new Error("unsupported: attachments-v2");
44 return app.AttachDroppedForTarget(token, nativePath);
45 }
46 const query = new URLSearchParams({ target: token, name: file.name });
47 const response = await fetcher(`/__reasonix_attachment_upload?${query}`, {
48 method: "POST", headers: { "content-type": "application/octet-stream" }, body: file,
49 });
50 if (!response.ok) {
51 const error: unknown = await response.json().catch(() => null);
52 if (error && typeof error === "object" && "code" in error && error.code === "attachment.too_large"
53 && "message" in error && typeof error.message === "string"
54 && "limit_bytes" in error && typeof error.limit_bytes === "number"
55 && "limit_source" in error && typeof error.limit_source === "string") {
56 throw Object.assign(new Error(error.message), { code: error.code, limit_bytes: error.limit_bytes, limit_source: error.limit_source });
57 }
58 throw new Error(`File upload failed (${response.status})`);
59 }
60 const value: unknown = await response.json();
61 if (!value || typeof value !== "object" || !("path" in value) || typeof value.path !== "string" || !value.path) {
62 throw new Error("File upload returned no attachment path");
63 }
64 return { kind: "attachment", path: value.path };
65 }
66
67 export function imageSubmissionIdentity(draft: string, fingerprint: string): string {
68 const previous = pendingImageSubmissions.get(draft);
69 if (previous?.fingerprint === fingerprint) return previous.id;
70 const id = `image-${crypto.randomUUID()}`;
71 pendingImageSubmissions.set(draft, { fingerprint, id });
72 return id;
73 }
74
75 export function settleImageSubmission(draft: string, id?: string): void {
76 if (pendingImageSubmissions.get(draft)?.id === id) pendingImageSubmissions.delete(draft);
77 }
78
79 export async function prepareImageSubmission(
80 app: AppBindings,
81 target: ComposerTarget,
82 draftKey: string,
83 fingerprint: string,
84 attachments: Array<{ draftId?: string; clientAttachmentId?: string; recoveryPath?: string; displayName?: string }>,
85 structured: StructuredInvocationSubmit | undefined,
86 display: string,
87 input: string,
88 ) {
89 const token = await captureImageTarget(app, target);
90 const submissionId = imageSubmissionIdentity(draftKey, fingerprint);
91 const restored = [];
92 try {
93 for (const [index, item] of attachments.entries()) {
94 let draftId = item.draftId;
95 if (!draftId && item.recoveryPath) {
96 if (!app.AttachmentDataURLForTarget || !app.StageImageForTarget) throw new Error("unsupported: attachments-v2");
97 const data = await app.AttachmentDataURLForTarget(token, item.recoveryPath);
98 const staged = await app.StageImageForTarget(token, `${submissionId}:restore:${index}`, item.displayName || "image", "", data);
99 draftId = staged.draftId;
100 }
101 if (!draftId) throw new Error("Image source is unavailable; reattach the image before sending");
102 restored.push({ clientAttachmentId: item.clientAttachmentId || `image-${index + 1}`, draftId });
103 }
104 } catch (error) {
105 await app.ReleaseAttachmentTarget?.(token).catch(() => {});
106 throw error;
107 }
108 return {
109 token,
110 submissionId,
111 structured: {
112 display: structured?.display ?? display,
113 input: structured?.input ?? input,
114 invocations: structured?.invocations ?? [],
115 attachmentTarget: token,
116 attachmentSubmissionId: submissionId,
117 attachments: restored,
118 } satisfies StructuredInvocationSubmit,
119 };
120 }
121
122 export function submitAttachmentTurn(app: AppBindings, submissionId: string, structured: StructuredInvocationSubmit, original: string, initialGoal?: { goal: string; toolApprovalMode?: string }) {
123 if (!app.StartTurnForAttachmentTarget || !structured.attachmentTarget) throw new Error("unsupported: attachments-v2");
124 return app.StartTurnForAttachmentTarget(structured.attachmentTarget, submissionId, {
125 input: structured.input, display: structured.display, original,
126 goal: initialGoal?.goal, toolApprovalMode: initialGoal?.toolApprovalMode,
127 invocations: structured.invocations, attachments: structured.attachments ?? [],
128 });
129 }
130
131 export function readFileAsDataURL(file: File): Promise<string> {
132 return new Promise((resolve, reject) => {
133 const reader = new FileReader();
134 reader.onload = () => resolve(String(reader.result));
135 reader.onerror = () => reject(reader.error);
136 reader.readAsDataURL(file);
137 });
138 }
139
140 export async function captureImageTarget(app: AppBindings, target: ComposerTarget): Promise<string> {
141 return captureAttachmentTarget(app, target, target.kind === "draft"
142 ? ["StageImageForTarget", "AttachmentDataURLForTarget"]
143 : ["StageImageForTarget", "ReadDraftImageForTarget"]);
144 }
145
146 export async function captureAttachmentTarget(
147 app: AppBindings,
148 target: ComposerTarget,
149 required: ReadonlyArray<keyof AppBindings>,
150 ): Promise<string> {
151 if (!app.CaptureAttachmentTarget || required.some((name) => typeof app[name] !== "function")) {
152 throw new Error("unsupported: attachments-v2");
153 }
154 const captured = await app.CaptureAttachmentTarget(target);
155 if (!captured.capabilities.includes("attachments-v2")) throw new Error("unsupported: attachments-v2");
156 return captured.token;
157 }
158
159 export async function stageImageFile(app: AppBindings, target: string, draftKey: string, file: File, persistentTarget?: ComposerTarget) {
160 const dataURL = await readFileAsDataURL(file);
161 const staged = await app.StageImageForTarget!(target, `${draftKey}:${file.name}:${file.lastModified}`, file.name, file.type, dataURL);
162 const path = staged.draftId ? `draft:${staged.draftId}` : staged.path;
163 if (!path) throw new Error("attachment staging returned no source");
164 const previewUrl = staged.draftId
165 ? await app.ReadDraftImageForTarget!(target, staged.draftId)
166 : await app.AttachmentDataURLForTarget!(target, path);
167 const recoveryPath = persistentTarget && staged.draftId ? await app.SavePastedImageForComposerTarget(persistentTarget, dataURL) : undefined;
168 return { path, previewUrl, displayName: file.name, draftId: staged.draftId || undefined, recoveryPath, file };
169 }
170
170 lines TYPESCRIPT